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><?php
include("track.class.php");
$track = new Trackingmore;
$track = $track->deleteTrackingItem('laposte','RK145199309FR');
?><file_sep><?php
include("track.class.php");
$track = new Trackingmore;
$track = $track->getSingleTrackingResult('laposte','RK152199309FR');
?> | ac46c2099d55391e21572ca17b0790e43929b971 | [
"PHP"
]
| 2 | PHP | clooney/laposte | 9a6820181656c717acfd8d5119e757ea97c2c0cb | 643063c7a83fe0eb4da076d48ff929b1153de193 |
refs/heads/main | <file_sep>#include <Arduino.h>
int incoming = 0;
int a[100] = {0};
int i = 0;
int max_a = 0;
bool incoming_data = false;
bool data_end = true;
int incomingbyte = 0;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
int value = 0;
String value_str = "";
while (Serial.available() > 0 || !data_end) {
data_end = false;
incoming_data = true;
value_str = Serial.readStringUntil('\n');
value = value_str.toInt();
Serial.print("value ");
Serial.println(value_str);
if (value_str[0] != 'e') {
a[i] = value;
++i;
}
else {
data_end = true; //end of data
}
}
max_a = i;
if (incoming_data) {
for(i = 0; i < max_a; i++) {
if (a[i] == 10) {
Serial.println(a[i]);
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
}
}
incoming_data = false;
i = 0;
}
}
| a11c4b11c087e285a2a17e83b790df69941b0ebf | [
"C++"
]
| 1 | C++ | ntd252/matlab-to-arduino | a5961a800d4f1b253e78097b0d8a5a16feaa4411 | 03362723ee9671b3ff49fd70370d6c1a402e3296 |
refs/heads/master | <file_sep>一个支持中英语言选择的小型四则运算程序。这个程序我使用的是Ç语言编写。主要有随机生成整数,然后对整数进行四则运算,支持判断答案是否正确,还有随机生成真分数进行四则运算的功能。很简单很实用。
这是一个经典的wc程序
一个经典的老游戏其规则是:N个同学每个报数(0~100间的有理数),交给裁判算出其平均值,然后乘0.618,得到G值最接近G值的得到N分最远的-2分,其他人0分。
<file_sep>#include <iostream>
#include<math.h>
using namespace std;
void main()
{
int i, j, num, N, M, S[100], S2[100], S3[100] = { 0 };
double S1[100], ave, sum, G;
double max, min;
cout << "==============欢迎进入黄金点游戏!============" << endl;
cout << "=============================================" << endl;
cout << "=====================v指南v==================" << endl;
cout << "===1.N个玩家(N通常大于10)进行游戏============" << endl;
cout << "===2.每人写一个0~100之间的有理数 (除0和100)==" << endl;
cout << "===3.G=N位玩家平均值*0.618===================" << endl;
cout << "===4.最高分(N): 提交数字最接近G值的玩家======" << endl;
cout << "===5.最低分(-2):提交数字距离G值最远的玩家====" << endl;
cout << "===6.其他分(0): 其他所有玩家=================" << endl;
cout << "Please input the number of your game!" << endl;
cin >> N;
cout << "The number of the person:" << endl;
cin >> M;
for (i = 1; i <= N; i++)
{
sum = 0;
G = 0;
cout << "Input the number between 1 to 100." << endl;
for (j = 1; j <= M; j++)
{
cout << " Player " << j << " input your choose!" << endl;
cin >> num;
S[j] = num;
sum = sum + S[j];
}
ave = sum / M;
G = ave*0.618;
cout << "黄金点是G=" << G << endl;
for (j = 1; j <= M; j++)
{
S1[j] = abs(S[j] - G);
}
max = min = S1[1];
for (j = 1; j <= M; j++)
{
if (S1[j] >= max)
max = S1[j];
else if (S1[j] < min)
min = S1[j];
}
for (j = 1; j <= M; j++)
{
if (S1[j] == max)
S2[j] = -2;
else if (S1[j] == min)
S2[j] = M;
else S2[j] = 0;
}
for (j = 1; j <= M; j++)
{
cout << "本轮分数" << "S2[" << j << "]=" << S2[j] << endl;
S3[j] = S3[j] + S2[j];
cout << "总分数 " << "S3[" << j << "]=" << S3[j] << endl;
}
}
system("pause");
}
1.项目介绍
黄金点游戏是一个小游戏,我们组的黄金点游戏设计简单,属于单机类游戏。主要针对的是人数较少的人群,操作简单,更易于比较各玩家的得分。
2.代码来源
http://www.cnblogs.com/zw2013040101034/p/5370302.html 是一位叫做张威的人写的
3.项目分析
我们的小游戏分几个阶段。首先是用户进入界面,在界面上我们很贴心的为每位新来的玩家设置了指南,游戏规则以及游戏得分算法。接下来就是设置的游戏轮数玩家可以选择需要进行的游戏场数。在选择好场数以后就是游戏的人数,可以是10以内也可以是10以外。然后每位玩家输入自己想输入的数字,但我们仅支持整数,最后全部的得分以及本轮得分都由算法完成。玩家就只需要等待数秒就能知道自己的得分。
4.bug排查
在拿到这个代码的时候我们测试是没有问题的,但是当我们进行游戏测试时发现,我们自己计算的黄金点跟计算机计算的黄金点不一样,并且差距较大。后来我们检查代码时发现,算法出错。原始代码在计算G值时把第二次玩家输入的数字当做了总人数,导致平均数计算出错。我们修改了代码,添加了玩家人数M当做平均数的分母。接下来代码运行也成功了,黄金点跟我们计算的值一样。项目基本完成。
5.项目扩展
对于这个代码的扩展,我认为我们可以在游戏进入时加上玩家name输入,也可以在最后游戏结束时添加恭喜xxx胜利.......
6.游戏某些部分介绍
开始时我对游戏里计算出来的本轮得分和总得分不是很懂。我以为出错了,后来当我仔细看了代码后发现,本轮得分指的是当前这次游戏的得分,而总得分更是关于所有轮次的得分。
<file_sep> 首先是添加单词,下面是代码://先记录单词,在运用指针指向他
void addWord(char *w1) //添加单词
{
link *p1,*p2;
//if(w1[0] <= 'Z' && w1[0] >= 'A') //转成小写字母
//{
// w1[0]+=32;
//}
for(p1=head;p1!=NULL;p1=p1->next) //判断单词在连表中是否存在
{
if(!strcmp(p1->w,w1))
{
p1->count++; //存在就个数加1
return;
}
}
p1=(struct word *)malloc(sizeof(word));//不存在添加新单词
strcpy(p1->w,w1);
p1->count=1;
p1->next=NULL;
count++; //总的单词数加加
if(head==NULL)
{
head=p1;
}
else
{
for(p2=head;p2->next!=NULL;p2=p2->next);
p2->next=p1;
}
}
然后判断指向的是是不是字符或是其他
int isnotWord(char a) //判断是否为字母
{
if(a <= 'z' && a >= 'a')
{
littleletter++;
return 0;
}
else if(a <= 'Z' && a >= 'A')
{
bigletter++;
return 0;
}
else if(a==' ')
{
space++;
return 1;
}
else if(a>='1'&&a<='9')
{
number++;
return 1;
}
else if(a=='\n')
{
hang_num++;
return 1;
}
else
{
other++;
return 1;
}
}
统计单词个数:
#include <iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
//统计单词的个数
int main()
{
char a;
int count=0;
while((a=getchar())!='\n')
{
if(a==' ')
count++;
}
cout << count+1 << endl;
return 0;
}
| 31c7e669c6674ee637c3e0852c8716bf22598c02 | [
"Markdown",
"C"
]
| 3 | Markdown | TalosLin/QTL | 55cc87a9f406d3b4708f08112b93c08f3e233a25 | fda41c3583952ff547ad1c05ae7fcbd88b0bedef |
refs/heads/master | <file_sep>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
//---------------------------EXP1: Developer App----------------------------------------
app.put("/developer/:index", function (req, res) {
var idx = req.params.index;
developers[idx] = req.body;
res.json(developers);
});
app.get("/developer", function (req, res) {
res.json(developers);
});
app.get("/developer/:index", function (req, res) {
var idx = req.params.index;
res.json(developers[idx]);
});
app.delete("/developer/:index", function (req, res) {
var idx = req.params.index;
developers.splice(idx, 1);
res.json(developers);
});
app.post("/developer", function (req, res) {
var obj = req.body;
developers.push(obj);
res.json(developers);
});
var developers = [
{ name: "alice", lang: "java", experience: "2 years" },
{ name: "abc", lang: "c", experience: "5 years" },
{ name: "xyz", lang: "c++", experience: "4 years" },
{ name: "pqr", lang: "python", experience: "1 years" },
{ name: "def", lang: "javascript", experience: "1 years" },
{ name: "hij", lang: "nodejs", experience: "0.5 years" },
]
//----------------------------------------------------EXP-2: User Login------------------------------------------------
var users = [
{ username: "isha", password: "<PASSWORD>", email: "<EMAIL>", firstName: "Isha", lastName: "Shah", photo: "" },
{ username: "admin", password: "<PASSWORD>", email: "<EMAIL>", firstName: "Admin", lastName: "Admin", photo: "" }
];
app.post('/login', function (req, res) {
var username = req.body.username;
var password = req.body.password;
var currentUser = null;
for (var index in users) {
if (users[index].username == username && users[index].password == password) {
currentUser = users[index];
}
}
res.json(currentUser);
});
//-----------------------------------------------EXP-3: User Profile Edit---------------------------------------------------
app.post('/update', function (req, res) {
var user = req.body;
var currentUser = null;
for (var index in users) {
if (users[index].username == user.username) {
users[index].firstName = user.firstName;
users[index].lastName = user.lastName;
users[index].email = user.email;
users[index].password = <PASSWORD>;
users[index].photo = user.photo;
currentUser = users[index];
}
}
res.json(currentUser);
});
//-----------------------------------------------------EXP-4: Upload Photo----------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------
var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
app.listen(port, ip);<file_sep>$("#rateit5").bind("click", function () {
alert("clicked");
$('#value5').text('You\'ve rated it: ' + value);
});
$("#rateit5").bind('reset', function () {
$('#value5').text('Rating reset');
});<file_sep>$(function () {
$("#srch").bind("click", function() {
// pull in the new value
var searchTerm = $("#searchtext").val();
// remove/update any old highlighted terms
$("#para").removeHighlight();
// disable highlighting if empty
if (searchTerm) {
// highlight the new term
$("#para").highlight(searchTerm);
}
});
});<file_sep>$(document).ready(function () {
// Initialize the plugin
$('#my_popup').popup({
transition: 'all 0.3s',
scrolllock: true // optional
});
});<file_sep>$(function () {
$('input:text').focus(function () {
$(this).val('');
});
$("#getValue").click(function(){
$('#weather').empty();
var city=$("#name").val();
$.ajax({
url: "http://api.worldweatheronline.com/free/v2/weather.ashx?q="+city+"&format=JSON&num_of_days=1&key=a53efcc3de3ded6ab63590252e80e",
success: function(weather){
for (var w in weather) {
var wt = weather[w];
var cc = wt.current_condition[0];
var $list = $('<ul>');
var $humidity = $('<li>').text("Humidity: " + cc.humidity);
var $feelc = $('<li>').text("FeelsLike in C: " + cc.FeelsLikeC);
var $feelf = $('<li>').text("FeelsLike in F: " + cc.FeelsLikeF);
var $tempc = $('<li>').text("Temprature in C: " + cc.temp_C);
var $tempf = $('<li>').text("Temprature in F: " + cc.temp_F);
var wdesc = cc.weatherDesc[0];
var $desc = $('<li>').text("Weather Description: " + wdesc.value);
var icon = cc.weatherIconUrl[0];
var $wicon = $('<img>').attr("src", icon.value);
var req = wt.request[0];
var $place = $('<h2>').text("Current weather condition in " + req.query);
$("#weather")
.append($place)
.append($list)
.append($humidity)
.append($tempc)
.append($feelc)
.append($tempf)
.append($feelf)
.append($desc)
.append($wicon);
}
}
});
});
});
<file_sep>var app = angular.module("upperAPI", []);
app.controller("convert", function ($scope) {
$scope.text;
});<file_sep>//Define an angular module for our app
var sampleApp = angular.module('sampleApp', []);
//Define Routing for app
//Uri /AddNewOrder -> template add_order.html and Controller AddOrderController
//Uri /ShowOrders -> template show_orders.html and Controller AddOrderController
sampleApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'templates/home.html',
controller: 'homeController'
}).
when('/about', {
templateUrl: 'templates/about.html',
controller: 'aboutController'
}).
when('/profile', {
templateUrl: 'templates/profile.html',
controller: 'profileController'
}).
otherwise({
redirectTo: '/home'
});
}]);
sampleApp.controller('homeController', function ($scope) {
$scope.message = 'This is Home screen';
});
sampleApp.controller('aboutController', function ($scope) {
$scope.message = 'In this page you can find information about us';
});
sampleApp.controller('profileController', function ($scope) {
$scope.message = 'In this page you can surf through your profile';
});<file_sep>var helloApp = angular.module("helloApp", []);
helloApp.controller("CompanyCtrl", ['$scope', '$http', function($scope, $http) {
$scope.companies = [
{ 'name':'Intuit',
'employees': 125000,
'headoffice': 'Sac Diago,CA'},
{ 'name':'HP',
'employees': 100000,
'headoffice': 'Mountainview,CA'},
{ 'name':'Amzon.Inc',
'employees': 115000,
'headoffice': 'San Fransisco,CA'},
{ 'name':'Google',
'employees': 150000,
'headoffice': 'Mountainview,CA'},
];
$scope.addRow = function(){
$scope.companies.push({ 'name':$scope.name, 'employees': $scope.employees, 'headoffice':$scope.headoffice });
$scope.name='';
$scope.employees='';
$scope.headoffice='';
};
$scope.removeRow = function (name) {
var index = -1;
var comArr = eval($scope.companies);
for (var i = 0; i < comArr.length; i++) {
if (comArr[i].name === name) {
index = i;
break;
}
}
if (index === -1) {
alert("Something gone wrong");
}
$scope.companies.splice(index, 1);
};
}]);<file_sep><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Weather API</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/weatherAPI.js"></script>
<link rel="stylesheet" type="text/css" href="../../css/weather.css" />
<style>
body {
background-image:url("../../images/gbg.jpg");
}
</style>
</head>
<body ng-app="bookinfo">
<div class="content">
<h1>Weather Condition in your city</h1>
<h3>About The Experiment</h3>
<p>In this experiment I have tried my hands on API services. Here I have used worldweatheronline API for displaying the weather of input place. The user enters the City or Country or Places name in the input box and as he clicks on the Go! button, the current weather conditions of that place are displayed. These details include: Temprateure in Celcius and Ferenhit, Feels like temprature, weather condition description, humidity, weather icon etc. I have also enabled keyboard controls like Enter,Tab for the ease of use.</p>
<div class="detail">
<h3>Enter City:</h3>
<input type="text" id="name" contenteditable="true" />
<button id="getValue" >Go!</button>
<div id="weather"></div>
</div>
<h3>Code Snippet</h3>
<!-- HTML generated using hilite.me --><div style="background: #202020; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%"> <span style="color: #d0d0d0">$(</span><span style="color: #ed9d13">"#getValue"</span><span style="color: #d0d0d0">).click(</span><span style="color: #6ab825; font-weight: bold">function</span><span style="color: #d0d0d0">(){</span>
<span style="color: #6ab825; font-weight: bold">var</span> <span style="color: #d0d0d0">city=$(</span><span style="color: #ed9d13">"#name"</span><span style="color: #d0d0d0">).val();</span>
<span style="color: #d0d0d0">$.ajax({</span>
<span style="color: #d0d0d0">url:</span> <span style="color: #ed9d13">"http://api.worldweatheronline.com/free/v2/weather.ashx?q="</span><span style="color: #d0d0d0">+city+</span><span style="color: #ed9d13">"&format=JSON&num_of_days=1&key=a53efcc3de3ded6ab63590252e80e"</span><span style="color: #d0d0d0">,</span>
<span style="color: #d0d0d0">success:</span> <span style="color: #6ab825; font-weight: bold">function</span><span style="color: #d0d0d0">(weather){</span>
<span style="color: #6ab825; font-weight: bold">for</span> <span style="color: #d0d0d0">(</span><span style="color: #6ab825; font-weight: bold">var</span> <span style="color: #d0d0d0">w</span> <span style="color: #6ab825; font-weight: bold">in</span> <span style="color: #d0d0d0">weather)</span> <span style="color: #d0d0d0">{</span>
<span style="color: #6ab825; font-weight: bold">var</span> <span style="color: #d0d0d0">wt</span> <span style="color: #d0d0d0">=</span> <span style="color: #d0d0d0">weather[w];</span>
<span style="color: #6ab825; font-weight: bold">var</span> <span style="color: #d0d0d0">cc</span> <span style="color: #d0d0d0">=</span> <span style="color: #d0d0d0">wt.current_condition[</span><span style="color: #3677a9">0</span><span style="color: #d0d0d0">];</span>
<span style="color: #6ab825; font-weight: bold">var</span> <span style="color: #d0d0d0">$list</span> <span style="color: #d0d0d0">=</span> <span style="color: #d0d0d0">$(</span><span style="color: #ed9d13">'<ul>'</span><span style="color: #d0d0d0">);</span>
<span style="color: #6ab825; font-weight: bold">var</span> <span style="color: #d0d0d0">$humidity</span> <span style="color: #d0d0d0">=</span> <span style="color: #d0d0d0">$(</span><span style="color: #ed9d13">'<li>'</span><span style="color: #d0d0d0">).text(</span><span style="color: #ed9d13">"Humidity: "</span> <span style="color: #d0d0d0">+</span> <span style="color: #d0d0d0">cc.humidity);</span>
<span style="color: #d0d0d0">...</span>
<span style="color: #d0d0d0">...</span>
<span style="color: #d0d0d0">...</span>
<span style="color: #d0d0d0">$(</span><span style="color: #ed9d13">"#weather"</span><span style="color: #d0d0d0">)</span>
<span style="color: #d0d0d0">.append($place)</span>
<span style="color: #d0d0d0">}</span>
<span style="color: #d0d0d0">}</span>
<span style="color: #d0d0d0">});</span>
<span style="color: #d0d0d0">});</span>
<span style="color: #d0d0d0">});</span>
</pre></div>
<h3>Decsription</h3>
<p>
Here when the button is clicked, the value from input field is stored in a variable named <i>city</i>. This value is used as a parameter to the url we are passing to access the API data. Only on click of button, jQuery ajax function is called. This function sets url as API url with city parameter. For successful response, it performs iteration over each element in response and their values are stored in variables and dynamically added to the web page.
</p>
<h3>References</h3>
<p>
I have used the following tutorial to create this animation:
<a href="https://developer.worldweatheronline.com/page/explorer-free">Tutorial</a>
</p>
<h3>Source Code</h3>
<p>
<button><a href="../../fileview/Default.aspx?~/experiments/week4/API1.html" target="_blank">View Source</a></button>
<button><a href="../../fileview/Default.aspx?~/css/weather.css" target="_blank">View CSS</a></button>
<button><a href="../../fileview/Default.aspx?~/experiments/week4/js/weatherAPI.js" target="_blank">View JS</a></button>
</p>
</div>
</body>
</html>
<file_sep>
app.controller("SearchController", function ($scope, $http, $routeParams) {
//Search Tourist Destinations in A City
var name = $routeParams.name;
$scope.destinations = [];
$(function () {
console.log(name);
$http.get("https://api.foursquare.com/v2/venues/explore?offset=0&limit=50§ion=sights&near="+name+"&radius=40233.60&client_id=GSIEU2B3JTCYFZ35EKBEYDTI0ZVDWDHN31WY3RHKQ1O0UD5Q&client_secret=<KEY>&v=20121215")
.success(function (places) {
var groups = places.response.groups;
var destinations = groups[0].items;
console.log(places);
$scope.destinations = destinations;
})
})
});
<file_sep><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Play Video in Background of the Home Page</title>
<link rel="stylesheet" type="text/css" href="css/video.css" />
</head>
<body>
<video id="bgvid" poster="css/collage.jpg" autoplay loop muted>
<!--<source src="css/travel.webm" type="video/webm" />-->
<source src="css/travel.mp4" type="video/mp4" />
</video>
<div id="bg">
<div id="bgbtn">
<button id="btn">Pause</button>
</div>
<h2>About The Experiment</h2>
<p>In this experiment, I have tried playing a video in the background which will be my project home page. CSS does not support videos as background but HTML5 supports that. Here I have deon that through autolooping <strong>video</strong> tag. Also user can pause/unpause the video at his will.</p>
<h3>Code Snippet</h3>
<pre>
<video id="bgvid" poster="css/collage.jpg" autoplay loop muted>
<source src="css/travel.mp4" type="video/mp4" />
</video>
pauseButton.addEventListener("click", function () {
vid.classList.toggle("stopfade");
if (vid.paused) {
vid.play();
pauseButton.innerHTML = "Pause";
} else {
vid.pause();
pauseButton.innerHTML = "Paused";
}
})
</pre>
<h3>Description</h3>
<p>
Here in the first snippet, it shown how to put a video as background and repeat it. Here for the start of the video, the image in poster will be used and then after the video will start. In the second snippet, the code for puase/unpause is shown. So it works as a toggle. The fading effect will be done/undone after every toggle and if the video is playing it will be paused and vise-a-versa.
</p>
<h3>References</h3>
<a href="http://demosthenes.info/blog/777/Create-Fullscreen-HTML5-Page-Background-Video">DemosThenes</a>
<h4>Source Code</h4>
<a href="../../fileview/Default.aspx?~/experiments/week9/background_video.html" target="_blank">View HTML Code</a><hr />
<a href="../../fileview/Default.aspx?~/experiments/week9/css/video.css" target="_blank">View CSS</a><hr />
<a href="../../fileview/Default.aspx?~/experiments/week9/js/playvideo.js" target="_blank">View javascript</a><hr />
</div>
<script src="js/playvideo.js"></script>
</body>
</html>
<file_sep>var app = angular.module("MyApp", []);
app.controller("MyCtrl", function ($scope) {
$scope.books = [
{ title: "<NAME>", price: 200 },
{ title: "Alchemist", price: 100 },
{ title: "L<NAME> the Rings", price: 300 },
{ title: "Meluha", price: 50 },
{ title: "Othello", price: 100 }
];
$scope.filterFunction = function (element) {
return element.title.match(/^Ma/) ? true : false;
};
});<file_sep>$(function () {
$("#pwd1").keyup(function () {
$('#result').html(checkStrength($('#pwd1').val()))
})
$("#sbmt").bind("click", function () {
var pwd1 = $("#pwd1").val();
var pwd2 = $("#pwd2").val();
if (pwd1 != pwd2) {
alert("Passwords do not match");
}
else if (pwd1 == '' || pwd2 == '') {
alert("password field must have some value");
}
else if (pwd1 == pwd2) {
alert("Both Passwords match");
}
})
$('.link').on('mouseenter', function () {
if ($('.tooltip').is(':visible')) {
$('.tooltip').hide();
}
$(this).next().show();
})
$('.link').on('mouseout', function () {
$(this).next().hide();
})
function checkStrength(password) {
var strength = 0
if (password.length < 6) {
$('#result').removeClass()
$('#result').addClass('short')
return 'Too short'
}
if (password.length > 7)
strength += 1
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))
strength += 1
if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/))
strength += 1
if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/))
strength += 1
if (strength < 2) {
$('#result').removeClass()
$('#result').addClass('weak')
return 'Weak'
}
else if (strength == 2) {
$('#result').removeClass()
$('#result').addClass('good')
return 'Good'
}
else {
$('#result').removeClass()
$('#result').addClass('strong')
return 'Strong'
}
}
});
<file_sep>var app = angular.module("CourseApp", ["ngRoute"]);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'courseApp/home.html'
}).
when('/about', {
templateUrl: 'courseApp/about.html'
}).
when('/contact', {
templateUrl: 'courseApp/contact.html'
}).
when('/profile', {
templateUrl: 'courseApp/profile.html'
}).
otherwise({
redirectTo: '/home'
});
}]);
app.controller("loginController", function ($scope, loginService,$location) {
$scope.currentUser = null;
$scope.color = "btn btn-success";
$scope.clear = function () {
$scope.username = '';
}
$scope.psclear = function(){
$scope.password = '';
}
$scope.login = function () {
var username = $scope.username;
var password = <PASSWORD>;
var result = loginService.login(username, password);
if (result == true) {
$scope.currentUser = loginService.getCurrentUser();
$scope.color = "btn btn-success";
}
else {
$scope.color = "btn btn-danger";
}
}
$scope.logout = function () {
$scope.currentUser = null;
$scope.username = null;
$scope.password = <PASSWORD>;
var res = loginService.logout();
$location.path('courseApp/home.html');
}
});
app.factory("loginService", function () {
var currentUser = null;
var users = [
{ username: "isha", password: "<PASSWORD>" },
{ username: "admin", password: "<PASSWORD>" }
];
var login = function (username, password) {
for (var index in users) {
if (users[index].username == username && users[index].password == password) {
currentUser = users[index];
return true;
}
}
return false;
}
var getCurrentUser = function () {
return currentUser;
}
var logout = function () {
currentUser = null;
}
return {
login: login,
getCurrentUser: getCurrentUser,
logout: logout
}
});
<file_sep>var app = angular.module("HelloApplication", []);
app.controller("control", function ($scope) {
$scope.hello;
})
<file_sep><h3>
This is my fifth blog
</h3>
<p>This is my sixth week of web development class and in this week I am doing experiments related to Angular JS</p>
Here is the link to experiments:
<a href="../story/index.htm?../experiments/week6/story6.txt">Week 6 : Angular-Routing Experiments</a>
<h3>Experiment Description</h3>
<ul>
<li><b>login</b></li>
<p>
In this experiment I have created different user profiles and provided the login facility. Using Angular,I have created the Service, View, Controller model. LoginService is the service which stores the user details and check it aginast the entered details. Then there is loginController which changes the view according to result returned by loginService.
</p>
<li><b>Profile</b></li>
<p>
In this experiment I have created different user profiles and provided the login facility. Using Angular,I have created the Service, View, Controller model. LoginService is the service which stores the user details and check it aginast the entered details. Then there is loginController which changes the view according to result returned by loginService. After loggin in the user is able to view his profile which is different for each user.
</p>
<li><b>Profile Edit</b></li>
<p>
In this experiment, user is able to login to his profile and edit the information. There is additional controller provided here: ProfileController. This controller fetches the user information and displays it after user logs in. User can change that info and on save it. The next time user logs in, new info is shown to him.
</p>
<li><b>Uploading Profile Pic</b></li>
<p>
In this experiment, user is able to login to his profile and edit the profile picture. I have added an extra feature of photo in user data. when there is no pic, it shows the default one. Otherwise when user has chosen some picture, it checks for the type of file and stores the image as binary data base 64. On save changes event, this data is passed to loginService which stores it in user profile photo.
</p>
<li><b>Course Page</b></li>
<p>
In this experiment, I have tried replicating the course application taught by sir in the class. Here 3 different profiles are maintained namely:admin, faculty and student. Admin maintains accounts, faculty teaches and authors courses and students register in different classes. So UserService and CourseService are maintained. UserService maintains user data and ligin logout functionality. CourseService maintains the courseinfo and course add remove and get functionalities.
</p>
</ul>
<file_sep>var app = angular.module("CourseApp", ["ngRoute"]);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'profileManager/home.html'
}).
when('/about', {
templateUrl: 'profileManager/about.html'
}).
when('/contact', {
templateUrl: 'profileManager/contact.html'
}).
when('/adduser', {
templateUrl: 'profileManager/adduser.html',
controller: 'UserController'
}).
when('/profile/:username', {
templateUrl: 'profileManager/dp.html',
controller: 'ProfileController'
}).
otherwise({
redirectTo: '/home'
});
}]);
app.factory("loginService", function ($http) {
var currentUser = null;
var login = function (user, callback) {
$http.post('/login', user)
.success(function (response) {
currentUser = response;
callback();
});
}
var updatePhoto = function (photo) {
currentUser.photo = photo;
}
var updateCurrentUser = function (password, email, firstName, lastName) {
currentUser.password = <PASSWORD>;
currentUser.email = email;
currentUser.firstName = firstName;
currentUser.lastName = lastName;
$http.post('/update', currentUser)
.success(function (response) {
currentUser = response;
});
}
var addUser = function (username ,password, email, firstName, lastName,photo, callback) {
var user = {
username: username,
password: <PASSWORD>,
email: email,
firstName: firstName,
lastName: lastName,
photo: photo
};
$http.post('/add', user)
.success(function (response) {
callback(true);
});
}
var getCurrentUser = function () {
return currentUser;
}
var logout = function () {
currentUser = null;
}
return {
login: login,
getCurrentUser: getCurrentUser,
logout: logout,
updateCurrentUser: updateCurrentUser,
addUser: addUser,
updatePhoto: updatePhoto
}
});
app.controller("loginController", function ($scope, loginService, $location) {
$scope.currentUser = null;
$scope.color = "btn btn-success";
$scope.clear = function () {
$scope.username = '';
}
$scope.psclear = function () {
$scope.password = '';
}
$scope.login = function () {
loginService.login($scope.user, callback);
}
function callback() {
$scope.currentUser = loginService.getCurrentUser();
if ($scope.currentUser)
$scope.color = "btn btn-success";
else
$scope.color = "btn btn-danger";
}
$scope.logout = function () {
$scope.currentUser = null;
$scope.username = null;
$scope.password = <PASSWORD>;
var res = loginService.logout();
$location.path('courseApp/home.html');
}
});
app.controller("ProfileController", function ($scope, loginService, $routeParams) {
var username = $routeParams.username;
$scope.username = username;
var currentUser = loginService.getCurrentUser();
$scope.new_fn = currentUser.firstName;
$scope.new_ln = currentUser.lastName;
$scope.new_mail = currentUser.email;
$scope.new_pwd = <PASSWORD>;
$scope.re_pwd = <PASSWORD>;
$scope.mismatch = false;
$scope.save = false;
if (currentUser.photo == "")
$scope.loc = "../images/dp.jpg";
else
$scope.loc = currentUser.photo;
var handleFileSelect = function (evt) {
var files = evt.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload = function (readerEvt) {
var binaryString = readerEvt.target.result;
$scope.loc = "data:image/jpeg;base64," + btoa(binaryString);
loginService.updatePhoto($scope.loc);
};
reader.readAsBinaryString(file);
}
};
if (window.File && window.FileReader && window.FileList && window.Blob) {
document.getElementById('filePicker').addEventListener('change', handleFileSelect, false);
} else {
alert('The File APIs are not fully supported in this browser.');
}
$scope.saveChanges = function () {
var password = $<PASSWORD>;
var repassword = $scope.<PASSWORD>;
var email = $scope.new_mail;
var firstName = $scope.new_fn;
var lastName = $scope.new_ln;
if (password != repassword) {
$scope.mismatch = true;
$scope.save = false;
} else {
$scope.mismatch = false;
$scope.save = true;
loginService.updateCurrentUser(password, email, firstName, lastName);
}
}
});
app.controller("UserController", function ($scope, loginService, $routeParams) {
$scope.loc = "../images/dp.jpg";
$scope.addUser = function () {
var username = $scope.username;
var password = <PASSWORD>;
var repassword = <PASSWORD>;
var email = $scope.new_mail;
var firstName = $scope.new_fn;
var lastName = $scope.new_ln;
var photo = $scope.loc;
if (password != <PASSWORD>) {
$scope.mismatch = true;
$scope.save = false;
} else {
$scope.mismatch = false;
loginService.addUser(username, password, email, firstName, lastName, photo, callback);
}
}
function callback(res) {
if (res == true) {
$scope.save = true;
$scope.save_msg = "User Added Successfully";
}
};
});<file_sep><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Adding a new user in the database</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
<link rel="stylesheet" type="text/css" href="../../css/codesnippets/sunburst.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<style>
body{
padding-top : 60px;
background-image:url("../../images/gbg.jpg");
}
</style>
</head>
<body>
<div class="container">
<hr />
<div class="jumbotron">
<h2>Adding New User using Node js and MongoDB</h2>
<h6>Click on the link below to see the experiment</h6>
<a href="http://developeride-ishashah112.rhcloud.com/adduser.html" target="_blank">Add new user in Database</a>
</div>
<h2>About the Experiment</h2>
<h4>Credentails:</h4>
<p>
<ul>
<li>username:isha, password:<PASSWORD></li>
<li>username:admin, password:<PASSWORD></li>
</ul>
</p>
<p>
In this experiment, I have provided an option of registration to the user. Here the info entered by user is passed to Node server as json object and then that object is inserted in the user collection.
</p>
<h3>Code Snippet</h3>
<span id="text">
<pre class="prettyprint">
app.post('/mongod/add', function (req, res) {
var username = req.body.username;
var password = req.body.password;
var email = req.body.email;
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var photo = req.body.photo;
UserModel.find({ username: username }, function (err, data) {
if (data.length > 0) {
res.json({ response: 'false' });
} else {
new UserModel({
username: username,
password: <PASSWORD>,
email: email,
firstName: firstName,
lastName: lastName,
photo: photo
}).save(function (err, data) {
console.log("new user created");
res.json(data);
});
}
});
});
</pre>
</span>
<h3>
Description
</h3>
<p>Here in this code snippet I have shown the code for adding new user in the databse. It stores all the fields one by one and makes a json object which is inserted in the db.</p>
<div class="h4">
<h1>Source Code</h1>
<a href="../../fileview/Default.aspx?~/experiments/developeride/public/mongodb/adduser.html" target="_blank">View Source Code</a><hr />
<a href="../../fileview/Default.aspx?~/experiments/developeride/public/mongodb/js/newuser.js" target="_blank">Client Side javascript</a><hr />
<a href="../../fileview/Default.aspx?~/experiments/developeride/server.js">Server Side Javascript</a>
<hr />
<h1>Reference</h1>
Prof.Jose's Lecture
</div>
</div>
</body>
</html>
<file_sep>var app = angular.module('ModalTest', ['ui.bootstrap']);
app.controller('NavController', function ($scope, $modal) {
// $scope.items = ['item1', 'item2', 'item3'];
$scope.launch = function () {
$modal.open({
templateUrl: 'partials/signup-page.html',
controller: 'ModalInstanceCtrl'
});
//modalInstance.result.then(function (selectedItem) {
// $scope.selected = selectedItem;
//}, function () {
// $log.info('Modal dismissed at: ' + new Date());
//});
};
});
app.controller('ModalInstanceCtrl', function ($scope, $modal) {
console.log("hello");
});
//var ModalInstanceCtrl = function ($scope, $modalInstance, items) {
// $scope.items = items;
// $scope.selected = {
// item: $scope.items[0]
// };
// $scope.ok = function () {
// $modalInstance.close($scope.selected.item);
// };
// $scope.cancel = function () {
// $modalInstance.dismiss('cancel');
// };
//};
<file_sep><html>
<head>
<title>AngularJS HTML DOM</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="js/dom.js"></script>
<style>
body {
background-image:url("../../images/gbg.jpg");
}
</style>
</head>
<body ng-app="MyApp">
<div ng-controller="button" class="container">
<h2>HTML DOM change using Angular js</h2>
<h3>
About The Experiment
</h3>
<p>
In this experiment I have tried playing with various DOM elements provided by angular. I have used <i>hide,show,disable,click</i> etc for that. When user checks the disabled option, the button gets disabled. When user checks show/hide the button is shown/hidden respectively. When user clicks on last button, everytime the counter is increased and total number of clicks are displayed.
</p>
<h2>Try It Yourself!!</h2>
<table class="table table-striped">
<tr>
<td><input type="checkbox" ng-model="enableDisableButton" >Disable Button</td>
<td><button ng-disabled="enableDisableButton" ng-click="click()">Click Me!</button></td>
</tr>
<tr>
<td><input type="checkbox" ng-model="showHide1" >Show Button</td>
<td><button ng-show="showHide1" ng-click="click()">Click Me!</button></td>
</tr>
<tr>
<td><input type="checkbox" ng-model="showHide2" >Hide Button</td>
<td><button ng-hide="showHide2" ng-click="click()">Click Me!</button></td>
</tr>
<tr>
<td><p>Total click: {{ clickCounter }}</p></td>
<td><button ng-click="clickCounter = clickCounter + 1">Click Me!</button></td>
</tr>
</table>
<h3>Code Snippet</h3>
<pre>
<td><input type="checkbox" ng-model="enableDisableButton" >Disable Button</td>
<td><button ng-disabled="enableDisableButton" ng-click="click()">Click Me!</button></td>
<td><input type="checkbox" ng-model="showHide1" >Show Button</td>
<td><button ng-show="showHide1" ng-click="click()">Click Me!</button></td>
<td><p>Total click: {{ clickCounter }}</p></td>
<td><button ng-click="clickCounter = clickCounter + 1">Click Me!</button></td>
</pre>
<p>
<ul>
<li>Here the first snippet shows the code for disabling the button. I have used <i>ng-disabled</i> for that.</li>
<li>In the second snippet I have shown the code for showing the button. I have used <i>ng-show</i> for that. Same can be done to hide the button with <i>ng-hide</i></li>
<li>In the third snippet I have shown the code for showing the number of clicks. I have used <i>ng-click</i> for that. Each time the button is clicked the counter is incremented. This counter is a scope variable which is shown at UI to display total number of clicks</li>
</ul>
</p>
<h3>References</h3>
<a href="http://www.tutorialspoint.com/angularjs/angularjs_html_dom.htm" class="btn btn-success" target="_blank">Tutorial Points</a>
<h3>Source Code</h3>
<a href="../../fileview/Default.aspx?~/experiments/week5/html_dom.html" class="btn btn-success" target="_blank">View HTML Source</a>
<a href="../../fileview/Default.aspx?~/experiments/week5/js/dom.js" class="btn btn-success" target="_blank">View javascript</a>
<p>
</p>
</div>
</body>
</html><file_sep><html>
<head>
<title>Filtering using Angular JS</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="js/angular.min.js"></script>
<script src="js/search.js"></script>
<style>
body {
background-image:url("../../images/gbg.jpg");
}
</style>
</head>
<body ng-app="MyApp">
<div class="container">
<h1>Filtering using Angular JS</h1>
<h2>About The Experiment</h2>
<p>
In this experiment I have tried to implement filtering functionality with help of angular js. Here there is a dataset given. On that dataset, filtering is applied. When the user types the book's title or its price in the input field, the dataset elements are filtered and the result is shown by updating the DOM. So it is a single page application where the user gets all result on single page without reloading it.
</p>
<div ng-controller="MyCtrl">
<form class="form-inline">
<input ng-model="query" type="text"
placeholder="Filter by book title or price" autofocus>
</form>
<table class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="book in books | filter:query | orderBy: 'title'">
<td>{{book.title}}</td>
<td>{{book.price}}</td>
</tr>
</tbody>
</table>
</div>
<h2>Code Snippet</h2>
<pre>
$scope.filterFunction = function (element) {<br />
return element.title.match(/^Ma/) ? true : false;<br />
};
</pre>
<pre>
<tr ng-repeat="book in books | filter:query | orderBy: 'title'"><br />
<td>scope variable</td><br />
<td>scope variable</td><br />
</tr>
</pre>
<h4>Description</h4>
<p>
Here in the first snippet, filetr function is called with the an element. If that element's title matches with input then that element is displayed .And in the second snippet, a ng-repeat is called and that performs iteration over each element in the data set and filters them according to the query:value in the input field. It sorts the elements by title. The scope variables are bound to both UI and Contorl. So values from the dataset are fed in the scope variables.
</p>
<h3>References</h3>
<a href="http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/filtering-and-sorting-a-list.html" class="btn btn-primary" target="_blank">Recipes With Angular.js</a>
<h3>Source Code</h3>
<a href="../../fileview/Default.aspx?~/experiments/angular/search.html" class="btn btn-primary" target="_blank">View HTML Source</a>
<a href="../../fileview/Default.aspx?~/experiments/angular/js/search.js" class="btn btn-primary" target="_blank">View javascript</a>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Resizable and Draggable Image</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="../../css/dandr.css" />
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$(".resizebleImage").resizable().parent().draggable();
});
</script>
<h1>Image Drag And Resizing</h1>
<h3>About the Experiment</h3>
<p>
Here I have created the code to resize a given image. User can drag the image on screen anywhere as well he can resize the image by pulling it from corners. I have made use of javascript <i>resizable()</i> and <i>draggable</i> functions for that. I have included the jQuery and javascript files from Google CDN to make the experiment run.
</p>
<div class="pic">
<img class="resizebleImage" src="../../images/img2.jpg" />
<div class="text">
<p>Try Dragging And Resizing The Image!!!</p>
</div>
</div>
<div class="snip">
<h3>Code Snippet</h3>
<!-- HTML generated using hilite.me --><div style="background: #202020; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%"><span style="color: #6ab825; font-weight: bold"><script </span><span style="color: #bbbbbb">type=</span><span style="color: #ed9d13">"text/javascript"</span><span style="color: #6ab825; font-weight: bold">></span>
<span style="color: #d0d0d0">$(</span><span style="color: #24909d">document</span><span style="color: #d0d0d0">).ready(</span><span style="color: #6ab825; font-weight: bold">function</span> <span style="color: #d0d0d0">()</span> <span style="color: #d0d0d0">{</span>
<span style="color: #d0d0d0">$(</span><span style="color: #ed9d13">".resizebleImage"</span><span style="color: #d0d0d0">).resizable().parent().draggable();</span>
<span style="color: #d0d0d0">});</span>
<span style="color: #6ab825; font-weight: bold"></script></span>
</pre></div>
<p>
The resizableImage class will call the function upon drag and resize events which will in turn call the inbuilt javascript functions for that.
</p>
<h3>Reference</h3>
<a href="http://stackoverflow.com/questions/2702008/how-to-do-drag-n-drop-and-resize-on-an-image-using-jquery">Stack Overflow</a>
<h3>Source Code</h3>
<p>
<div class="button-link"><a href="../../fileview/Default.aspx?~/experiments/week2/randd.html" target="_blank">View Source</a></div>
<div class="button-link"><a href="../../fileview/Default.aspx?~/css/dandr.css" target="_blank">View CSS</a></div>
</p>
</div>
</body>
</html>
<file_sep>var app = angular.module("MyApp", [])
app.controller("button", function ($scope) {
$scope.click = function () {
alert("button clicked");
}
});<file_sep><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Travel Destinations of a City</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.min.js"></script>
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
<link rel="stylesheet" type="text/css" href="../../css/codesnippets/sunburst.css" />
<script src="js/dest.js"></script>
<style>
body {
background-image:url("css/collage.jpg");
}
#content {
background: rgba(0,0,0,0.8);
color:wheat;
}
</style>
</head>
<body ng-app="TravelApp">
<div ng-controller="infocontroller" class="container" id="content">
<h2>Search Places</h2>
<div class="input-group">
<input type="text" ng-model="searchByCity" class="form-control" id="city" contenteditable="true" placeholder="Enter the City Name"/>
<span class="input-group-btn">
<button ng-click="searchPlaces()" class="btn btn-primary" type="button" >Search!</button>
</span>
</div>
<table class="table">
<caption ng-show="destinations"><h2>Tourist Attractions in the City</h2></caption>
<thead>
<tr>
<th>Attraction</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="dest in destinations">
<td>{{dest.text}}</td>
</tr>
</tbody>
</table>
<h1>About The Experiment</h1>
<p>In this experiment,I have shown the usage of one of the APIs I will be using in my project. <strong>FreeBase API</strong> allows you to make a free text search. Here I have used it for retreiving famous tourist destinations of a city. When User enters a city name, it is embedded in the http GET request and sent to the API. The API in turn returns a json object from which the array of destinations is retrieved and displayed on the page. </p>
<h3>Code Snippet</h3>
<pre class="prettyprint">
$scope.searchPlaces = function () {
var name = $scope.searchByCity;
$http.get("https://www.googleapis.com/freebase/v1/topic/en/" + name + "/?props=&lang=en&filter=%2Ftravel%2Ftravel_destination%2Ftourist_attractions&limit=30&key=<KEY>")
.success(function (places) {
var travel = "/travel/travel_destination/tourist_attractions";
var destinations = places.property[travel].values;
$scope.destinations = destinations;
})
}
</pre>
<h3>Description</h3>
<p>In this code snippet I have shown the javascript code for retrieving data from API. Here the city name entered by the user is passed in the request and the response is then stored in destinations variable. Then on front end, ng-repeat module is used to traverse through the data.</p>
<h3>References</h3>
<h5>Prof. Jose's Lectures and my previous experiments</h5>
<h3>Source Code</h3>
<a href="../../fileview/Default.aspx?~/experiments/week9/travel_dest.html" target="_blank">View HTML Code</a><hr />
<a href="../../fileview/Default.aspx?~/experiments/week9/css/dest.css" target="_blank">View javascript</a><hr />
</div>
</body>
</html>
<file_sep>var app = angular.module("MyApp", []);
app.controller("Profile", function ($scope) {
$scope.person = {
name: "<NAME>",
};
});
app.controller("Editor", function ($scope) {
$scope.name = $scope.person.name;
$scope.save = function () {
$scope.person.name = $scope.name;
}
});
| 59d0a26f9abadf902ba128fa6211f7c96a19aa70 | [
"JavaScript",
"HTML"
]
| 25 | JavaScript | dbharathkumar08/webdev | e9b825917137ef7cc084d22083a453e85fe42f29 | b4a255b45ede8af48fa74d1698cf49695c1941bc |
refs/heads/master | <file_sep>import React from 'react';
const NotFound = () => (
<>
<h1>404</h1>
<h2>Pagina no Encontrada</h2>
</>
);
export default NotFound; | 5194f938fd13168a3d06f359ee030aa2a89fb7b3 | [
"JavaScript"
]
| 1 | JavaScript | smavo/platziVideo | 70f513c7b138bbe51306ff109453ad46f3139d0d | 1f88d1d95ced2fb3010ce75c27c8a6e9f6a37566 |
refs/heads/master | <file_sep>YAY_REPO_URL = 'https://aur.archlinux.org/yay.git'
GETTY_OVERRIDE_PATH = '/etc/systemd/system/[email protected]'
INSTALL_DEV_PACKAGES = <<-END
pacman -S --needed --noconfirm git base-devel
END
INSTALL_PYTHON = <<-END
pacman -S --needed --noconfirm python python-pip
END
INSTALL_YAY = <<-END
pushd .
if [ ! -e /tmp/yay ]; then
git clone '#{YAY_REPO_URL}' /tmp/yay/
fi
cd /tmp/yay
makepkg --clean
makepkg --noconfirm -si
popd
END
INSTALL_PYCHARM = <<-END
yay -S --needed --noconfirm pycharm-professional
END
# Or we could just, you know...
# use SSH and (Neo)Vim or Emacs?
INSTALL_GUI = <<-END
pacman --noconfirm --needed -S xfce4 \
xorg-server xf86-input-libinput
yes | pacman -S --needed virtualbox-guest-utils
systemctl daemon-reload
systemctl enable --now vboxservice.service
END
SETUP_GUI = <<-END
echo 'startxfce4' > ~/.xinitrc
END
AUTOLOGIN_OVERRIDE = <<-END
[Service]
ExecStart=
ExecStart=-/usr/bin/agetty --autologin vagrant --noclear %I $TERM
END
AUTO_GUI_PROFILE = <<-END
grep -q 'tty' ~vagrant/.bash_profile || \
echo '[[ "$(tty)" = "/dev/tty1" ]] && startx' >> ~vagrant/.bash_profile
END
AUTOLOGIN_SYSTEMD = <<-END
mkdir -p '#{GETTY_OVERRIDE_PATH}'
echo '#{AUTOLOGIN_OVERRIDE}' > '#{GETTY_OVERRIDE_PATH}/override.conf'
systemctl daemon-reload
END
RESTART_TTY = <<-END
systemctl restart [email protected]
END
SETUP_PARALLEL_MAKEPKG = <<-END
sed -i '/etc/makepkg.conf' -e 's/^COMPRESSXZ=.*$/COMPRESSXZ=\(xz -c -z - --threads=0\)/'
sed -i '/etc/makepkg.conf' -e 's/#MAKEFLAGS=.*$/MAKEFLAGS=\(-O2 -j3 -march=native)/'
END
VM_NAME = 'agile-dev'
Vagrant.configure('2') do |config|
config.vm.box = 'archlinux/archlinux'
config.vm.box_version = '2020.03.04'
config.vm.define VM_NAME
config.vm.hostname = VM_NAME
config.vm.provider :virtualbox do |vm|
vm.name = VM_NAME
vm.gui = true
# Everyone can spare that much, right?
vm.cpus = 2
vm.memory = 2048
end
config.vm.provision :shell, privileged: true, inline: 'pacman -Sy --noconfirm'
config.vm.provision :shell, privileged: true, inline: INSTALL_DEV_PACKAGES
config.vm.provision :shell, privileged: true, inline: INSTALL_PYTHON
config.vm.provision :shell, privileged: true, inline: INSTALL_GUI
config.vm.provision :shell, privileged: true, inline: SETUP_PARALLEL_MAKEPKG
config.vm.provision :shell, privileged: false, inline: INSTALL_YAY
config.vm.provision :shell, privileged: false, inline: INSTALL_PYCHARM
config.vm.provision :shell, privileged: false, inline: SETUP_GUI
config.vm.provision :shell, privileged: false, inline: AUTO_GUI_PROFILE
config.vm.provision :shell, privileged: true, inline: AUTOLOGIN_SYSTEMD
config.vm.provision :shell, privileged: true, inline: RESTART_TTY
end
| a61b58a4b00baa846ac886005ac46e70d7cc8758 | [
"Ruby"
]
| 1 | Ruby | 2020-agilis-csapat-a/toolchain | de59d1d597bf0d3959e811368f811b908db82186 | 361a27bf6e73d149a4f0792b5898cac6f626d510 |
refs/heads/master | <repo_name>s9891326/Data-Mining-homeWrok<file_sep>/hw4/hw4n.py
import pandas as pd
from apyori import apriori
import pyfpgrowth
import time
df_init = pd.read_excel("交易資料集.xlsx", dtype={'ITEM_NO':str, 'INVOICE_NO':str})
##刪除數量 = 0 及負值
df_init = df_init[df_init['QUANTITY'] > 0]
#抓取不重複的INVOICE_NO值
df_init = df_init.drop_duplicates(['INVOICE_NO','ITEM_NO'],'first')
#把INVOICE_NO重複的值PRODUCT_TYPE相加
df_list = df_init.groupby(by='INVOICE_NO').apply(lambda x:[(','.join(x['ITEM_NO']).split(','))][0])
#計算apriori開始時間
apriori_start_time = time.time()
#依照支持度 信心度 進行apriori的關聯規則探索
rules = list(apriori(df_list[:50]))
#計算apriori結束時間
apriori_end_time = time.time()
for i in range(0,len(rules)):
for j in range(0,len(rules[i][2])):
for k in range(0,len(rules[i][2][j])):
print(rules[i][2][j][k])
print("-"*20)
print("apriori cost time = %.2f" %(apriori_end_time-apriori_start_time))
print("\n\n")
#計算fg_growth開始時間
fp_growth_start_time = time.time()
#選擇支持度在100以上的
patterns = pyfpgrowth.find_frequent_patterns(df_list[:50], 5)
#選擇信心度在0.7以上的
fp_rules = pyfpgrowth.generate_association_rules(patterns, 0.7)
#計算fg_growth結束時間
fp_growth_end_time = time.time()
for i,k in fp_rules.items():
print("選擇的話 : ",i)
print("會被推測為會購買 : ",k)
print("-"*20)
print("FP-Growth cost time = %.2f" %(fp_growth_end_time-fp_growth_start_time))<file_sep>/hw4/hw4.py
import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
# from efficient_apriori import apriori
from apyori import apriori
import pyfpgrowth
import time
df_list = []
df = pd.read_excel("交易資料集.xlsx")
##刪除數量 = 0 及負值
df = df[df['QUANTITY'] > 0]
#抓取不重複的INVOICE_NO值
df = df.drop_duplicates(['INVOICE_NO','PRODUCT_TYPE'],'first')
#把INVOICE_NO重複的值PRODUCT_TYPE相加
df = df.groupby(by='INVOICE_NO').apply(lambda x:[','.join(x['PRODUCT_TYPE'])])
for i in df:
df_list.append(i[0].split(','))
print(df_list)
#計算apriori開始時間
apriori_start_time = time.time()
te = TransactionEncoder()
#建立表格
te_ary = te.fit(df_list).transform(df_list)
df = pd.DataFrame(te_ary, columns=te.columns_)
print(df)
print(df.columns)
#依照支持度 信心度 進行apriori的關聯規則探索
rules = list(apriori(df, min_support=0.7,min_confidence=0.7))
#計算apriori結束時間
apriori_end_time = time.time()
for i in range(0,len(rules)):
for j in range(0,len(rules[i][2])):
for k in range(0,len(rules[i][2][j])):
print(rules[i][2][j][k])
print("-"*20)
print("apriori cost time = %.2f" %(apriori_end_time-apriori_start_time))
#計算fg_growth開始時間
fp_growth_start_time = time.time()
#選擇支持度在100以上的
patterns = pyfpgrowth.find_frequent_patterns(df_list,50)
#選擇信心度在0.7以上的
rules = pyfpgrowth.generate_association_rules(patterns, 0.7)
#計算fg_growth結束時間
fp_growth_end_time = time.time()
for i,k in rules.items():
print("選擇的話 : ",i)
print("會被推測為會購買 : ",k)
print("-"*20)
print("FP-Growth cost time = %.2f" %(fp_growth_end_time-fp_growth_start_time))<file_sep>/hw4/main_1.py
import pandas as pd
df_init = pd.read_excel("rule.xlsx")
a = df_init['選擇']
b = df_init['推薦']
product_list = []
product_output = []
product = input("請輸入(多個值請用 ',' 隔開) = ")
print("input = " , product)
product = product.split(', ')
##抓資料
for i in range(0,len(a)):
for item in product:
for j in range(0,len(a[i])):
if item == a[i]:
product_list.append(b[i])
##整理
for i in product_list:
print(i)
product_output.append(i)
##去重複
product_output = list(set(product_output))
print("product output = ",product_output)
<file_sep>/hw4/main.py
import pandas as pd
import pyfpgrowth
from time import time
import xlsxwriter
# 加载数据集
def loadDataSet():
df_init = pd.read_excel("交易資料集.xlsx", dtype={'ITEM_NO':str, 'INVOICE_NO':str})
##刪除數量 = 0 及負值
df_init = df_init[df_init['QUANTITY'] > 0]
#抓取不重複的INVOICE_NO值
df_init = df_init.drop_duplicates(['INVOICE_NO','ITEM_NO'],'first')
#把INVOICE_NO重複的值PRODUCT_TYPE相加
df_init = df_init.groupby(by='INVOICE_NO').apply(lambda x:[(' , '.join(x['ITEM_NO']).split(' , '))][0])
df_list = []
for i in df_init:
if(len(i) > 1):
df_list.append(i)
return df_list
# 创建集合 C1。即对 dataSet 进行去重,排序,放入 list 中,然后转换所有的元素为 frozenset
def createC1(dataSet):
C1 = []
for transaction in dataSet:
for item in transaction:
if not [item] in C1:
C1.append([item])
C1.sort()
return list(map(frozenset, C1))
# 计算候选数据集 CK 在数据集 D 中的支持度,并返回支持度大于最小支持度(minSupport)的数据
def scanD(D, Ck, minSupport):
ssCnt = {}
for tid in D:
for can in Ck:
if can.issubset(tid):
if can not in ssCnt:
ssCnt[can] = 1
else:
ssCnt[can] += 1
numItems = float(len(D))
retList = []
supportData = {}
for key in ssCnt:
support = ssCnt[key]/numItems
if support >= minSupport:
retList.insert(0, key)
supportData[key] = support
return retList, supportData
# 输入频繁项集列表 Lk 与返回的元素个数 k,然后输出所有可能的候选项集 Ck
def aprioriGen(Lk, k):
retList = []
lenLk = len(Lk)
for i in range(lenLk):
for j in range(i+1, lenLk):
L1 = list(Lk[i])[: k-2]
L2 = list(Lk[j])[: k-2]
L1.sort()
L2.sort()
# 第一次 L1,L2 为空,元素直接进行合并,返回元素两两合并的数据集
if L1 == L2:
retList.append(Lk[i] | Lk[j])
return retList
# 找出数据集 dataSet 中支持度 >= 最小支持度的候选项集以及它们的支持度。即我们的频繁项集。
def apriori(dataSet, minSupport=0.5):
C1 = createC1(dataSet)
D = list(dataSet)
# 计算候选数据集 C1 在数据集 D 中的支持度,并返回支持度大于 minSupport 的数据
L1, supportData = scanD(D, C1, minSupport)
L = [L1]
k = 2
while (len(L[k-2]) > 0):
Ck = aprioriGen(L[k-2], k)
Lk, supK = scanD(D, Ck, minSupport)
supportData.update(supK)
if len(Lk) == 0:
break
L.append(Lk)
k += 1
return L, supportData
# 计算可信度(confidence)
def calcConf(freqSet, H, supportData, brl, minConf=0.7):
# 记录可信度大于最小可信度(minConf)的集合
prunedH = []
for conseq in H:
conf = supportData[freqSet]/supportData[freqSet-conseq]
if conf >= minConf:
brl.append((freqSet-conseq, conseq, conf))
prunedH.append(conseq)
return prunedH
# 递归计算频繁项集的规则
def rulesFromConseq(freqSet, H, supportData, brl, minConf=0.7):
m = len(H[0])
if (len(freqSet) > (m + 1)):
Hmp1 = aprioriGen(H, m+1)
# 返回可信度大于最小可信度的集合
Hmp1 = calcConf(freqSet, Hmp1, supportData, brl, minConf)
# 计算可信度后,还有数据大于最小可信度的话,那么继续递归调用,否则跳出递归
if (len(Hmp1) > 1):
rulesFromConseq(freqSet, Hmp1, supportData, brl, minConf)
# 生成关联规则
def generateRules(L, supportData, minConf=0.7):
bigRuleList = []
for i in range(1, len(L)):
# 获取频繁项集中每个组合的所有元素
for freqSet in L[i]:
H1 = [frozenset([item]) for item in freqSet]
if (i > 1):
rulesFromConseq(freqSet, H1, supportData, bigRuleList, minConf)
else:
calcConf(freqSet, H1, supportData, bigRuleList, minConf)
return bigRuleList
dataSet = loadDataSet()
print('load success')
apriori_start_time = time()
# Apriori 算法生成频繁项集以及它们的支持度
L1, supportData1 = apriori(dataSet, minSupport=0.0025)
apriori_time = time() - apriori_start_time
print('Apriori time: ', apriori_time)
# 生成关联规则
apriori_rules = generateRules(L1, supportData1, minConf=0.5)
for item in apriori_rules:
rule = [x for x in item[0]]
result = [x for x in item[1]]
print("選擇的話 : ",rule)
print("會被推測為會購買 : ",result)
print("-"*20)
print("\n\n")
fp_growth_start_time = time()
patterns = pyfpgrowth.find_frequent_patterns(dataSet, 29)
fp_rules = pyfpgrowth.generate_association_rules(patterns, 0.5)
#計算fg_growth結束時間
fp_growth_time = time() - fp_growth_start_time
print("FP-Growth cost time = %.2f" %(fp_growth_time))
for i,k in fp_rules.items():
print("選擇的話 : ",i)
print("會被推測為會購買 : ",k)
print("-"*20)
workbook = xlsxwriter.Workbook('rule.xlsx')
worksheet1 = workbook.add_worksheet('Apriori')
row = 1
worksheet1.write(0, 0, '選擇')
worksheet1.write(0, 2, '推薦')
for item in apriori_rules:
rule = [x for x in item[0]]
result = [x for x in item[1]]
worksheet1.write(row, 0, ', '.join(rule))
worksheet1.write(row, 1, '->')
worksheet1.write(row, 2, ', '.join(result))
row += 1
worksheet2 = workbook.add_worksheet('FP-Growth')
row = 1
worksheet2.write(0, 0, '選擇')
worksheet2.write(0, 2, '推薦')
for i, k in fp_rules.items():
if (str(i)[-2] == "'"):
worksheet2.write(row, 0, str(i)[1:-1])
else:
worksheet2.write(row, 0, str(i)[1:-2])
worksheet2.write(row, 1, '->')
if (str(k[0])[-2] == "'"):
worksheet2.write(row, 2, str(k[0])[1:-1])
else:
worksheet2.write(row, 2, str(k[0])[1:-2])
row = row + 1
workbook.close()
<file_sep>/hw2/hw2.py
from sklearn import datasets
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
import numpy as np
import matplotlib.pyplot as plt
from nltk.corpus import stopwords
from sklearn.model_selection import cross_validate
dataset = datasets.load_files('mini_newsgroups')
stopwords = set(stopwords.words('english'))
tfv = TfidfVectorizer(encoding = 'ISO-8859-1', stop_words = stopwords)
training_tfv = tfv.fit_transform(dataset.data).toarray()
indices = np.random.permutation(training_tfv.shape[0])
feature_attribute = training_tfv[indices]
class_attribute = dataset.target[indices]
alpha_list = range(1, 10, 1)
accuracy_training_list = []
accuracy_test_list = []
for alpha in alpha_list:
naive_bayes = MultinomialNB(alpha = alpha, fit_prior = True)
cv_results = cross_validate(naive_bayes, feature_attribute, class_attribute, cv = 5, return_train_score = True)
accuracy_training = cv_results['train_score'].mean()
accuracy_training_list.append(accuracy_training)
print('NAIVE BAYES 訓練正確率: ' + str(accuracy_training))
accuracy_test = cv_results['test_score'].mean()
accuracy_test_list.append(accuracy_test)
print('NAIVE BAYES 測試正確率: ' + str(accuracy_test) + '\n')
plt.figure()
#plt.xticks(np.arange(2, 31, step = 2))
#plt.yticks(np.arange(0.7, 1, step = 0.05))
plt.title('NAIVE BAYES')
plt.xlabel('the number of alpha')
plt.ylabel('accuracy')
plt.plot(alpha_list, accuracy_training_list, marker = 'o', label = 'training')
plt.plot(alpha_list, accuracy_test_list, marker = 'o', label = 'test')
plt.legend(loc = 'best')
plt.savefig('NAIVE BAYES.png')
plt.show()
c_list = np.arange(0.1, 1, 0.1)
accuracy_training_list = []
accuracy_test_list = []
for c in c_list:
svm = LinearSVC(penalty = 'l2', dual = True, C = c, max_iter = 2000)
cv_results = cross_validate(svm, feature_attribute, class_attribute, cv = 5, return_train_score = True)
accuracy_training = cv_results['train_score'].mean()
accuracy_training_list.append(accuracy_training)
print('SVM 訓練正確率: '+ str(accuracy_training))
accuracy_test = cv_results['test_score'].mean()
accuracy_test_list.append(accuracy_test)
print('SVM 測試正確率: '+ str(accuracy_test) + '\n')
plt.figure()
#plt.xticks(np.arange(2, 31, step = 2))
#plt.yticks(np.arange(0.7, 1, step = 0.05))
plt.title('SVM')
plt.xlabel('the number of C')
plt.ylabel('accuracy')
plt.plot(c_list, accuracy_training_list, marker = 'o', label = 'training')
plt.plot(c_list, accuracy_test_list, marker = 'o', label = 'test')
plt.legend(loc = 'best')
plt.savefig('SVM.png')
plt.show()
<file_sep>/hw3/hw3-1.py
from sklearn import datasets
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from nltk.corpus import stopwords
import numpy as np
from time import time
dataset = datasets.load_files('mini_newsgroups', shuffle = False)
stopwords = set(stopwords.words('english'))
tfv = TfidfVectorizer(encoding = 'ISO-8859-1', stop_words = stopwords)
training_tfv = tfv.fit_transform(dataset.data).toarray()
t0 = time()
kmeans = KMeans(n_clusters = 20).fit(training_tfv)
print('花費時間:', time() - t0, '秒')
print('Silhouette Coefficient:', silhouette_score(training_tfv, kmeans.labels_))
print('SSE:', kmeans.inertia_)
result_list = [[0 for i in range(20)] for j in range(20)]
for k in range(2000):
result = kmeans.predict(training_tfv[k][:].reshape(1, -1))
result_list[int(result)][int(k / 100)] += 1
print('result_list:', result_list)
purity_list = []
purity = 0
for l in range(20):
result = max(result_list[l]) / sum(result_list[l])
purity += sum(result_list[l]) / 2000 * result
print('purity:', purity)
<file_sep>/hw4/input.py
a = [['coffe','test'],['milk'],['test'],['some'],['milk'],['coffe','test']]
b = [['coffe2'],['milk2','123','milk_two'],['test2'],['some2'],['milk_two'],['coffe2','test2']]
product_list = []
product_output = []
product = input("請輸入(多個值請用 ',' 隔開) = ")
print("input = " , product)
product = product.split(',')
##抓資料
for i in range(0,len(a)):
if product == a[i]:
product_list.append(b[i])
##整理
for i in product_list:
if type(i) is list:
for j in i:
product_output.append(j)
else:
product_output.append(i)
##去重複
product_output = list(set(product_output))
print("product output = ",product_output)<file_sep>/hw1/HW1.py
from sklearn import *
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
import pydotplus
import xlsxwriter
import matplotlib.pyplot as plt
#讀取原始資料
original_dataset = np.loadtxt('letter-recognition.data', dtype = 'str', delimiter = ',')
#指定屬性
feature_attribute = original_dataset[:, 1::].astype('float')
#指定類別
class_attribute = original_dataset[:, 0]
#標準化屬性
#standardized_feature_attribute = preprocessing.scale(feature_attribute)
#切割訓練及測試資料
feature_attributes_for_training, feature_attributes_for_test, class_attribute_for_training, class_attribute_for_test = train_test_split(feature_attribute, class_attribute, test_size = 0.5)
#採用標準化的方式進行預處理
scale = preprocessing.StandardScaler()
#計算平均值和標準差
scale.fit(feature_attributes_for_training)
#對訓練資料標準化
standardized_feature_attributes_for_training = scale.transform(feature_attributes_for_training)
#對測試資料標準化
standardized_feature_attributes_for_test = scale.transform(feature_attributes_for_test)
#方法一 - Decision Tree
#紀錄決策樹的深度
depth_list = range(2, 31)
#紀錄決策樹的訓練正確率
accuracy_of_decision_tree_training_list = []
#記錄決策樹的測試正確率
accuracy_of_decision_tree_test_list = []
#計算決策樹的最佳深度
for depth in depth_list:
#採取決策樹演算法
decision_tree_classifier = DecisionTreeClassifier(max_depth = depth)
#訓練決策樹
decision_tree = decision_tree_classifier.fit(standardized_feature_attributes_for_training, class_attribute_for_training)
#用決策樹的模型來預測訓練資料
predict_decision_tree_training_data = decision_tree.predict(standardized_feature_attributes_for_training)
#計算訓練資料的分類正確率
accuracy_of_decision_tree_training_data = metrics.accuracy_score(class_attribute_for_training, predict_decision_tree_training_data)
#紀錄正確率
accuracy_of_decision_tree_training_list.append(accuracy_of_decision_tree_training_data)
#用決策樹的模型來預測測試資料
predict_decision_tree_test_data = decision_tree.predict(standardized_feature_attributes_for_test)
#計算測試資料的分類正確率
accuracy_of_decision_tree_test_data = metrics.accuracy_score(class_attribute_for_test, predict_decision_tree_test_data)
#記錄正確率
accuracy_of_decision_tree_test_list.append(accuracy_of_decision_tree_test_data)
#產生圖片
plt.figure()
#設定x軸刻度
plt.xticks(np.arange(2, 32, step = 2))
#設定y軸刻度
plt.yticks(np.arange(0.1, 1.2, step = 0.1))
#畫出決策樹訓練曲線
plt.plot(depth_list, accuracy_of_decision_tree_training_list, marker = 'o', label = 'training')
#畫出決策樹預測曲線
plt.plot(depth_list, accuracy_of_decision_tree_test_list, marker = 'o', label = 'test')
#設定圖片標題
plt.title('Decision Tree')
#設定x軸標題
plt.xlabel('the depth of decision tree')
#設定y軸標題
plt.ylabel('accuracy')
#產生圖例
plt.legend(loc = 'best')
#儲存圖片
plt.savefig('DecisionTree.png')
#設定Excel檔的原始類別欄位
colunm_of_original_class_attribute_for_excel = class_attribute_for_test.reshape(class_attribute_for_test.shape[0], 1)
#設定Excel檔的箭頭欄位
colunm_of_arrow_for_excel = np.full(((class_attribute_for_test.shape[0]), 1), '→')
#設定Excel檔的預測類別欄位
colunm_of_predicted_class_attribute_for_excel = predict_decision_tree_test_data.reshape(class_attribute_for_test.shape[0], 1)
#組合多個欄位
result = np.concatenate((colunm_of_original_class_attribute_for_excel, standardized_feature_attributes_for_test, colunm_of_arrow_for_excel, colunm_of_predicted_class_attribute_for_excel), axis = 1)
#建立Excel檔案
workbook = xlsxwriter.Workbook('result.xlsx')
#新增工作表
worksheet1 = workbook.add_worksheet('Decision Tree')
#寫檔
for row, data in enumerate(result):
worksheet1.write_row(row, 0, data)
#列出屬性名稱
feature_names = np.array([['x-box'], ['y-box'], ['width'], ['high'], ['onpix'], ['x-bar'], ['y-bar'], ['x2bar'], ['y2bar'], ['xybar'], ['x2ybr'], ['xy2br'], ['x-egg'], ['xegvy'], ['y-egg'], ['yegvx']])
#找出測試紀錄中的最高正確率
highest_accuracy_in_list = max(accuracy_of_decision_tree_test_list)
#找出最高正確率的索引值
index_of_highest_accuracy_in_list = accuracy_of_decision_tree_test_list.index(highest_accuracy_in_list)
#採取決策樹演算法
decision_tree_classifier = DecisionTreeClassifier(max_depth = index_of_highest_accuracy_in_list)
#訓練決策樹
decision_tree = decision_tree_classifier.fit(standardized_feature_attributes_for_training, class_attribute_for_training)
#繪製決策樹(DOT格式)
dot_data = tree.export_graphviz(decision_tree, feature_names = feature_names, class_names = class_attribute, filled = True)
#取得圖片(DOT格式)
graph = pydotplus.graph_from_dot_data(dot_data)
#轉存為pdf格式
graph.write_pdf('decision_tree.pdf')
#方法二 - KNN
#紀錄最近鄰居法的鄰居個數
number_of_neighbors_list = range(1, 21)
#紀錄最近鄰居法的訓練正確率
accuracy_of_k_nearest_neighbors_training_list = []
#紀錄最近鄰居法的測試正確率
accuracy_of_k_nearest_neighbors_test_list = []
#計算最近鄰居法的最佳鄰居個數
for number_of_neighbors in number_of_neighbors_list:
#採取最近鄰居法演算法
k_nearest_neighbors_classifier = KNeighborsClassifier(n_neighbors = number_of_neighbors, weights = 'distance', algorithm = 'auto')
#訓練最近鄰居法
k_nearest_neighbors = k_nearest_neighbors_classifier.fit(standardized_feature_attributes_for_training, class_attribute_for_training)
#用最近鄰居法的模型來預測訓練資料
predict_k_nearest_neighbors_train_data = k_nearest_neighbors.predict(standardized_feature_attributes_for_training)
#計算訓練資料的分類正確率
accuracy_of_k_nearest_neighbors_training_data = metrics.accuracy_score(class_attribute_for_training, predict_k_nearest_neighbors_train_data)
#記錄正確率
accuracy_of_k_nearest_neighbors_training_list.append(accuracy_of_k_nearest_neighbors_training_data)
#用最近鄰居法的模型來預測測試資料
predict_k_nearest_neighbors_test_data = k_nearest_neighbors.predict(standardized_feature_attributes_for_test)
#計算預測資料的分類正確率
accuracy_of_k_nearest_neighbors_test_data = metrics.accuracy_score(class_attribute_for_test, predict_k_nearest_neighbors_test_data)
#記錄正確率
accuracy_of_k_nearest_neighbors_test_list.append(accuracy_of_k_nearest_neighbors_test_data)
#產生圖片
plt.figure()
#設定x軸刻度
plt.xticks(np.arange(1, 21, step = 1))
#設定y軸刻度
plt.yticks(np.arange(0.91, 1.03, step = 0.02))
#畫出最近鄰居法訓練曲線
plt.plot(number_of_neighbors_list, accuracy_of_k_nearest_neighbors_training_list, marker = 'o', label = 'training')
#畫出最近鄰居法測試曲線
plt.plot(number_of_neighbors_list, accuracy_of_k_nearest_neighbors_test_list, marker = 'o', label = 'test')
#設定圖片標題
plt.title('K Nearest Neighbors')
#設定x軸標題
plt.xlabel('the number of k')
#設定y軸標題
plt.ylabel('accuracy')
#設定圖例
plt.legend(loc = 'best')
#儲存圖片
plt.savefig('KNN.png')
#設定Excel檔的預測類別欄位
colunm_of_predicted_class_attribute_for_excel = predict_k_nearest_neighbors_test_data.reshape(class_attribute_for_test.shape[0], 1)
#組合多個欄位
result = np.concatenate((colunm_of_original_class_attribute_for_excel, standardized_feature_attributes_for_test, colunm_of_arrow_for_excel, colunm_of_predicted_class_attribute_for_excel), axis = 1)
#新增工作表
worksheet2 = workbook.add_worksheet('K Nearest Neighbors')
#寫檔
for row, data in enumerate(result):
worksheet2.write_row(row, 0, data)
#關閉Excel檔
workbook.close()<file_sep>/hw3/hw3-2.py
from sklearn import datasets
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import DBSCAN
from sklearn.metrics import silhouette_score
from nltk.corpus import stopwords
import numpy as np
from time import time
dataset = datasets.load_files('mini_newsgroups', shuffle = False)
stopwords = set(stopwords.words('english'))
tfv = TfidfVectorizer(encoding = 'ISO-8859-1', stop_words = stopwords)
training_tfv = tfv.fit_transform(dataset.data).toarray()
t0 = time()
clustering = DBSCAN(eps = 3, min_samples = 5).fit(training_tfv)
print('花費時間:', time() - t0, '秒')
print(clustering.labels_)
#print('Silhouette Coefficient:', silhouette_score(training_tfv, clustering.labels_))<file_sep>/hw4/hw4_2.py
import pandas as pd
# from mlxtend.preprocessing import TransactionEncoder
# from efficient_apriori import apriori
from apyori import apriori
import pyfpgrowth
import time
df_list = []
df = pd.read_excel("交易資料集.xlsx", dtype={'ITEM_NO':str, 'INVOICE_NO':str})
##刪除數量 = 0 及負值
df = df[df['QUANTITY'] > 0]
#抓取不重複的INVOICE_NO值
df = df.drop_duplicates(['INVOICE_NO','ITEM_NO'],'first')
#把INVOICE_NO重複的值ITEM_NO相加
# df = df.groupby(by='INVOICE_NO').apply(lambda x: [",".join(map(str,x['ITEM_NO']))])
#
# # print("df =",df)
#
# for i in df:
# df_list.append(i[0].split(','))
df_list = df.groupby(by='INVOICE_NO').apply(lambda x:[(','.join(x['ITEM_NO']).split(','))][0])
print("df_list = " ,df_list)
#計算apriori開始時間
apriori_start_time = time.time()
#依照支持度 信心度 進行apriori的關聯規則探索
rules = list(apriori(df_list,min_support=0.005,min_confidence=0.5))
#計算apriori結束時間
apriori_end_time = time.time()
print("rules = " ,rules)
# for i in range(0,len(rules)):
# for j in range(0,len(rules[i][2])):
# for k in range(0,len(rules[i][2][j])):
# print(rules[i][2][j][k])
# print("-"*20)
for item in rules:
pair = item[0]
items = [x for x in pair]
print("Rule: " + items[0] + " -> " + items[1])
print("Support: " + str(item[1]))
print("Confidence: " + str(item[2][0][2]))
print("Lift: " + str(item[2][0][3]))
print("=====================================")
print("apriori cost time = %.2f\n" %(apriori_end_time-apriori_start_time))
#計算fg_growth開始時間
fp_growth_start_time = time.time()
#選擇支持度在100以上的
patterns = pyfpgrowth.find_frequent_patterns(df_list,25)
print("pattern = " ,patterns)
#選擇信心度在0.7以上的
FP_growth_rules = pyfpgrowth.generate_association_rules(patterns, 0.7)
#計算fg_growth結束時間
fp_growth_end_time = time.time()
for i,k in FP_growth_rules.items():
print("選擇的話 : ",i)
print("會被推測為會購買 : ",k)
print("-"*20)
print("FP-Growth cost time = %.2f" %(fp_growth_end_time-fp_growth_start_time))<file_sep>/hw3/main.py
# import os
# os.environ["PATH"] += os.pathsep + 'E:\\nltk_data'
from sklearn import datasets
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.cluster import DBSCAN
from nltk.corpus import stopwords
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram
from sklearn.cluster import AgglomerativeClustering
from time import time
import tarfile
import numpy as np
# 解壓縮
tar = tarfile.open("mini_newsgroups.tar.gz", "r:gz")
tar.extractall()
tar.close()
# 原始資料集
original_dataset = datasets.load_files('mini_newsgroups')
# 設定stopwords為英文
stopwords = set(stopwords.words('english'))
# 轉換編碼方式、並記錄頻率
tfv = TfidfVectorizer(encoding = 'ISO-8859-1', stop_words = stopwords)
trans_dataset = tfv.fit_transform(original_dataset.data).toarray()
'''
# K-means
t1 = time()
kmeans = KMeans(n_clusters = 20).fit(trans_dataset)
print('K-means')
print('花費時間:', time() - t1, '秒')
print('Silhouette Coefficient:', silhouette_score(trans_dataset, kmeans.labels_))
print('SSE:', kmeans.inertia_)
kmeans_list = {i: [int(x / 100 + 1) for x in np.where(kmeans.labels_ == i)[0]] for i in range(kmeans.n_clusters)}
purity_list = []
purity = 0
count = 0
for i in range(20):
for j in range(21):
if count < kmeans_list[i].count(j):
count = kmeans_list[i].count(j)
result = count / len(kmeans_list[i])
purity += len(kmeans_list[i]) / 2000 * result
print('purity:', purity)
'''
# DBSCAN
t2 = time()
dbscan = DBSCAN(eps = 1, min_samples = 4).fit(trans_dataset)
print('DBSCAN')
print('花費時間:', time() - t2, '秒')
dbscan_list = {i: [int(x / 100 + 1) for x in np.where(dbscan.labels_ == i)[0]] for i in range(dbscan.n_clusters)}
purity_list = []
purity = 0
count = 0
for i in range(20):
for j in range(21):
if count < dbscan_list[i].count(j):
count = dbscan_list[i].count(j)
result = count / len(dbscan_list[i])
purity += len(dbscan_list[i]) / 2000 * result
print('purity:', purity)
'''
# 階層式分群
def plot_dendrogram(model, **kwargs):
children = model.children_
distance = np.arange(children.shape[0])
no_of_observations = np.arange(2, children.shape[0]+2)
linkage_matrix = np.column_stack([children, distance, no_of_observations]).astype(float)
# Plot the corresponding dendrogram
dendrogram(linkage_matrix, **kwargs)
t3 = time()
hierarchical = AgglomerativeClustering(n_clusters=20)
hierarchical = hierarchical.fit(trans_dataset)
print('hierarchical')
print('花費時間:', time() - t3, '秒')
plt.title('Hierarchical Clustering Dendrogram')
plot_dendrogram(hierarchical, )
plt.savefig('dendrogram')
hiera_list = {i: [int(x / 100 + 1) for x in np.where(hierarchical.labels_ == i)[0]] for i in range(hierarchical.n_clusters)}
purity_list = []
purity = 0
count = 0
for i in range(20):
for j in range(21):
if count < hiera_list[i].count(j):
count = hiera_list[i].count(j)
result = count / len(hiera_list[i])
purity += len(hiera_list[i]) / 2000 * result
print('purity:', purity)
''' | dfa2215ea57bb78cc2bbd4c9d011e50114c0a183 | [
"Python"
]
| 11 | Python | s9891326/Data-Mining-homeWrok | 404174da03ae175d6274f9892d6683b104469b95 | c7d3358c0737876d0b02da6500d5daa8bc8e3d78 |
refs/heads/master | <file_sep># Avengers launch hype app
Just a little app I made because I'm excited about avengers infinity war.
Also wanted to learn how html parsing worked in golang. It's very powerful, if
a bit manual.
I claim no copyright for any of the movies in the Marvel Cinematic Universe.
<file_sep>package avengers
import (
"bytes"
"encoding/json"
"fmt"
htmlR "html"
"html/template"
"net/http"
"strconv"
"strings"
"time"
//"time"
"go.chromium.org/gae/impl/prod"
//"go.chromium.org/gae/service/datastore"
"go.chromium.org/gae/service/memcache"
"go.chromium.org/gae/service/urlfetch"
"go.chromium.org/luci/common/logging"
"golang.org/x/net/context"
"golang.org/x/net/html"
)
func init() {
http.HandleFunc("/", getIndex)
http.HandleFunc("/movies", getMCUMovieData)
http.HandleFunc("/release", getIWRelease)
}
var tpl = template.Must(template.ParseGlob("static/templates/*.html"))
func getIndex(w http.ResponseWriter, r *http.Request) {
if err := tpl.ExecuteTemplate(w, "index.html", nil); err != nil {
panic(err)
}
}
type nodePred func(*html.Node) bool
func hasChildId(id string) nodePred {
return func(n *html.Node) bool {
for c := n.FirstChild; c != nil; c = c.NextSibling {
for _, attr := range c.Attr {
if attr.Key == "id" && attr.Val == id {
return true
}
}
}
return false
}
}
func findNode(n *html.Node, nodeType string, pred nodePred) *html.Node {
if n.Type == html.ElementNode && n.Data == nodeType {
if pred(n) {
return n
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if res := findNode(c, nodeType, pred); res != nil {
return res
}
}
return nil
}
func nodeChildren(n *html.Node) []*html.Node {
arr := []*html.Node{}
for c := n.FirstChild; c != nil; c = c.NextSibling {
arr = append(arr, c)
}
return arr
}
// n is assumed to be a table
// This will break if not used on film.
func getHTMLTableColumn(c context.Context, n *html.Node, column string) []*html.Node {
// There's a weird newline we have to skip
n = n.FirstChild.NextSibling
if n.Data != "tbody" {
panic(fmt.Sprintf("bad node %v %v", n, textContent(n)))
}
vals := []*html.Node{}
idx := -1
// First child should be a header row
for i, cc := range nodeChildren(n.FirstChild) {
if strings.HasPrefix(textContent(cc), column) {
idx = i
break
}
}
for ch := n.FirstChild.NextSibling; ch != nil; ch = ch.NextSibling {
itms := nodeChildren(ch)
if len(itms) == 0 {
continue
}
vals = append(vals, itms[idx])
}
return vals
}
func textContent(n *html.Node) string {
if n.Type == html.TextNode {
return n.Data
}
s := ""
for c := n.FirstChild; c != nil; c = c.NextSibling {
s += textContent(c)
}
if len(s) > 0 {
return s
}
return ""
}
func getAttr(attrs []html.Attribute, name string) string {
for _, a := range attrs {
if a.Key == name {
return a.Val
}
}
return ""
}
func getMovies(c context.Context, doc *html.Node, phaseIds ...string) []*Movie {
movies := []*Movie{}
for _, phaseId := range phaseIds {
phaneNode := findNode(doc, "h2", hasChildId(phaseId))
tblNode := phaneNode.NextSibling
if tblNode.Type == html.TextNode {
tblNode = tblNode.NextSibling
}
tableVal := getHTMLTableColumn(c, tblNode, "Film")
for _, n := range tableVal {
name := textContent(n)
linkNode := n.FirstChild.FirstChild
movies = append(movies, &Movie{
Name: name,
Phase: strings.Replace(phaseId, "_", " ", -1),
Runtime: getRuntime(c, name, getAttr(linkNode.Attr, "href")),
})
}
}
return movies
}
func getRuntime(c context.Context, title, href string) int {
// Fake for now, lazy about getting these values
//return 120
itm := memcache.NewItem(c, fmt.Sprintf("runtime|%v", title))
err := memcache.Get(c, itm)
isCacheMiss := err == memcache.ErrCacheMiss
if err != nil {
doc, err := getWebpage(c, "https://en.wikipedia.org"+href)
if err != nil {
panic(err)
}
phaneNode := findNode(doc, "tr", func(n *html.Node) bool {
if n.FirstChild == nil {
return false
}
n = n.FirstChild.NextSibling
if n == nil || n.FirstChild == nil || n.Data != "th" {
return false
}
n = n.FirstChild.NextSibling
if n == nil {
return false
}
return strings.TrimSpace(textContent(n)) == "Running time"
})
valNode := phaneNode.FirstChild.NextSibling.NextSibling.NextSibling.FirstChild
logging.Warningf(c, "found %v", textContent(valNode))
split := strings.Split(valNode.Data, " ")
if split[1] != "minutes" {
panic(fmt.Sprintf("weird %v", split))
}
val, err := strconv.Atoi(split[0])
if err != nil {
panic(err)
}
itm.SetValue([]byte{byte(val)})
if isCacheMiss {
err := memcache.Set(c, itm)
if err != nil {
panic(err)
}
}
}
return int(itm.Value()[0])
}
type Movie struct {
Name string `json:"name"`
Runtime int `json:"runtime"`
Phase string `json:"phase"`
}
func getMCUMovieData(w http.ResponseWriter, r *http.Request) {
c := context.Background()
c = prod.Use(c, r)
movies := []*Movie{}
itm := memcache.NewItem(c, "mcumovies")
err := memcache.Get(c, itm)
if err != memcache.ErrCacheMiss && err != nil {
panic(err)
}
if err == memcache.ErrCacheMiss {
doc, err := getWebpage(c, "https://en.wikipedia.org/wiki/List_of_Marvel_Cinematic_Universe_films")
if err != nil {
panic(err)
}
movies = getMovies(c, doc, "Phase_One", "Phase_Two", "Phase_Three")
res, err := json.Marshal(movies)
if err != nil {
panic(err)
}
itm.SetValue(res)
//err = memcache.Set(c, itm)
//if err != nil {
//panic(err)
//}
}
w.WriteHeader(200)
w.Write(itm.Value())
}
func getWebpage(c context.Context, url string) (*html.Node, error) {
rt := urlfetch.Get(c)
req, err := http.NewRequest("GET", url, bytes.NewReader(nil))
if err != nil {
panic(err)
}
resp, err := rt.RoundTrip(req)
if err != nil {
panic(err)
}
return html.Parse(resp.Body)
}
func getIWRelease(w http.ResponseWriter, r *http.Request) {
c := context.Background()
c = prod.Use(c, r)
itm := memcache.NewItem(c, "releasedate")
err := memcache.Get(c, itm)
if err != memcache.ErrCacheMiss && err != nil {
panic(err)
}
if err == memcache.ErrCacheMiss {
doc, err := getWebpage(c, "https://en.wikipedia.org/wiki/Avengers:_Infinity_War")
phaneNode := findNode(doc, "tr", func(n *html.Node) bool {
if n.FirstChild == nil {
return false
}
n = n.FirstChild.NextSibling
if n == nil || n.FirstChild == nil || n.Data != "th" {
return false
}
n = n.FirstChild.NextSibling
if n == nil {
return false
}
return strings.TrimSpace(textContent(n)) == "Release date"
})
// :)
dateNode := phaneNode.FirstChild.NextSibling.NextSibling.NextSibling.FirstChild.NextSibling.FirstChild.NextSibling.FirstChild.NextSibling
dateNode = dateNode.FirstChild
txt := htmlR.UnescapeString(textContent(dateNode))
logging.Warningf(c, "found %v", txt)
txt = string(bytes.Replace([]byte(txt), []byte{194, 160}, []byte(nil), -1))
logging.Warningf(c, "found %v", txt)
const longForm = "Jan2,2006"
t, err := time.Parse(longForm, txt)
if err != nil {
panic(err)
}
logging.Warningf(c, "got %v", t)
d, err := t.MarshalJSON()
if err != nil {
panic(err)
}
itm.SetValue(d)
err = memcache.Set(c, itm)
if err != nil {
panic(err)
}
}
w.WriteHeader(200)
w.Write(itm.Value())
}
| 4350cef81c9f549f38fefc369ace04e86ada0764 | [
"Markdown",
"Go"
]
| 2 | Markdown | moowiz/avengers_time_app | dc4453c3893e5a4177d8c603db97fe05c097a8ff | 68878cbc1d4ed1ed095d60eb5596930487db2263 |
refs/heads/master | <file_sep>package com.eip.sorting;
import java.util.Arrays;
public class MergeSort {
public int[] sort(int[] array) {
int length = array.length;
if (length < 2) {
return array;
} else {
int median = (int) Math.floor(length / 2);
int[] leftAarry = Arrays.copyOfRange(array, 0, median);
int[] rightArray = Arrays.copyOfRange(array, median, length);
return merge(sort(leftAarry), sort(rightArray));
}
}
private int[] merge(int[] left, int[] right) {
int lLeft = left.length;
int lRight = right.length;
int[] result = new int[lLeft + lRight];
int i = 0, j = 0, nextIndex = 0;
while (i < lLeft && j < lRight) {
if (left[i] < right[j]) {
result[nextIndex++] = left[i++];
} else {
result[nextIndex++] = right[j++];
}
}
while (i < lLeft) {
result[nextIndex++] = left[i++];
}
while (j < lRight) {
result[nextIndex++] = right[j++];
}
return result;
}
}<file_sep>package com.eip.algos;
import java.util.HashMap;
import java.util.Map;
public class ArrayContainsDuplicate {
public boolean containsDuplicate(int[] nums) {
if(nums == null) return false;
if(nums.length == 1) return false;
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
int val = nums[i];
if(map.containsKey(val)) {
return true;
}
map.put(val,val);
}
return false;
}
}<file_sep>package com.eip.arrays;
import java.util.Arrays;
public class BinarySearch {
public int binarySearch(int[] inputArray, int value) {
return binarySearchRec(inputArray, value, 0, inputArray.length - 1);
}
public int binarySearchRec(int[] inputArray, int value, int left, int right) {
if (inputArray == null) {
return -1;
}
int median = (int) (left + right) / 2;
if (inputArray[median] == value) {
return median;
} else if (inputArray[median] > value) {
right = median - 1;
return binarySearchRec(inputArray, value, left, right);
} else if (inputArray[median] < value) {
left = median + 1;
return binarySearchRec(inputArray, value, left, right);
}
return -1;
}
}
<file_sep>package com.eip.tree;
public class Tree {
public static int maxDepth(TreeNode node) {
if (node == null)
return 0;
else {
int lDepth = maxDepth(node.left);
int rDepth = maxDepth(node.right);
if (lDepth > rDepth)
return (lDepth + 1);
else
return (rDepth + 1);
}
}
}<file_sep>package com.eip.tree;
public class BinarySearchTree {
Node root;
public void addNode(int data) {
root = addRec(root, data);
}
private Node addRec(Node root, int data) {
if (root == null) {
root = new Node(data);
return root;
}
if (data < root.data) {
root.left = addRec(root.left, data);
} else if (data > root.data) {
root.right = addRec(root.right, data);
}
return root;
}
public boolean isBalancedTree() {
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
int depthDiff = Math.abs(leftDepth - rightDepth);
return depthDiff < 2;
}
private int getDepth(Node node) {
return getDepthRec(node, 0, 0);
}
private int getDepthRec(Node node, int leftDepth, int rightDepth) {
if (node == null) {
return 0;
}
if (node.left != null) {
leftDepth = 1 + getDepthRec(node.left, leftDepth, rightDepth);
}
if (node.right != null) {
rightDepth = 1 + getDepthRec(node.right, leftDepth, rightDepth);
}
return Math.max(leftDepth, rightDepth);
}
public void traverseInOrder() {
traverseInOrderRec(root);
}
public void traversePreOrder() {
traversePreOrderRec(root);
}
public void traversePostOrder() {
traversePostOrderRec(root);
}
private boolean traverseInOrderRec(Node node) {
if (node == null) {
return false;
}
traverseInOrderRec(node.left);
System.out.println(node.data);
traverseInOrderRec(node.right);
return true;
}
private boolean traversePreOrderRec(Node node) {
if (node == null) {
return false;
}
System.out.println(node.data);
traversePreOrderRec(node.left);
traversePreOrderRec(node.right);
return true;
}
private boolean traversePostOrderRec(Node node) {
if (node == null) {
return false;
}
traversePostOrderRec(node.left);
traversePostOrderRec(node.right);
System.out.println(node.data);
return true;
}
class Node {
private int data;
private Node left;
private Node right;
public Node(int data) {
this.data = data;
}
}
}
class Node {
private int data;
private Node left;
private Node right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
<file_sep>package com.eip.algos;
import com.eip.linkedList.LinkedList;
import com.eip.linkedList.LinkedListNode;
public class AddNumbers {
public LinkedList addTwoNumbers(LinkedList numList1, LinkedList numList2) {
if (numList1 == null) {
return numList2;
}
if (numList2 == null) {
return numList1;
}
LinkedListNode head1 = numList1.head;
LinkedListNode head2 = numList2.head;
LinkedList result = new LinkedList();
int sum = 0;
int remainder = 0;
int quotient = 0;
while (head1.getNext() != null && head2.getNext() != null) {
int currSum = Integer.parseInt(head1.getData()) + Integer.parseInt(head2.getData());
quotient = currSum / 10;
if (currSum < 10) {
result.addNodeAtEnd(String.valueOf(currSum));
} else if(currSum >= 10) {
if (currSum % 10 != 0) {
remainder = currSum % 10;
}
}
}
return null;
}
public static void main(String[] args) {
System.out.println(2 / 10);
}
}<file_sep>package com.eip.sorting;
import java.util.Arrays;
public class MergeSortClient {
public static void main(String[] args) {
MergeSort mergeSort = new MergeSort();
int[] result = mergeSort.sort(new int[] { 1, 3, 4, 6, 2, 8 });
Arrays.stream(result).forEach(System.out::println);
}
}<file_sep># eip-ds-algos<file_sep>package com.eip.mfp;
import java.util.ArrayList;
import java.util.List;
public class PrimeNumbers {
// runtime O(n)
private static boolean isPrime(int number) {
boolean isprime = true;
for (int i = 2; i < number; i++) {
if (number % i == 0) {
isprime = false;
}
}
return isprime;
}
// optimized based on number property
// that if we have any number that divides n with in root n, then n is not prime
// else n is prime
// runtime o(sqrt(n))
private static boolean isPrimeOpt(int number) {
boolean isPrime = true;
for (int i = 2; i < Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
}
}
return isPrime;
}
// runtime o(n . sqrt(n))
private static List findAllPrimes(int number) {
List<Integer> primeNumbers = new ArrayList();
for (int i = 2; i <= number; i++) {
if (isPrimeOpt(i)) {
primeNumbers.add(i);
}
}
return primeNumbers;
}
// This method is using sieve of eratosthenes algorithm to find primes
private static int[] findAllPrimesSOE(int number) {
int[] primeNumbers = new int[number + 1];
for (int i = 2; i <= number; i++) {
primeNumbers[i] = 1;
}
for (int i = 2; i <= number; i++) {
if (isPrimeOpt(i) && primeNumbers[i] == 1) {
for (int j = 2; i * j < number; j++) {
primeNumbers[i * j] = 0;
}
}
}
return primeNumbers;
}
public static void main(String args[]) {
int[] primes = findAllPrimesSOE(100);
for (int i = 0; i <= primes.length - 1; i++) {
if (primes[i] == 1) {
System.out.println(i);
}
}
}
}<file_sep>package com.eip.arrys;
import com.eip.arrays.BinarySearch;
public class BinarySearchClient {
public static void main(String args[]) {
BinarySearch binarySearch = new BinarySearch();
System.out.println(binarySearch.binarySearch(new int[] { 1, 2, 3, 4, 5, 6 }, 6));
}
/* if (inputArray.length == 2) {
if(inputArray[0] == value){
return 0
}
if(inputArray[1] == value){
return 1
}
else{
return -1;
}
}
int median = (int) Math.floor(inputArray.length / 2);
int left = 0;
int right = inputArray.length - 1;
if (inputArray[median] == value) {
return median;
} else if (inputArray[median] < value) {
left = median + 1;
return binarySearch(Arrays.copyOfRange(inputArray, left, right), value);
} else if (inputArray[median] > value) {
right = median - 1;
return binarySearch(Arrays.copyOfRange(inputArray, left, right), value);
}
return -1; */
} | 20f4c72f98e468a0f38a5d7cd1cecbc374d58cde | [
"Markdown",
"Java"
]
| 10 | Java | Mallesh2088/eip-ds-algos | fd501f50dbc7bb58097242dfd9e38de99af980ac | 4b52c373567f292d8ad2a09de129182dd222efd2 |
refs/heads/master | <file_sep>---
title: "Chicago Bikedata Analysis"
author: "<NAME>"
date: "06/06/2019"
output: html_document
---
```{r setup, include=FALSE}
library(forecast)
library(ggplot2)
library(dplyr)
library(lubridate)
library(tidyverse)
library(lvplot)
library(ggridges)
library(tsibble)
library(bikedata)
library(gravitas)
```
```{r dataextract, echo=FALSE}
#extract chicago datas for 2017 and 2018
# chicago <- dl_bikedata (city = 'divvy', dates = 2017:2018, data_dir = "bikedata/Data", quiet = TRUE)
# 2018 data doesn't exist
# nyc citibikes for 2017 and 2018 downloaded
#nyc <- dl_bikedata (city = 'citibike', dates = 2017:2018, data_dir = "bikedata/Data", quiet = TRUE)
# 48 monthly files downloaded
# file_list <- list.files("bikedata/Data")
#
# for (file in file_list){
#
# # if the merged dataset doesn't exist, create it
# if (!exists("dataset")){
# dataset <- read.table(file, header=TRUE, sep="\t")
# }
#
# # if the merged dataset does exist, append to it
# if (exists("dataset")){
# temp_dataset <-read.table(file, header=TRUE, sep="\t")
# dataset<-rbind(dataset, temp_dataset)
# rm(temp_dataset)
# }
#
# }
```
#Data Description
1. Trip Duration (seconds) — How long a trip lasted
2. Start Time and Date - time and date where trip started
3. Stop Time and Date - time and date where trip ended
4. Start/End Station ID - Unique identifier for starting/end bike station
5. Start/End Station Name - Brief address for starting/end bike station
6. Start Station Latitude/Longitude - Coordinates
7. Bike ID - unique identifier for each bike
8. User Type (Customer = 24-hour pass or 3-day pass user; Subscriber = Annual Member) - Customers are usually tourists, subscribers are usually NYC residents
9. Year of Birth
10. Gender (Zero=unknown; 1=male; 2=female)
```{r overall_view, echo=FALSE}
nyc_bikes <- tsibbledata::nyc_bikes %>% as_tsibble()
summary(nyc_bikes)
# Top 20 Bike stations by number of starts
top_bikes <- nyc_bikes %>%as_tibble() %>% group_by(start_station) %>% summarise(count = n()) %>% arrange(-count)
nyc_all <- nyc_bikes %>%
as_tibble() %>%
dplyr::select(start_station, start_lat, start_long)%>%
right_join(top_bikes) %>% distinct()
ggplot(nyc_all) + geom_polygon(aes(start_long, start_lat,fill=count)) + scale_fill_continuous(type="gradient") +
coord_map()
```
```{r popular_bikes}
top_bikes <- nyc_bikes %>%as_tibble() %>% group_by(start_station) %>% summarise(count = n()) %>% arrange(-count) %>% slice(1:20)
top_bikes %>%ggplot(aes(x = reorder(start_station, -count), y= count)) + geom_bar(stat="identity")
```
```{r busiest_bike_behavior}
devtools::install_github("Sayani07/gravitas")
rides_busiest <- tsibbledata::nyc_bikes %>% filter(start_station %in% c(3186, 3203)|end_station %in% c(3186, 3203))
summary(rides_busiest)
rides_busiest_grans <- rides_busiest %>% mutate(hour_day = nest("hour", "day", start_time),
month_year = nest("month", "year", start_time),
day_week = nest("day", "week", start_time, abbr),
hhour_day = nest("hhour", "day", start_time),
minute_hour = nest("minute", "hour", start_time),
hhour_hour = nest("hhour", "hour", start_time))
rides_busiest_grans %>%
as_tibble %>% group_by(hour_day) %>%
summarise(Count = n()) %>%
ggplot(aes(x = hour_day, y= Count)) + geom_col() + scale_x_continuous(breaks = seq(0, 23, 1))
#8am and 6pm experiences maximum rush in terms of rides
rides_busiest_grans %>%
as_tibble %>% group_by(day_week) %>%
summarise(Count = n()) %>%
ggplot(aes(x = day_week, y= Count)) + geom_col() + scale_x_continuous(breaks = seq(1, 7, 1))
#Monday has lowest count when compared with other days of the week
rides_busiest_grans %>%
as_tibble %>% group_by(minute_hour) %>%
summarise(Count = n()) %>%
ggplot(aes(x = minute_hour, y= Count)) + geom_line()
rides_busiest_grans %>%
as_tibble %>% group_by(month_year) %>%
summarise(Count = n()) %>%
ggplot(aes(x = month_year, y= Count)) + geom_line() + scale_x_continuous(breaks = seq(1,12,1))
# Mostly in summer months counts are more
granplot = function(data, x, y) {
data %>% as_tibble %>% group_by(!!sym(x), !!sym(y)) %>%
summarise(ecount = n()) %>%
ggplot(aes(x = !!sym(x), y = ecount)) +
geom_line() +
theme_bw() +
facet_wrap(as.formula(paste("~", y))) +
ylab("Total Count") +
ggtitle(paste0("Plot of ", x, " given ", y))
}
granplot(rides_busiest_grans, "hhour_day", "day_week")
#
granplot(rides_busiest_grans, "hour_day", "day_week")
# No peaks on Monday and total counts across hours are less compared to other days
granplot(rides_busiest_grans, "day_week", "month_year")
# During Summers, high ride shares on weekends are observed. In Winters (Nov - February), counts are much less for all days of the week
granplot(rides_busiest_grans, "hour_day", "day_week")
# Peaks are at different times of the day on Sunday(compared to other days), also there are more than 2 peaks
granplot(rides_busiest_grans, "hour_day", "hhour_hour")
# For first peak (around 8am) first half hour of the hour sees more count, while during the evening peak, later half hour sees more count.
```
```{r}
```
<file_sep>---
title: "Exploration of example data"
author: "<NAME>"
date: "27/05/2019"
output: html_document
---
```{r setup, include=FALSE}
library(forecast)
library(ggplot2)
library(dplyr)
library(lubridate)
library(tidyverse)
library(lvplot)
library(ggridges)
library(tsibble)
```
- **Frequency** ~ 30 minutes interval smart meter data
- **Time frame** ~ January, 2012 to December 31, 2014
- **Spread** ~ Australian State (Victoria)
```{r allFig, fig.height=5.5, out.width="50%", fig.pos = "p", fig.align= 'left',echo=FALSE, eval=TRUE, fig.cap="Various probability distribution plots of electricity consumption data of Victoria from 2012 to 2014. (a)-(b) are examples of Harmonies (c)-(e) are examples of Clashes", fig.show = 'hold'}
VIC <- read.csv("VIC2015/Data/demand_VIC.csv")
VIC$Date <- as.Date(VIC$Date,origin = "1899-12-30")
first_day_of_month_wday <- function(dx) {
day(dx) <- 1
wday(dx)
}
VIC <- VIC %>%mutate(Indx_Year = year(Date),
Indx_Month = month(Date, label = FALSE, abbr = TRUE),
Indx_Wk_Yr = week(Date),
Indx_Wk_Month = ceiling((day(Date) + first_day_of_month_wday(Date) - 1) / 7),
Indx_Day_Week = wday(Date, label=FALSE, abbr=TRUE,
week_start=1),
Indx_Day_Month = day(Date),
Indx_Day_Year = yday(Date),
Indx_Weekend=if_else(Indx_Day_Week %in% c(6,7),1,0),
Indx_HlHr_day = Period,
month = month(Date, label = FALSE, abbr = TRUE),
year = year(Date),
yday =yday(Date),
wday = wday(Date, label=FALSE, abbr=TRUE,
week_start=1),
bow = (wday - 1) * 48 + Period,
dom = day(Date),
bom = (dom - 1) * 48 + Period,
Weekend=if_else(wday %in% c(6,7),1,0),
Indx_hour = ceiling(Period/2),
Indx_Hour_Yr = Indx_hour + 24*(yday-1),
Indx_Hour_Month = Indx_hour + 24*(Indx_Day_Month-1),
Indx_Hour_Wk = Indx_hour + 24*(wday-1))
VIC <- as_tibble(VIC)
par(mfrow = c(3, 2))
VIC%>% filter(year %in% c(2012, 2013, 2014),Indx_Month %in% c(1,2,4,12))%>% ggplot(aes(Indx_Day_Month,OperationalLessIndustrial,group = Indx_Day_Month)) + geom_lv(aes(fill=..LV..),outlier.colour = "red",outlier.shape = 1) + scale_fill_brewer()+ facet_wrap(~Indx_Month) + ylab("Electricity Demand [KWh]") + xlab("Days of the Month") + scale_x_continuous(breaks=seq(0,31,5)) + ggtitle("(a) Letter value plot by DoM and MoY")
VIC_hod_dow <- VIC%>% filter(year %in% c(2012, 2013, 2014)) %>%
group_by(wday,Indx_hour) %>%
do({x <- .$OperationalLessIndustrial
map_dfr(.x = seq(0.1,0.9,0.1),
.f = ~ tibble(Quantile = .x,
Value = quantile(x, probs = .x,na.rm=TRUE)))
}) %>% filter(wday %in% c(1,2,6,7))
VIC_hod_dow %>%ggplot(aes(x=Indx_hour,y=Value,col=as.factor(Quantile))) + geom_line() + facet_wrap(~wday) + scale_x_continuous(breaks=seq(1, 24,5)) + ylab("") + xlab("Day of the Week") + theme(legend.position = "none",strip.text = element_text(size = 7, margin = margin())) + ggtitle("(b) Decile plot by HoD and DoW ")
VIC%>% filter(year %in% c(2012, 2013, 2014),Indx_Day_Month %in% c(1,15,29,31))%>% ggplot(aes(as.factor(yday),OperationalLessIndustrial,group = yday)) + geom_boxplot()+ facet_wrap(~Indx_Day_Month) + ylab("Electricity Demand [KWh]") +
xlab("Days of the Year") + scale_x_discrete(breaks=seq(0,366,60)) +theme(legend.position = "bottom",strip.text = element_text(size = 7, margin = margin())) + ggtitle("(c) Box plot by DoY and DoM")
VIC%>% filter(year %in% c(2012, 2013, 2014),Indx_Wk_Month %in% c(1,2,4))%>% ggplot(aes(as.factor(Indx_Day_Month),OperationalLessIndustrial)) + geom_violin(alpha = 0.03)+ facet_wrap(~Indx_Wk_Month,nrow=3) + ylab("") + xlab("Days of the Month") + theme(legend.position = "bottom",strip.text = element_text(size = 7, margin = margin())) + scale_x_discrete(breaks=seq(0,31,5))+ scale_y_continuous(breaks = seq(2000,9000,2000))+ ggtitle("(d) Violin plot of DoM and WoM")
VIC%>% dplyr:::filter(year %in% c(2012, 2013, 2014),Indx_Wk_Month %in% c(1,2,5),Indx_Wk_Yr <20)%>% ggplot(aes(x=OperationalLessIndustrial,y=as.factor(Indx_Wk_Yr),group=Indx_Wk_Yr)) + geom_density_ridges2() +facet_wrap(~Indx_Wk_Month) + xlab("Electricity Demand [KWh]") + ylab("Weeks of the Year") + scale_x_continuous(breaks = seq(2000,10000,3000)) + theme(legend.position = "bottom",strip.text = element_text(size = 7, margin = margin())) + ggtitle("(e) Ridge plot by WoM and WoY")
VIC_moy_doy <- VIC%>% filter(year %in% c(2012, 2013, 2014)) %>%
group_by(Indx_Month,yday) %>%
do({x <- .$OperationalLessIndustrial
map_dfr(.x = seq(0.1,0.9,0.1),
.f = ~ tibble(Quantile = .x,
Value = quantile(x, probs = .x,na.rm=TRUE)))
}) %>% filter(Indx_Month %in% c(1,7,11))
VIC_moy_doy %>%ggplot(aes(x=yday,y=Value,col=as.factor(Quantile),group=yday)) + geom_line() + facet_wrap(~Indx_Month)+ scale_x_continuous(breaks=seq(1, 336, 60)) + ylab("") + xlab("Day of the Year") + theme(legend.position = "none",strip.text = element_text(size = 7, margin = margin())) + ggtitle("(f) Decile plot by DoY and MoY.")
```
- **Frequency** ~ 30 minutes interval smart meter data
- **Time frame** ~ January, 2012 to December 31, 2014
- **Spread** ~ Australian State (Tasmania)
```{r allFig1s, fig.height=5.5, out.width="50%", fig.pos = "p", fig.align= 'left',echo=FALSE, eval=TRUE, fig.cap="Various probability distribution plots of electricity consumption data of Tasmania from 2012 to 2014. (a)-(b) are examples of Harmonies (c)-(e) are examples of Clashes", fig.show = 'hold'}
TAS <- read.csv("TAS2015/Data/demand_TAS.csv")
TAS$Date <- as.Date(TAS$Date,origin = "1899-12-30")
first_day_of_month_wday <- function(dx) {
day(dx) <- 1
wday(dx)
}
TAS <- TAS %>%mutate(Indx_Year = year(Date),
Indx_Month = month(Date, label = FALSE, abbr = TRUE),
Indx_Wk_Yr = week(Date),
Indx_Wk_Month = ceiling((day(Date) + first_day_of_month_wday(Date) - 1) / 7),
Indx_Day_Week = wday(Date, label=FALSE, abbr=TRUE,
week_start=1),
Indx_Day_Month = day(Date),
Indx_Day_Year = yday(Date),
Indx_Weekend=if_else(Indx_Day_Week %in% c(6,7),1,0),
Indx_HlHr_day = Period,
month = month(Date, label = FALSE, abbr = TRUE),
year = year(Date),
yday =yday(Date),
wday = wday(Date, label=FALSE, abbr=TRUE,
week_start=1),
bow = (wday - 1) * 48 + Period,
dom = day(Date),
bom = (dom - 1) * 48 + Period,
Weekend=if_else(wday %in% c(6,7),1,0),
Indx_hour = ceiling(Period/2),
Indx_Hour_Yr = Indx_hour + 24*(yday-1),
Indx_Hour_Month = Indx_hour + 24*(Indx_Day_Month-1),
Indx_Hour_Wk = Indx_hour + 24*(wday-1))
TAS <- as_tibble(TAS)
par(mfrow = c(3, 2))
TAS%>% filter(year %in% c(2012, 2013, 2014),Indx_Month %in% c(1,2,4,12))%>% ggplot(aes(Indx_Day_Month,OperationalLessIndustrial,group = Indx_Day_Month)) + geom_lv(aes(fill=..LV..),outlier.colour = "red",outlier.shape = 1) + scale_fill_brewer()+ facet_wrap(~Indx_Month) + ylab("Electricity Demand [KWh]") + xlab("Days of the Month") + scale_x_continuous(breaks=seq(0,31,5)) + ggtitle("(a) Letter value plot by DoM and MoY")
TAS_hod_dow <- TAS%>% filter(year %in% c(2012, 2013, 2014)) %>%
group_by(wday,Indx_hour) %>%
do({x <- .$OperationalLessIndustrial
map_dfr(.x = seq(0.1,0.9,0.1),
.f = ~ tibble(Quantile = .x,
Value = quantile(x, probs = .x,na.rm=TRUE)))
}) %>% filter(wday %in% c(1,2,6,7))
TAS_hod_dow %>%ggplot(aes(x=Indx_hour,y=Value,col=as.factor(Quantile))) + geom_line() + facet_wrap(~wday) + scale_x_continuous(breaks=seq(1, 24,5)) + ylab("") + xlab("Day of the Week") + theme(legend.position = "none",strip.text = element_text(size = 7, margin = margin())) + ggtitle("(b) Decile plot by HoD and DoW ")
TAS%>% filter(year %in% c(2012, 2013, 2014),Indx_Day_Month %in% c(1,15,29,31))%>% ggplot(aes(as.factor(yday),OperationalLessIndustrial,group = yday)) + geom_boxplot()+ facet_wrap(~Indx_Day_Month) + ylab("Electricity Demand [KWh]") +
xlab("Days of the Year") + scale_x_discrete(breaks=seq(0,366,60)) +theme(legend.position = "bottom",strip.text = element_text(size = 7, margin = margin())) + ggtitle("(c) Box plot by DoY and DoM")
TAS%>% filter(year %in% c(2012, 2013, 2014),Indx_Wk_Month %in% c(1,2,4))%>% ggplot(aes(as.factor(Indx_Day_Month),OperationalLessIndustrial)) + geom_violin(alpha = 0.03)+ facet_wrap(~Indx_Wk_Month,nrow=3) + ylab("") + xlab("Days of the Month") + theme(legend.position = "bottom",strip.text = element_text(size = 7, margin = margin())) + scale_x_discrete(breaks=seq(0,31,5))+ scale_y_continuous(breaks = seq(2000,9000,2000))+ ggtitle("(d) Violin plot of DoM and WoM")
TAS%>% dplyr:::filter(year %in% c(2012, 2013, 2014),Indx_Wk_Month %in% c(1,2,5),Indx_Wk_Yr <20)%>% ggplot(aes(x=OperationalLessIndustrial,y=as.factor(Indx_Wk_Yr),group=Indx_Wk_Yr)) + geom_density_ridges2() +facet_wrap(~Indx_Wk_Month) + xlab("Electricity Demand [KWh]") + ylab("Weeks of the Year") + scale_x_continuous(breaks = seq(2000,10000,3000)) + theme(legend.position = "bottom",strip.text = element_text(size = 7, margin = margin())) + ggtitle("(e) Ridge plot by WoM and WoY")
TAS_moy_doy <- TAS%>% filter(year %in% c(2012, 2013, 2014)) %>%
group_by(Indx_Month,yday) %>%
do({x <- .$OperationalLessIndustrial
map_dfr(.x = seq(0.1,0.9,0.1),
.f = ~ tibble(Quantile = .x,
Value = quantile(x, probs = .x,na.rm=TRUE)))
}) %>% filter(Indx_Month %in% c(1,7,11))
TAS_moy_doy %>%ggplot(aes(x=yday,y=Value,col=as.factor(Quantile),group=yday)) + geom_line() + facet_wrap(~Indx_Month)+ scale_x_continuous(breaks=seq(1, 336, 60)) + ylab("") + xlab("Day of the Year") + theme(legend.position = "none",strip.text = element_text(size = 7, margin = margin())) + ggtitle("(f) Decile plot by DoY and MoY.")
```
**Source** ~ Buildings and Property Division at Monash University **Frequency** ~ 30 minutes interval smart meter data of Monash Residential Services **Time frame** ~ April 4, 2018 to May 31, 2018, **Spread** ~ 73 living units
Living units chosen: B4 29/B3 37
```{r okaygraph1,fig.height=6, fig.width=4, echo=FALSE}
DHR <-read_rds("DHResidence.rds")
selected_units <- DHR %>% filter(Source %in% c("B3 37","B2 15","B3 37", "B4 29", "BG 50"))
selected_units$`Timestamp UTC` <-lubridate::ymd_hms(selected_units$`Timestamp UTC`)
# selected_units_tsibble <- as_tsibble(selected_units,key=id(Source),index=`Timestamp UTC`,tz="UTC")
vic_holidays <- holiday_aus(2018, state = "VIC")
SU_uniform_mutate <-selected_units %>% mutate(date = date(`Timestamp UTC`),wday = wday(date, label = TRUE, abbr = TRUE,
week_start = 1),
month = month(date, label = TRUE, abbr = TRUE),
year = year(date),
hour = hour(`Timestamp UTC`),
work = ifelse(wday %in% c("Mon", "Tue", "Wed", "Thu", "Fri"), "Yes", "No"))
# p1 = SU_uniform_mutate %>% filter(Source=="B3 37") %>%
# dplyr::group_by(date,wday) %>%
# summarise(dkwh = sum(Value, na.rm=TRUE)) %>%
# ggplot(aes(x=wday, y=dkwh)) + geom_boxplot() + ylab("Energy consumption in KwH ") + xlab("Day-of-Week")
p12 = SU_uniform_mutate %>% filter(Source=="B4 29") %>%
group_by(date,wday) %>%
summarise(dkwh = sum(Value, na.rm=TRUE)) %>%
ggplot(aes(x=wday, y=dkwh)) + geom_boxplot() + ylab("Energy consumption in KwH ") + xlab("Day-of-Week") + coord_cartesian(ylim = c(0,25)) + ggtitle("a) Across DoY - B4 29")
p12
p22 = SU_uniform_mutate %>% filter(Source=="B3 37") %>%
group_by(date,wday) %>%
summarise(dkwh = sum(Value, na.rm=TRUE)) %>%
ggplot(aes(x=wday, y=dkwh)) + geom_boxplot() + ylab("Energy consumption in KwH ") + xlab("Day-of-Week")+ coord_cartesian(ylim = c(0,25)) + ggtitle("b) Across DoW - B3 37")
p22
```
From a) and b), we observe that:
For B4 29, median energy consumption and variation on weekends are higher than weekdays. The same can't be observed for B3 37, where median consumption and variation remains unifrom for all days of the week.
For B3 37, pretty stable Wednesday and Thursdays compared to other weekdays. Also Saturday has less variation and consumption compared to Sundays.
Next, we might be interested in knowing if these variation are a result of varied behavior only for certain hours of the day or through out the day.
```{r DoW_HoD, echo=FALSE}
p14 = SU_uniform_mutate %>% filter(Source=="B4 29") %>%
group_by(wday,hour) %>% filter(wday %in% c("Tue","Wed","Thu","Fri","Sat","Sun")) %>%
ggplot(aes(x=as.factor(hour), y=Value, group=hour)) + geom_boxplot() +
facet_wrap(~wday) +
ylab("Daily Consumption in KwH") +
xlab("Hour-of-Day") +
coord_cartesian(xlim= c(0,23), ylim = c(0,0.75))+ scale_x_discrete(breaks=c(0,5,10,15,20))+ ggtitle("B4 29")+ ggtitle("c) Across DOW and HoD - B4 29")
p14
p24 = SU_uniform_mutate %>% filter(Source=="B3 37") %>%
group_by(wday,hour) %>% filter(wday %in% c("Tue","Wed","Thu","Fri","Sat","Sun")) %>%
ggplot(aes(x=as.factor(hour), y=Value, group=hour)) + geom_boxplot() +
facet_wrap(~wday) +
ylab("Daily Consumption in KwH") +
xlab("Hour-of-Day") +
coord_cartesian(xlim= c(0,23), ylim = c(0,0.75))+ scale_x_discrete(breaks=c(0,5,10,15,20))+ ggtitle("B4 29")+ ggtitle("d) Across DoW and HoD - B3 37")
p24
```
From c) suggests that the high variation in energy usage on Wednesday compared to other weekdays can only be attributed to the energy behavior from roughly 10am -1pm. Also, the same hours are responsible for difference in variation between Sunday and Wednesday.
From d) suggests Saturday and Sunday are similar after 5pm. The increased variation on Sunday can be the result of variation only in the early morning hours of Sunday.
```{r HoD,WD_NWD, echo=FALSE}
s1 <- SU_uniform_mutate %>%
mutate(work = ifelse(date %in% vic_holidays$date, "No", work))
b12_Quantile <- s1 %>% filter(Source=="B4 29") %>% group_by(work,hour) %>%
do({x <- .$Value
map_dfr(.x = seq(0.1,0.9,0.1),
.f = ~ tibble(Quantile = .x,
Value = quantile(x, probs = .x,na.rm=TRUE)))
})
p16 <- b12_Quantile %>% ggplot(aes(x=hour,y=Value,col=as.factor(Quantile))) +geom_line() + scale_x_continuous(breaks=seq(1, 24, 5)) +theme(legend.position = "bottom") + facet_wrap(~work, labeller = "label_both") + ylab("Daily Consumpttion in KwH") + xlab("Hour-of-Day") + coord_cartesian(ylim = c(0,0.75)) + ggtitle("B4 29") + ggtitle("e) Across HoD and WD/NWD - B4 29")
p16
b22_Quantile <- s1 %>% filter(Source=="B3 37") %>% group_by(work,hour) %>%
do({x <- .$Value
map_dfr(.x = seq(0.1,0.9,0.1),
.f = ~ tibble(Quantile = .x,
Value = quantile(x, probs = .x,na.rm=TRUE)))
})
p26 <- b22_Quantile %>% ggplot(aes(x=hour,y=Value,col=as.factor(Quantile))) +geom_line() + scale_x_continuous(breaks=seq(1, 24, 5)) +theme(legend.position = "bottom") + facet_wrap(~work, labeller = "label_both") + ylab("Daily Consumpttion in KwH") + xlab("Hour-of-Day") + coord_cartesian(ylim = c(0,0.75)) + ggtitle("B4 29") + ggtitle("f) Across HoD and WD/NWD - B3 37")
p26
```
From e) Energy consumption is pretty variable on weekends/No work days during late night hours and increases till 3am
On weekdays energy consumption is low till 8am and starts increasing from 9am to 4pm and then again decreases till 10pm and peaks up from 11 to 12pm
Looks like from 4pm the student is not at home for weekdays and weekends.
On weekends, student goes to sleep around 2 or 3 am and wakes up around 10am. (consistent behavior as can be seen even 30th or 40th percentile)
From f) Variation is almost uniform across hours of the day and days of the week.<file_sep>---
title: "NYC Bikedata Analysis"
author: "<NAME>"
date: "19/06/2019"
output: html_document
---
```{r setup, include=FALSE}
library(forecast)
library(ggplot2)
library(dplyr)
library(lubridate)
library(tidyverse)
library(lvplot)
library(ggridges)
library(tsibble)
library(bikedata)
library(gravitas)
```
```{r data_prep, echo=F}
# rawbikedata <- read.csv(file="./bikeshare_nyc_raw.csv", head=TRUE,sep="\t")
#
# # Create a working data frame
# bikedata <- rawbikedata %>% as_tibble()
## Load DOCkS DATA
load("bikedata.Rda")
# Create a variable which measure how 'full' a bikeshare dock is
# 0 = empty, 1.0 = full
bikedata$avail_ratio <- bikedata$avail_bikes / bikedata$tot_docks
#Remove columns of data we don't nee/d
bikedata <- bikedata[c("dock_id","dock_name","date","avail_bikes","avail_docks", "tot_docks", "avail_ratio","X_lat", "X_long")]
bikedata_mut <- bikedata %>% mutate(hour_day = build_gran("hour", "day", date),
month_year = build_gran("month", "year", date),
day_week = build_gran("day", "week", date),
hhour_day = build_gran("hhour", "day", date))
## RIDES DATA
# Top 20 Bike stations by number of starts
rides_busiest_grans <- tsibbledata::nyc_bikes %>% mutate(hour_day = build_gran("hour", "day", start_time),
month_year = build_gran("month", "year", start_time),
day_week = build_gran("day", "week", start_time),
hhour_day = build_gran("hhour", "day", start_time),
day_month = build_gran("day", "month", start_time)
)
```
```{r Rides_Docks_Avail}
top_bikes <- tsibbledata::nyc_bikes %>%as_tibble() %>% group_by(start_station) %>% summarise(count = n()) %>% arrange(-count) %>% mutate(rank = row_number())
rides_dock_avail <- function(i)
{
station = top_bikes$start_station[top_bikes$rank==i] %>% as.character %>% as.numeric()
rides_from <- rides_busiest_grans %>% as_tibble %>% filter(start_station==station) %>% group_by(hour_day) %>%
summarise(Count = n())
rides_to <- rides_busiest_grans %>% as_tibble %>% filter(end_station==station) %>% group_by(hour_day) %>%
summarise(Count = n())
#Draw plot
docks_avail <- bikedata_mut %>% filter(dock_id==station)
theme_set(theme_classic())
# Allow Default X Axis Labels
ggplot(docks_avail, aes(x=as.factor(hour_day), y=avail_ratio*50)) +
geom_boxplot(col="tomato2", size=1) +
geom_line(data = rides_from, aes(x = hour_day, y=Count)) +
geom_line(data = rides_to, aes(x = hour_day, y=Count), colour = "blue") +
labs(title=paste("Boxplot of Dock Availability for station", station),
subtitle = paste("Black: Count from station", station, "Blue: Count to station", station),
caption="Source: Open Bus",
y="Count") +
xlab("hour of the day") +
scale_y_continuous(name = "Count",
sec.axis = sec_axis(~ . /50, name = "avail_ratio")) +
theme(
axis.title.y = element_text(color = "black"),
axis.title.y.right = element_text(color = "black"), legend.text =element_text( "grey(from), black(to)") )
}
```
```{r analysis_1, echo=TRUE}
rides_dock_avail(1) # most busy station in terms of total number of start trips
```
# Grove St PATH
Trips starting from this station rises in the evening, implying people getting back from work are taking bikes from this station to reach home. Similarly, the trips to this station are also higher in the morning hours indicating it is a major office hub/station. On further inspection, we found 3186 to be Grove St PATH, NYC is indeed a busy station in NYC.
For rebalancing of bikes, what is therefore needed is to ensure that the dock spaces are available (low avail_ratio) in the morning so that customers can park their bikes there. In the evening, it is to be ensured that bikes are available (high avail_ratio) at this dock.
Perhaps, it is more appropriate to look at median counts and not total counts per hour. But median counts were pretty flat (mostly 1, maximum 3), so I chose to display total counts to have an overall idea.
```{r analysis_2, echo=TRUE}
rides_dock_avail(2) # 2nd most busy station in terms of total number of start trips
```
# Hamilton Park
Trips starting from this station are higher in number in the morning, which indicates people are starting their rides from this bike station to reach to their work place. This implies, bikes should be available in the morning (avail_ratio) and dock space should be available in the evening (low avail_ratio) so that people can park their bikes here.
# Sip Ave
The time series pattern of "from" and "to" trip is similar to the first case, implying it is a major office hub/ station.
```{r analysis_3, echo=TRUE}
rides_dock_avail(3) # 3rd most busy station in terms of total number of start trips
```
# Exchange Place
```{r analysis_4, echo=TRUE}
rides_dock_avail(4) # 4th most busy station in terms of total number of start trips
```
The time series pattern of "from" and "to" trip is similar to the first and third case, implying it is a major office hub/ station. But for this station avail_ratio is pretty high in the morning - which can create a hurdle for people to park their bikes in the morning. It might also be the case that people parked in the morning and hence the resulting avail_ratio became low. Since we are doing this analysis ex-post, it might be a good idea to plot count for hour (x) and availability at hour (x - 1).
<file_sep>#install.packages("bikedata")
library(bikedata)
library(RSQLite)
library(dplyr)
bike_data <- store_bikedata (city = 'nyc', bikedb = 'bikedb', dates = 201901:201905)
bikedb <- file.path ("bikedata/Data", "bikedb.sqlite")
la_2017 <- dl_bikedata (city = 'divvy', dates = 2015, quiet = TRUE)
store_bikedata (bikedb = 'bikedb',city = 'nyc',dates = 201601:201603, quiet = TRUE)
con <- dbConnect(RSQLite::SQLite(), "bikedata/Data/bikedb.sqlite")
src_dbi(con)
la_2018 <- tbl(con, "datafiles")
la_db <- la_2018 %>% collect()
store_bikedata (city = 'nyc', bikedb = 'bikedb', dates = 201601:201603)
la_dbdata_dir <- tempdir ()
bike_write_test_data (data_dir = data_dir)
# or download some real data!
dl_bikedata (city = 'la', data_dir = bikedb)
bikedb <- file.path (data_dir, 'testdb')
store_bikedata (data_dir = data_dir, bikedb = bikedb)
# create database indexes for quicker access:
index_bikedata_db (bikedb = bikedb)
#
dc_2016 <- dl_bikedata (city = 'dc', dates = '2016.03-2016.05', data_dir = "bikedata/Data")
library(tsibble)
data_nyc <- tsibbledata::nyc_bikes %>% as_tsibble()
<file_sep>---
title: "Fun T20 cricket analysis "
author: "<NAME>"
date: "12/07/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(lvplot)
library(ggridges)
library(viridis)
```
```{r, echo=FALSE}
hierarchy <- tibble(units = c("ball", "over", "quarter", "semester", "match"), convert_fct = c(6, 5, 2, 2, 1))
hierarchy
#
#
# dynamic_build_gran <- function(x, hierarchy_tbl = NULL, lowest_unit = NULL, highest_unit = NULL, ...) {
# # for aperiodic granularities - lgran less than month and ugran more than or equal to month
#
# #
# # if (is.null(lgran) | is.null(ugran)) {
# # stop("function requires both lgran and ugran to be specified")
# # }
#
#
# if (g_order(hierarchy_tbl, lowest_unit, highest_unit) < 0) {
# stop("Order of second unit should be larger than the first one in the hierarchy table. Try swapping lgran and ugran")
# }
#
# lgran_ordr1 <- g_order(hierarchy_tbl, lowest_unit, order = 1)
# if (g_order(hierarchy_tbl, lowest_unit, highest_unit) == 1) {
# one_order <- convert_fct[units %>% match(x = lowest_unit)]
# return(hierarchy_tbl$one_order) # need to change
# } else {
# value <- build_gran(x, hierarchy_tbl, lowest_unit, lgran_ordr1) +
# gran_convert(lowest_unit, lgran_ordr1) *
# (build_gran(x, hierarchy_tbl, lgran_ordr1, highest_unit) - 1)
# return(value)
# }
# }
# balls_match, overs_match for example
#unit_last(hierarchy, "ball", "quarter")
unit_last <- function(hierarchy_tbl = NULL, lower_gran = NULL, upper_gran = NULL, ...){
units <- hierarchy_tbl$units
convert_fct <- hierarchy_tbl$convert_fct
lowest_unit = dplyr::first(hierarchy_tbl$units)
highest_unit = dplyr::last(hierarchy_tbl$units)
index_l = units %>% match(x = lower_gran)
index_h = units %>% match(x = upper_gran)
gran_set <- units[index_l:index_h]
gran <- paste(gran_set, highest_unit, sep="_")
gran
}
# one order function to create single order up granularities
one_order <- function(.data, hierarchy_tbl = NULL, lower_gran = NULL, col_name = NULL, ...)
{
units <- hierarchy_tbl$units
convert_fct <- hierarchy_tbl$convert_fct
lowest_unit = dplyr::first(hierarchy_tbl$units)
highest_unit = dplyr::last(hierarchy_tbl$units)
if(lower_gran == highest_unit)
{
stop("single-order-up granularties can not be obtained for the highest unit in the hierarchy table")
}
upper_gran = g_order(hierarchy_tbl, lower_gran, order = 1)
index_l = units %>% match(x = lower_gran)
index_h = units %>% match(x = upper_gran)
#
# gran_set <- units[index_l:index_h]
#
# if(is.null(col_name))
# {
# stop("Column name must be provided")
# }
col_req <- .data[[col_name]]
# # relating upper_gran and highest_unit
# constant <- gran_convert(hierarchy_tbl, lowest_unit = upper_gran, highest_unit = highest_unit)
#
# upper_highest = ceiling(col_req/constant)
# relating lowest unit and lower_gran
constant_upper <- gran_convert(hierarchy_tbl, lowest_unit, upper_gran)
# relating lowest unit and upper_gran
constant_lower <- gran_convert(hierarchy_tbl, lowest_unit, lower_gran)
rel_upper <- col_req%%constant_upper
rel_upper <- if_else(rel_upper!=0, rel_upper, constant_upper)
value = ceiling((rel_upper)/constant_lower)
value
}
# provides the order difference between two granularities, also provide the upper granularity given the order (given a hierachy table)
g_order <- function(hierarchy_tbl, lower_gran =NULL, upper_gran = NULL, order = NULL,...){
units <- hierarchy_tbl$units
convert_fct <- hierarchy_tbl$convert_fct
# Put the first element of the vector units as the lowest most unit desired - default
# if (is.null(lowest_unit)) {
# lowest_unit = dplyr::first(hierarchy_tbl$units)
# }
index_l <- units %>% match(x = lower_gran)
if (!is.null(upper_gran)) {
index_h <- units %>% match(x = upper_gran)
return(index_h - index_l)
}
if (!is.null(order)) {
return(units[index_l + order])
}
}
# provides the conversion factor between two granularities
gran_convert <- function(hierarchy_tbl = NULL,lower_gran = NULL, upper_gran = NULL, order = NULL) {
units <- hierarchy_tbl$units
convert_fct <- hierarchy_tbl$convert_fct
index_l <- units %>% match(x = lower_gran)
if (!is.null(lower_gran)) {
if (!lower_gran %in% units | !upper_gran %in% units) {
stop(paste0("units ", lower_gran, " and ", upper_gran, " both should be one of ", paste0(units, collapse = ", ")), call. = F)
}
if (g_order(hierarchy_tbl, lower_gran, upper_gran) < 0) {
stop("Order of second unit should be larger than the first one. Try reversing their position")
}
if (g_order(hierarchy_tbl, lower_gran, upper_gran) == 0) {
return(1)
}
else {
return(convert_fct[index_l] * gran_convert(hierarchy_tbl, g_order(hierarchy_tbl, lower_gran, order = 1), upper_gran))
}
}
if (!is.null(order)) {
converter <- convert_fct[index_l]
while (converter <= order) {
index_l <- index_l + 1
}
}
}
```
```{r try_gravitas}
data <- read_csv("deliveries.csv")
data_MI <- data %>%
filter(batting_team =="Mumbai Indians", inning ==1)
match_er <- data_MI %>% filter(wide_runs + noball_runs==0) %>% group_by(match_id,over) %>% summarize(n = n()) %>% filter(n!=6) %>% select(match_id)
data_rev <- data_MI %>% filter(!match_id %in% match_er$match_id, wide_runs + noball_runs==0) %>%
mutate(balls = purrr::rep_along(match_id, 1:6),
balls_game = purrr::rep_along(match_id, 1:120))
data_rev2 <- data_rev %>% mutate(new_col = one_order(data_rev, hierarchy_tbl = hierarchy, lower_gran = "ball", col_name = "balls_game"))
data_rev3 <- data_rev2 %>% mutate(data_index = row_number()) %>% tsibble::as_tsibble(index = data_index)
```
```{r search_fun}
search_gran_v1 <- function(.data, hierarchy_tbl = NULL, lowest_unit = NULL, highest_unit = NULL, filter_in = NULL, filter_out = NULL, ...) {
units <- hierarchy_tbl$units
convert_fct <- hierarchy_tbl$convert_fct
if (!tsibble::is_tsibble(.data)) {
stop("must use tsibble")
}
# Put the last element of the vector units as the upper most unit desired - default
if (is.null(highest_unit)) {
highest_unit = dplyr::last(hierarchy_tbl$units)
}
else if (!(highest_unit %in% units))
{
stop("upper unit must be listed as an element in the hierarchy table")
}
# Put the first element of the vector units as the lowest most unit desired - deafult
if (is.null(lowest_unit)) {
lowest_unit = dplyr::first(hierarchy_tbl$units)
} else if (!(lowest_unit %in% units))
{
stop("lower unit must be listed as an element in the hierarchy table")
}
# # Put the first element of the vector units/interval of the tsibble as the least most unit desired
if (tsibble::is_regular(.data)) {
interval_ts <- tsibble::interval(.data)
data_interval <- interval_ts[interval_ts != 0]
if (is.null(lowest_unit)) {
lgran_iden <- names(data_interval)
lgran_multiple <- data_interval[[1]]
if (lgran_multiple == 1) {
lowest_unit <- lgran_iden
}
else if (lgran_multiple > 1) {
index_lgran <- units %>% match(x = lgran_iden)
if (convert_fct[index_lgran] < lgran_multiple) {
convert_fct[index_lgran] <- convert_fct[index_lgran] * convert_fct[index_lgran + 1]
last_index <- index_lgran + 1
}
lowest_unit <- units[last_index + 1]
}
}
}
else if (!tsibble::is_regular(.data)) {
if (is.null(lowest_unit)) {
stop("lgran must be provided when the tsibble is irregularly spaced")
}
}
# if (g_order(hierarchy_tbl, lowest_unit, highest_unit) == 1) {
# stop("Only one unit ", lowest_unit, "_", {
# highest_unit
# }, " can be formed. Function requires checking compatibility for bivariate granularities")
# }
ind <- .data[[rlang::as_string(tsibble::index(.data))]]
index_l <- units %>% match(x = lowest_unit)
index_h <- units %>% match(x = highest_unit)
gran2_set <- units[index_l:index_h]
gran <- paste(gran1 = combn(gran2_set, 2)[1, ], gran2 = combn(gran2_set, 2)[2, ], sep = "_")
gran_split <- stringr::str_split(gran, "_", 2) %>% unlist() %>% unique()
if (!is.null(filter_in)) {
if (length(filter_in) == 1) {
stop("Atleast two temporal units to be provided for filter_in ")
}
if (!all(filter_in %in% units)) {
stop("temporal units to be filtered in not found: make sure vector contains units which are between lgran and highest_unit")
}
filter_in <- filter_in[match(units, filter_in)]
filter_in <- filter_in[!is.na(filter_in)]
gran_split <- gran_split[match(filter_in, gran_split)]
gran <- paste(gran1 = combn(gran_split, 2)[1, ], gran2 = combn(gran_split, 2)[2, ], sep = "_")
}
else if (!is.null(filter_out)) {
if (!all(filter_out %in% units)) {
stop("temporal units to be filtered out not found: make sure vector contains units which are between lgran and highest_unit")
}
filter_out <- filter_out[match(units, filter_out)]
filter_out <- filter_out[!is.na(filter_out)]
gran_split <- gran_split[-match(filter_out, gran_split)]
gran <- paste(gran1 = combn(gran_split, 2)[1, ], gran2 = combn(gran_split, 2)[2, ], sep = "_")
}
return(gran)
}
```
```{r build_gran}
# because one_order's argument is .data
dynamic_build_gran <- function(.data, hierarchy_tbl = NULL, lower_gran = NULL, upper_gran = NULL, lowest_highest = "balls_game",...) {
units <- hierarchy_tbl$units
convert_fct <- hierarchy_tbl$convert_fct
if (g_order(hierarchy_tbl, lower_gran, upper_gran) < 0) {
stop("Order of second unit should be larger than the first one in the hierarchy table. Try swapping lgran and ugran")
}
if(is.null(lowest_highest))
{
stop("lowest_highest column must be provided")
}
lgran_ordr1 <- g_order(hierarchy_tbl, lower_gran, order = 1)
if (g_order(hierarchy_tbl, lower_gran, upper_gran) == 1) {
one_order <- convert_fct[units %>% match(x = lower_gran)]
value <- one_order(.data, hierarchy_tbl, lower_gran, lowest_highest)
value # need to change
} else
{
col_name = lowest_highest
value <- dynamic_build_gran(.data, hierarchy_tbl, lower_gran, lgran_ordr1) +
gran_convert(hierarchy_tbl, lower_gran, lgran_ordr1) *
(dynamic_build_gran(.data, hierarchy_tbl, lgran_ordr1, upper_gran) - 1)
value
}
}
```
```{r, echo=TRUE}
create_gran <- function(.data, gran1 = NULL, hierarchy_tbl = NULL, label = TRUE, abbr = TRUE, ...) {
if (!tsibble::is_tsibble(.data)) {
stop("must use tsibble")
}
# if (is.null(gran2)) {
# gran2 <- g_order(gran1, order = 1)
# col_name <- paste(rlang::quo_name(gran1), gran2, sep = "_")
# }
# if (!is.null(gran2)) {
# col_name <- paste(rlang::quo_name(gran1), rlang::quo_name(gran2), sep = "_")
# }
x <- .data[[rlang::as_string(tsibble::index(.data))]]
gran1_split <- stringr::str_split(gran1, "_", 2) %>% unlist()
lgran <- gran1_split[1]
ugran <- gran1_split[2]
data_mutate <- .data %>% dplyr::mutate(L1 = dynamic_build_gran(x, hierarchy_tbl, lower_gran = lgran, upper_gran = ugran, ...))
lev <- unique(data_mutate$L1)
if (label) {
if (lgran == "day" & ugran == "week") {
names <- c(
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
)
}
else if (lgran == "month" & ugran == "year") {
names <- c(
"January", "February", "March", "April",
"May", "June", "July", "August", "September", "October", " November", "December"
)
}
else {
names <- as.character(1:length(unique(lev)))
}
names_abbr <- substr(names, 1, 3)
if (abbr) names_gran <- names_abbr else names_gran <- names
}
else {
names_gran <- as.character(1:length(unique(lev)))
}
data_mutate$L1 <- factor(data_mutate$L1, labels = names_gran)
data_mutate %>%
dplyr::select(
!!gran1 := L1
)
}
```
```{r}
data_rev %>%
mutate(ball_over = dynamic_build_gran(data_rev, hierarchy_tbl = hierarchy, lower_gran = "ball", upper_gran = "over"))%>%
mutate(over_quarter = dynamic_build_gran(data_rev, hierarchy_tbl = hierarchy, lower_gran = "over", upper_gran = "quarter"))
```
<file_sep>---
title: "Initiate codebase"
author: "<NAME>"
date: "05/06/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(tsibble)
library(ggplot2)
```
```{r}
data_nyc <- tsibbledata::nyc_bikes
data_nyc %>% summary()
# one year data for 2018
start_station <- data_nyc %>% distinct(start_station)
end_station <- data_nyc %>% distinct(end_station)
unique_start_end <- data_nyc %>% as_tibble() %>% ungroup() %>% group_by(start_station, end_station) %>% tally() %>% arrange(-n) %>% head()
bike_combo_1 <- data_nyc %>% filter(start_station %in% c(3186, 3203) | end_station %in% c(3186, 3203))
```
```{r BUILD, echo=TRUE}
parse_exp <- function(y) {
if (y == "1") {
value <- 1
}
else {
value <- parse(text = paste0(y, "(x)"))
}
return(value)
}
nest <- function(gran1, gran2, x, ...) { # for periodic granularities that are either strictly less than month or strictly more than month
gran1_ordr1 <- g_order(gran1, order = 1)
if (g_order(gran1, gran2) == 1) {
one_order <- lookup_table$convertfun[lookup_table$granularity %>% match(x = gran1)]
return(eval(parse_exp(one_order)))
} else {
value <- nest(gran1, gran1_ordr1, x) +
gran_convert(gran1, gran1_ordr1) *
(nest(gran1_ordr1, gran2, x) - 1)
return(value)
}
}
anest <- function(gran1, gran2, x, ...) { # for aperiodic granularities - gran1 less than month and gran2 more than or equal to month
index_gran2 <- granularity %>% match(x = gran2)
day_gran2 <- eval(parse_exp(lookup_table$convertday[index_gran2]))
c_gran1_day <- gran_convert(gran1, "day")
if(g_order("minute", "day")>=0)
{
value = nest(gran1, "day", x) + c_gran1_day*(day_gran2 - 1)
}
else
{
value = ceiling(day_gran2/c_gran1_day)
}
}
# the lookup table - this needs to be changed if other granularities are included
lookup_table <- tibble::tibble(
granularity = c("second", "minute", "qhour", "hhour", "hour", "day", "week", "fortnight", "month", "quarter", "semester", "year"),
constant = c(60, 15, 2, 2, 24, 7, 2, 2, 3, 2, 2, 1),
convertfun = c("lubridate::second", "minute_qhour", "qhour_hhour", "hhour_hour", "lubridate::hour", "lubridate::wday", "week_fortnight", "fortnight_month", "month_quarter", "quarter_semester", "semester_year", 1),
convertday = c("second_day", "minute_day", "qhour_day", "hhour_day", "lubridate::hour",1, "lubridate::wday", "day_fortnight", "lubridate::mday", "lubridate::qday", "day_semester", "lubridate::yday"),
)
# provides the order difference between two granularities, also provide the upper granularity given the order
g_order <- function(gran1, gran2 = NULL, order = NULL) {
granularity <- lookup_table$granularity
index_gran1 <- granularity %>% match(x = gran1)
if (!is.null(gran2)) {
index_gran2 <- granularity %>% match(x = gran2)
return(index_gran2 - index_gran1)
}
if (!is.null(order)) {
return(granularity[index_gran1 + order])
}
}
# provides the conversion factor between two granularities
gran_convert <- function(a, b) {
granularity <- lookup_table$granularity
conv_fac <- lookup_table %>% .$constant
index_gran1 <- granularity %>% match(x = a)
if (g_order(a, b) == 0) {
return(1)
}
else {
return(conv_fac[index_gran1] * gran_convert(g_order(a, order = 1), b))
}
}
second_minute <- function(x) {
lubridate::second(x)
}
minute_qhour <- function(x) {
lubridate::minute(x) %% 15 + 1
}
qhour_hhour <- function(x) {
dplyr::if_else((lubridate::minute(x) %% 30 + 1) <= 15, 1, 2)
}
hhour_hour <- function(x) {
dplyr::if_else(lubridate::minute(x) <= 30, 1, 2)
}
week_fortnight <- function(x) {
dplyr::if_else((lubridate::yday(x) %/% 14 + 1) <= 14, 1, 2)
}
month_quarter <- function(x) {
value <- lubridate::month(x) %% 3
dplyr::if_else(value == 0, 3, value)
# otherwise remainder will change the label of the largest value to zero
}
quarter_semester <- function(x) {
value <- lubridate::quarter(x) %% 2
dplyr::if_else(value == 0, 2, value)
# otherwise remainder will change the label of the largest value to zero
}
semester_year <- function(x) {
lubridate::semester(x)
}
# convert day functions
qhour_day <- function(x) {
# finds which quarter of the day
ceiling(lubridate::minute(x) / 15) + 4 * (lubridate::hour(x))
}
hhour_day <- function(x) {
(lubridate::hour(x) * 60 + lubridate::minute(x)) / 30
}
minute_day <- function(x) {
lubridate::minute(x) + (lubridate::hour(x) - 1) * 60
}
second_day <- function(x) {
lubridate::second(x) + (lubridate::hour(x) - 1) * 60 * 60
}
day_semester <- function(x) {
# finds day of the semester
which_sem <- lubridate::semester(x)
day_x <- lubridate::yday(x)
year_leap <- lubridate::leap_year(x)
div_indx <- dplyr::if_else(year_leap == "FALSE", 182, 183)
dplyr::if_else(which_sem == 1, day_x, day_x - div_indx + 1)
}
day_fortnight <- function(x)
{
value = lubridate::yday(x) %/% 14
dplyr::if_else(value==0, 14, value)
}
```
```{r}
#usage of functions
data_nyc_gran <- bike_combo_1 %>% mutate(hour_day = nest("hour", "day", start_time),
month_year = nest("month", "year", start_time),
day_week = nest("day", "week", start_time),
hhour_day = nest("hhour", "day", start_time))
```
<!-- # ```{r} -->
<!-- # data_nyc_gran %>% -->
<!-- # as_tibble %>% -->
<!-- # group_by(hour_day, month_year) %>% -->
<!-- # summarise(daily_tot = n()) %>% -->
<!-- # ggplot(aes(x=hour_day, y=daily_tot)) + -->
<!-- # geom_line() + -->
<!-- # facet_wrap(~month_year) -->
<!-- # -->
<!-- # # -->
<!-- # data_nyc_gran %>% -->
<!-- # as_tibble %>% -->
<!-- # group_by(hhour_day, day_week) %>% -->
<!-- # summarise(daily_tot = n()) %>% -->
<!-- # ggplot(aes(x=hhour_day, y=daily_tot)) + -->
<!-- # geom_line() + -->
<!-- # facet_wrap(~day_week) -->
```
# Building plot functions for automatic plot titles
```{r granplot, echo=TRUE}
granplot = function(x, y) {
data_nyc_gran %>% as_tibble %>% group_by(!!sym(x), !!sym(y)) %>%
summarise(ecount = n()) %>%
ggplot(aes(x = !!sym(x), y = ecount)) +
geom_line() +
theme_bw() +
facet_wrap(as.formula(paste("~", y))) +
ylab("Total Count") +
ggtitle(paste0("Plot of ", x, " given ", y))
}
granplot("hhour_day", "day_week")
granplot("hour_day", "month_year")
```
<file_sep>---
title: "NYC Bikedata Analysis - Answering few questions"
author: "<NAME>"
date: "24/06/2019"
output: html_document
---
```{r setup, include=FALSE}
library(forecast)
library(ggplot2)
library(dplyr)
library(lubridate)
library(tidyverse)
library(lvplot)
library(ggridges)
library(tsibble)
library(bikedata)
library(gravitas)
```
# How are the regular patterns of the rides:
- daily
- weekly
- weekends
- public holidays
```{r Q1_1, echo=T}
load('../Data/nyc_bikes.Rda')
# Top 20 busiest bike stations by number of starts
top_stns_from <- nyc_bikes %>% as_tibble() %>% group_by(start_station) %>% summarise(count = n()) %>% arrange(-count)
top_stns_from %>% summarise(count = sum(count)) %>% pull()
top_stns_to <- nyc_bikes %>% as_tibble() %>% group_by(end_station) %>% summarise(count = n()) %>% arrange(-count)
top_stns_to %>% summarise(count = sum(count)) %>% pull()
# total number of rides from and to stations are same, which is expected.
top_stns_from$start_station <- as.character(top_stns_from$start_station)
top_stns_to$end_station <- as.character(top_stns_to$end_station)
top_stns_from %>% anti_join(top_stns_to, by = c("start_station" = "end_station"))
# no stations where rides only starts but never ends
top_stns_to %>% anti_join(top_stns_from, by = c("end_station" = "start_station"))
# 65 stations where rides only ends but never starts. But maximum rides to these stations through out the year 2018 is 46 after which it drops to 13. So we can ignore these stations in our analysis.
```
59 distinct bike stations with 3186 having ~ 40k and 3203 ~ 20k rides starting from these stations.
124 distinct bike stations where rides are ending - implying rides never start from these stations but only end.
Let us investigate 3186 closely and see the patterns.
```{r Stn3186, echo=F}
nyc_bikes_ts <- nyc_bikes %>% as_tsibble(index = start_time, key = start_station, regular = FALSE)
ts_3186 <- nyc_bikes_ts %>% filter(start_station == 3186 | end_station == 3186)
# ~ 90K rows - 40k rides from this station and 50K to this station
# Daily pattern
ts_3186_grans <- ts_3186 %>% create_gran("month", "year") %>% create_gran("day", "week") %>% create_gran("hhour", "day") %>% create_gran("minute", "hour") %>% create_gran("hour", "day") %>% create_gran("day", "year")
stat_box_data <- function(y, upper_limit = max(iris$Sepal.Length) * 1.15) {
return(
data.frame(
y = 0.95 * upper_limit,
label = paste('count =', length(y), '\n')
)
)
}
ts_3186_grans %>% as_tibble %>% group_by(day_year, hour_day) %>% summarise(count = n()) %>% ggplot(aes( x= as.factor(hour_day), y = count)) + geom_boxplot() + stat_summary(
fun.data = stat_box_data,
geom = "text",
hjust = 9,
vjust = 0.5
)
```
Daily pattern: The busiest hours for this station are from 7 to 9 am in the morning and 5 to 7pm in the evening where it experiences maximum number of rides.
Let's break this up into rides from and to this station:
```{r from_to, echo=TRUE}
# Daily pattern
ts_3186_grans %>% filter(start_station == 3186) %>% as_tibble %>% group_by(day_year, hour_day) %>% summarise(count = n()) %>% ggplot(aes( x= as.factor(hour_day), y = count)) + geom_boxplot() + ggtitle("Boxplots of rides from 3186")
ts_3186_grans %>% filter(end_station == 3186) %>% as_tibble %>% group_by(day_year, hour_day) %>% summarise(count = n()) %>% ggplot(aes( x= as.factor(hour_day), y = count)) + geom_boxplot() + ggtitle("Boxplots of rides to 3186 across hours of day")
```
Trips starting from this station rises in the evening, implying people getting back from work are taking bikes from this station to reach home. Similarly, the trips to this station are also higher in the morning hours indicating it is a major office hub/station. On further inspection, it was found that 3186 is Grove St PATH, NYC which is a busy station in NYC.
```{r 3186_weekly}
# Weekly pattern
ts_3186_grans %>% as_tibble %>% group_by(day_year, day_week) %>% summarise(count = n()) %>% ggplot(aes( x= as.factor(day_week), y = count)) + geom_boxplot() + ggtitle("Boxplots of total rides to 3186 across days of week")
```
Let us see if weekly pattern differs for from and two trips.
```{r 3186_from_to}
ts_3186_grans <- ts_3186_grans %>% mutate(from_to_proxy = if_else(start_station==3186, "from", "to"))
ts_3186_grans %>% as_tibble %>% group_by(day_year, day_week, from_to_proxy) %>% summarise(count = n()) %>% ggplot(aes( x= as.factor(from_to_proxy), y = count, fill = from_to_proxy)) + geom_boxplot() + facet_grid(~day_week) + ggtitle("Boxplots of rides across days of week")
```
They are mostly similar with rides to this station always exceeding rides from this station with the maximum difference on Tuesdays. What happens on Tuesdays from rides from this station are so low compared to rides to this station?
```{r supply}
load('../Data/bikedata.Rda')
bikedata_new %>% as_tsibble(index = date_time, key = dock_id)
```
Let us see the pair of harmonies for this data set.
```{r harmonies_set}
mat = ts_3186_grans %>% harmony(ugran = "week", lgran = "hour")
mat
# %>% mutate(rank = row_number())
#
# mat$x = as.character(mat$x)
# mat$y = as.character(mat$y)
# granplot <- function(data, i=1)
# {
# gran1 = mat$x[i]
# gran2 = mat$y[i]
#
# data %>% as_tibble() %>% group_by(data[[gran1]], data[[gran2]]) %>%
# summarise(count = dplyr::n()) %>%
# ggplot(aes(x = gran1, y = count)) +
# geom_boxplot() +
# theme_bw() +
# facet_wrap(~ data[[gran2]]) +
# ylab("Total Count") +
# ggtitle(paste0("Plot of ", gran1, " given ", gran2))
# }
#
# granplot(ts_3186_grans, i= 1)
```
<!-- ```{r 3186_weekly} -->
<!-- # Weekly pattern -->
<!-- ts_3186_grans %>% as_tibble %>% group_by(day_year, day_week) %>% summarise(count = n()) %>% ggplot(aes( x= as.factor(day_week), y = count)) + geom_boxplot() -->
<!-- ``` -->
<!-- ```{r 3186_weekly} -->
<!-- # Weekly pattern -->
<!-- ts_3186_grans %>% as_tibble %>% group_by(day_year, day_week) %>% summarise(count = n()) %>% ggplot(aes( x= as.factor(day_week), y = count)) + geom_boxplot() -->
<!-- ``` -->
<!-- ```{r 3186_monthly} -->
<!-- # Monthly pattern -->
<!-- ts_3186_grans %>% as_tibble %>% group_by(month_year) %>% summarise(count = n()) %>% ggplot(aes( x= month_year, y = count)) + geom_step() + scale_x_continuous(breaks = seq(1, 12 , 1)) -->
<!-- ``` -->
<!-- ```{r, comptbl} -->
<!-- ts_3186_grans %>% comp_tbl(lgran = "week", ugran = "month") -->
<!-- Sys.setenv("R_MAX_VSIZE" = 8e9) -->
<!-- harmonies <- ts_3186_grans %>% comp_tbl(lgran = "minute", ugran = "day") -->
<!-- ``` -->
<!-- # How does weather impact the patterns in each case? -->
<!-- # Identify stations with similar/different/inverse patterns? -->
<!-- # What is the change of number of available bikes every hour? Busy station/ Quiet station? -->
<!-- # Specifically zoom in busy periods -->
<!-- # Excess supply/ demand -->
<file_sep>---
title: "Fun T20 cricket analysis "
author: "<NAME>"
date: "12/07/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(lvplot)
library(ggridges)
library(viridis)
```
Let us imagine a T20 format of cricket to be in a calendar format, where each ball is assumed to represent an unit of time. In such a world, a calendar would look like the following:
hour : ball
day: over
quarter: 5 overs
semester: 10 overs
year: 20 overs
Suppose, we are interested to see how the distribution of scores vary from the start to the end of the game. Let us brainstorm some of the questions that might help us comprehend that.
a) How the score varies across each balls, over, quarter or semester of the game for the number of matches played.
For example, if the team has played 5 T20 matches and we are interested to know how scores varied for each of those 20*5 = 100 overs, then what we are trying to understand here is the distribution of scores across linear categorization, overs in this case.
b) How the scores vary per each over of a quarter, or each quarter of a semester each over of a semester?
We are essentially trying to understand the distribution of scores across periodic categorisations, where each coarser unit consists of equal number of finer units for all levels of the coarser unit. For each match, balls, overs, quarters and semesters can be thought to align linearly where balls vary from 1,2, ..120, overs vary from 1, 2, ...20, quarters range from 1, 2,...,4 and so on. We call these "linear" categorisation if we are just looking at one match.But for 80 matches, these are not "linear" since they keep on repeating themselves within a match. We call these "circular" categorisations. Similarly, we can also be interested to study the distribution of runs across balls per over/quarter/semester, overs per quarter/semester and quarters per semester.
What are the exhaustive list of circular categorisation that we can look at here:
1) balls of an over (ball_over)
2) balls of a quarter (ball_quarter)
3) balls of a semester (ball_semester)
4) balls of a match (ball_match)
5) overs of a quarter (ball_quarter)
6) overs of a semester (over_semester)
7) overs of a match (over_match)
8) quarters of a semester (quarter_semester)
9) quarters of a match (quarter_match)
10) semesters of a match (semester_match)
The hierarchy being as follows -
- ball
- over -> 6 balls
- quarter -> 5 overs
- semester -> 2 quarters
- match -> 2 semesters
```{r hierarchy, echo=TRUE}
hierarchy_model <- tibble(category_ls = c("ball", "over", "quarter", "semester", "match"), conversion_fac = c(6, 5, 2, 2, 1))
hierarchy_model
```
### [Dataset: Indian Premier League (IPL) ball by ball](https://www.kaggle.com/littleraj30/indian-premier-league-2019-ball-by-ball)
We will look at the ball by ball data for Mumbai Indians. Performance will vary depending on if they are batting 1st or 2nd. Hence, it is a good idea to filter the matches in which they have batted first.
```{r read_data, echo=TRUE}
# reading ball by ball data
data <- read_csv("deliveries.csv")
data_MI <- data %>%
filter(batting_team =="Mumbai Indians", inning ==1) %>%
mutate(quarter_match = case_when(
between(over,1,5) ~ 1,
between(over,6,10) ~ 2,
between(over,11,15) ~ 3,
between(over,16,20) ~ 4
)) %>%
mutate(semester_match = case_when(
between(quarter_match,1,2) ~ 1,
between(quarter_match,3,4) ~ 2
)) %>%
mutate(over_quarter =
if_else(over%%5==0,5, over%%5)
) %>% mutate(quarter_semester =
if_else(quarter_match%%2==0,2, quarter_match%%2)
)
```
```{r nmatch, echo=TRUE}
data_MI %>% distinct(match_id) %>% nrow()
```
# Checking data accuracy
```{r data_check, echo=TRUE}
data_MI %>% distinct(over) %>% nrow()
data_MI %>% distinct(ball) %>% range()
data_MI %>% distinct(total_runs) %>% range()
```
Each match consists of 20 overs. Total runs per ball ranges from 0 to 7, which also seems sensible. Balls per over ranges from 1 to 9, which seems reasonable in case of no/wide balls. However, we would eliminate such cases so that each over consists of 6 balls. There are 2 matches for which some overs have less than 6 balls. These 2 matches are removed from the dataset. Also rows for which (wide_runs + noball_runs) not equal to zero are removed from the dataset. This would ensure that each over has 6 balls. However, in the dataset the ball index will still range from 1 to 9. The ball index is renamed from 1 to 6 based on the rank. Thus a over in the dataset which has balls (1, 3, 5, 6, 8, 9) will be renamed as (1, 2, 3, 4, 5, 6) so that ball labels are consistent across overs.
```{r}
match_er <- data_MI %>% filter(wide_runs + noball_runs==0) %>% group_by(match_id,over) %>% summarize(n = n()) %>% filter(n!=6) %>% select(match_id)
nmatch = data_MI$match_id %>% length()
nover = data_MI %>% distinct(over) %>% nrow()
data_MI <- data_MI %>% filter(!match_id %in% match_er$match_id, wide_runs + noball_runs==0) %>%
mutate(balls = purrr::rep_along(match_id, 1:6),
balls_game = purrr::rep_along(match_id, 1:120)) %>%
select(match_id, over, balls, balls_game, quarter_match, semester_match, total_runs, over_quarter, quarter_semester)
#data_MI %>% group_by(match_id, over) %>% summarise(n = n()) %>% distinct()
```
<!-- a) How the score varies across each balls (a simple time plot), over, quarter or semester of the match. What we are trying to understand here is the distribution of scores across linear time units. -->
```{r balls, echo=TRUE}
# data_MI %>% ggplot(aes(x = as.factor(balls_game), y= total_runs)) + geom_boxplot()+ xlab("balls")
# data_MI %>% ggplot(aes(y = as.factor(balls_game), x= total_runs)) + geom_density_ridges2() + ylab("Balls per over")
data_MI_dec <- data_MI %>%
group_by(balls_game) %>%
do({x <- .$total_runs
map_dfr(.x = c(0.25,0.5, 0.75, 0.9),
.f = ~ tibble(Quantile = .x,
Value = quantile(x, probs = .x,na.rm=TRUE)))
})
data_MI_dec %>%
ggplot(aes(x = balls_game,y = Value,col = as.factor(Quantile))) +
geom_step() +
xlab("Balls per match") + scale_x_continuous(breaks = seq(1, 120, 12)) +
ggtitle("Quartile plot of total runs per ball across balls per match")
```
The scores/ball increases from 1st to 120th ball in the 90th percentile. In the last 2 overs, players are more vulnerable to get more scores, which is evident from the fact that in 90 percent of cases, their scores vary between 4 and 6. Till around 50th ball, players play safe and may get no runs per ball in 25% of the times, after which they more likely to get one score per ball.
```{r over, echo=TRUE}
data_MI %>% ggplot(aes(x = as.factor(over), y= total_runs)) + ggtitle("Letter value plot of runs per ball across each over of a match") + geom_lv(aes(fill = ..LV..), outlier.colour = "red", outlier.shape = 1, k = 5) + xlab("overs per match")
# data_MI %>% ggplot(aes(y =as.factor(over), x= total_runs)) + geom_density_ridges2() + ylab("Balls per over")
```
In the first two overs, players play really safe and make no runs 50% of the times. The median is constant at 1 for all overs after the 2nd over. It is interesting to see the distribution of tails in this plot. M, F, E, D and C represents 50%, 25%, 12.5%, 6.25% and 3.13% of the tail area respectively. Till the first four overs, scoring a 4 or a 6 is extreme. The region which covers the tail 3.13% falls between 4 and 6 till up to 13th over. It is interesting to see how the letter values of scores (D, E and F) moves up, as we move towards the end of the game.
```{r quarter, echo=TRUE}
data_MI %>% ggplot(aes(x = as.factor(quarter_match), y= total_runs)) + geom_violin()+ xlab("quarters per match")+ ylab(" Total runs per ball") + ggtitle("Violin plot of runs per ball across each quarter of a match")
# data_MI %>% ggplot(aes(y =as.factor(quarter), x= total_runs)) + geom_density_ridges2() + ylab("quarters per match") + xlab(" Total runs per ball")
```
4th quarter of the match witnesses low density(mass) at scores 0, 1 and more at 4/6. The density at score 6 increases with the quarters of the match.
```{r semester, echo=TRUE}
# data_MI %>% ggplot(aes(x = as.factor(semester_match), y= total_runs)) + geom_violin()+ xlab("semester per match")+ ylab(" Total runs per ball") +ggtitle("Violin plot of runs per ball across each semesters of a match")
data_MI %>% ggplot(aes(x = total_runs, y= as.factor(semester_match))) + geom_density_ridges2()+ ylab("semesters per match")+ xlab(" Total runs per ball")+ ggtitle("Ridge plot of runs per ball across each semesters of a match")
# data_MI %>% ggplot(aes(y =as.factor(semester), x= total_runs, fill=factor(..quantile..))) + stat_density_ridges(
# geom = "density_ridges_gradient", calc_ecdf = TRUE,
# quantiles = 4, quantile_lines = TRUE
# ) + ylab("semester") + xlab(" Total runs per ball") +
# scale_fill_viridis(discrete = TRUE, name = "Quartiles")
```
In the second semester of the game, there is more probability to score more than zero as can be seen from the drop in peaks of the distribution at 0 and increased peak at 1, 2, 4 and 6.
Now, it will be interesting to see the distribution of runs per ball across two categorisation together:
```{r bivariate1, echo=TRUE}
# data_MI %>% ggplot(aes(x = as.factor(semester_match), y= total_runs)) + geom_violin()+ xlab("semester per match")+ ylab(" Total runs per ball") +ggtitle("Violin plot of runs per ball across each semesters of a match")
data_MI %>% ggplot(aes(x = as.factor(over_quarter), y = total_runs))+ geom_violin()+
facet_wrap(~quarter_semester) + xlab("overs per quarter")+ ylab(" Total runs per ball") + ggtitle("Boxplot of runs per ball across each over_quarter and quarter_semester")
```
# runs per over - as variation would be more
```{r checking}
data_MI_over <- data_MI %>% group_by(match_id, over) %>% summarise(runs_over = sum(total_runs)) %>%
mutate(quarter_match = case_when(
between(over,1,5) ~ 1,
between(over,6,10) ~ 2,
between(over,11,15) ~ 3,
between(over,16,20) ~ 4
)) %>%
mutate(semester_match = case_when(
between(quarter_match,1,2) ~ 1,
between(quarter_match,3,4) ~ 2
)) %>%
mutate(over_quarter =
if_else(over%%5==0,5, over%%5)
) %>% mutate(quarter_semester =
if_else(quarter_match%%2==0,2, quarter_match%%2)
) %>%
rename(over_match = over)
```
```{r over_match, echo=TRUE}
data_MI_over %>% ggplot(aes(x = as.factor(over_match), y= runs_over)) + ggtitle("Letter value plot of runs per over across each over of a match") + geom_lv(aes(fill = ..LV..), outlier.colour = "red", outlier.shape = 1, k = 5) + xlab("overs per match")
# data_MI %>% ggplot(aes(y =as.factor(over), x= total_runs)) + geom_density_ridges2() + ylab("Balls per over")
```
```{r over_quarter, echo=TRUE}
data_MI_over %>% ggplot(aes(x = as.factor(over_quarter), y= runs_over)) + geom_violin()+ xlab("quarters per match")+ ylab(" Total runs per ball") + ggtitle("Violin plot of runs per over across each quarter of a match")
data_MI_over %>% ggplot(aes(x = as.factor(over_quarter), y= runs_over)) + geom_violin()+ xlab("quarters per match")+ ylab(" Total runs per ball") + ggtitle("Violin plot of runs per over across each quarter of a match") + facet_grid(~quarter_match)
# data_MI %>% ggplot(aes(y =as.factor(quarter), x= total_runs)) + geom_density_ridges2() + ylab("quarters per match") + xlab(" Total runs per ball")
```
```{r quarter_match, echo=TRUE}
# data_MI %>% ggplot(aes(x = as.factor(semester_match), y= total_runs)) + geom_violin()+ xlab("semester per match")+ ylab(" Total runs per ball") +ggtitle("Violin plot of runs per ball across each semesters of a match")
data_MI_over %>% ggplot(aes(x = runs_over, y= as.factor(quarter_match))) + geom_density_ridges2()+ ylab("semesters per match")+ xlab(" Total runs per ball")+ ggtitle("Ridge plot of runs per overs across each semesters of a match")
data_MI_over %>% ggplot(aes(x = runs_over, y= as.factor(over_quarter))) + geom_density_ridges2()+ ylab("semesters per match")+ xlab(" Total runs per ball")+ ggtitle("Ridge plot of runs per overs across each semesters of a match") + facet_wrap(~quarter_match)
# data_MI %>% ggplot(aes(y =as.factor(semester), x= total_runs, fill=factor(..quantile..))) + stat_density_ridges(
# geom = "density_ridges_gradient", calc_ecdf = TRUE,
# quantiles = 4, quantile_lines = TRUE
# ) + ylab("semester") + xlab(" Total runs per ball") +
# scale_fill_viridis(discrete = TRUE, name = "Quartiles")
```
<file_sep>---
title: "Addressing Comments"
author: "<NAME>"
date: "30/05/2019"
output: html_document
---
```{r setup, include=FALSE}
library(forecast)
library(ggplot2)
library(dplyr)
library(lubridate)
library(tidyverse)
library(lvplot)
library(ggridges)
library(tsibble)
library(sugrrants)
```
1) Will you be including a check on Clashes and warning users if they choose an inappropriate coupling?
Yes. It can be provided either as a warning or in a summary format. However, the data structure will be provided even for clashes. To me, this will enable the user to visualize the plot and see where the problem lies.
2) The captions to the first two sets of graphics ignore (f) and do not say anything about what can be seen. Why do Tasmania and Victoria have different patterns?
Plot a) suggests that aggregate demand in Victoria is most variable for summer months from mid-November to mid March. Summer in Victoria is considered to include the months December to February. So the increased variation in the energy usage can be attributed to the increased use of air conditioners or coolers in those months.
```{r VIC, echo=FALSE}
VIC <- read.csv("VIC2015/Data/demand_VIC.csv")
VIC$Date <- as.Date(VIC$Date,origin = "1899-12-30")
first_day_of_month_wday <- function(dx) {
day(dx) <- 1
wday(dx)
}
VIC <- VIC %>%mutate(Indx_Year = year(Date),
Indx_Month = month(Date, label = FALSE, abbr = TRUE),
Indx_Wk_Yr = week(Date),
Indx_Wk_Month = ceiling((day(Date) + first_day_of_month_wday(Date) - 1) / 7),
Indx_Day_Week = wday(Date, label=FALSE, abbr=TRUE,
week_start=1),
Indx_Day_Month = day(Date),
Indx_Day_Year = yday(Date),
Indx_Weekend=if_else(Indx_Day_Week %in% c(6,7),1,0),
Indx_HlHr_day = Period,
month = month(Date, label = FALSE, abbr = TRUE),
year = year(Date),
yday =yday(Date),
wday = wday(Date, label=FALSE, abbr=TRUE,
week_start=1),
bow = (wday - 1) * 48 + Period,
dom = day(Date),
bom = (dom - 1) * 48 + Period,
Weekend=if_else(wday %in% c(6,7),1,0),
Indx_hour = ceiling(Period/2),
Indx_Hour_Yr = Indx_hour + 24*(yday-1),
Indx_Hour_Month = Indx_hour + 24*(Indx_Day_Month-1),
Indx_Hour_Wk = Indx_hour + 24*(wday-1))
VIC <- as_tibble(VIC)
VIC%>% filter(year %in% c(2002:2014))%>% ggplot(aes(Indx_Day_Month,OperationalLessIndustrial,group = Indx_Day_Month)) + geom_lv(aes(fill=..LV..),outlier.colour = "red",outlier.shape = 1) + scale_fill_brewer()+ facet_wrap(~Indx_Month) + ylab("Electricity Demand [KWh]") + xlab("Days of the Month") + scale_x_continuous(breaks=seq(0,31,5)) + ggtitle("(a) Letter value plot by DoM and MoY for Victoria")
```
```{r TAS, echo=FALSE}
TAS <- read.csv("TAS2015/Data/demand_TAS.csv")
TAS$Date <- as.Date(TAS$Date,origin = "1899-12-30")
first_day_of_month_wday <- function(dx) {
day(dx) <- 1
wday(dx)
}
TAS <- TAS %>%mutate(Indx_Year = year(Date),
Indx_Month = month(Date, label = FALSE, abbr = TRUE),
Indx_Wk_Yr = week(Date),
Indx_Wk_Month = ceiling((day(Date) + first_day_of_month_wday(Date) - 1) / 7),
Indx_Day_Week = wday(Date, label=FALSE, abbr=TRUE,
week_start=1),
Indx_Day_Month = day(Date),
Indx_Day_Year = yday(Date),
Indx_Weekend=if_else(Indx_Day_Week %in% c(6,7),1,0),
Indx_HlHr_day = Period,
month = month(Date, label = FALSE, abbr = TRUE),
year = year(Date),
yday =yday(Date),
wday = wday(Date, label=FALSE, abbr=TRUE,
week_start=1),
bow = (wday - 1) * 48 + Period,
dom = day(Date),
bom = (dom - 1) * 48 + Period,
Weekend=if_else(wday %in% c(6,7),1,0),
Indx_hour = ceiling(Period/2),
Indx_Hour_Yr = Indx_hour + 24*(yday-1),
Indx_Hour_Month = Indx_hour + 24*(Indx_Day_Month-1),
Indx_Hour_Wk = Indx_hour + 24*(wday-1))
TAS <- as_tibble(TAS)
TAS%>% filter(year %in% c(2002:2014))%>% ggplot(aes(Indx_Day_Month,OperationalLessIndustrial,group = Indx_Day_Month)) + geom_lv(aes(fill=..LV..),outlier.colour = "red",outlier.shape = 1) + scale_fill_brewer()+ facet_wrap(~Indx_Month) + ylab("Electricity Demand [KWh]") + xlab("Days of the Month") + scale_x_continuous(breaks=seq(0,31,5)) + ggtitle("(b) Letter value plot by DoM and MoY for Tasmania")
```
Plot b) suggests that aggregate demand in Tasmania is more variable for winter months compared to summer months. This is the opposite to how Victoria behaves. This can be explained with the range of summer temperature in these regions. Summer temperatures in [Melbourne, Victoria](https://www.australia.com/en/facts-and-planning/weather-in-australia/weather-in-melbourne.html) ranges from 14 - 25.3°C(occasionally soar past 30°C), whereas for [Hobart, Tasmania](https://www.australia.com/en/facts-and-planning/weather-in-australia/weather-in-hobart.html) goes to 21°C at max. So while Victoria needs a lot of heating, Tasmania stays pleasant in summer days leading to almost null usage of air conditioning.
```{r temp, echo=FALSE}
VIC_temp <- read.csv("VIC2015/Data/temp_86071.csv")
VIC_temp$Date <- as.Date(VIC_temp$Date,origin = "1899-12-30")
# Summer months (December - February)
VIC_temperature <- VIC_temp %>%
mutate(Date = case_when(
month(Date) %in% c(12, 1, 2) ~ 'Summer',
month(Date) %in% c(3, 4, 5) ~ 'Autumn',
month(Date) %in% c(6, 7, 8) ~ 'Winter',
month(Date) %in% c(9, 10,11) ~ 'Spring',
TRUE ~ as.character(Date)))
temp_sum_VIC <- VIC_temperature %>% group_by(Date) %>%
do({x <- .$Temp
map_dfr(.x = c(seq(0.5,0.9,0.1), 0.95, 0.99),
.f = ~ tibble(Quantile = .x,
Value = quantile(x, probs = .x,na.rm=TRUE)))
}) %>% filter(Date %in% c("Summer", "Winter"))
###
###
###
TAS_temp <- read.csv("TAS2015/Data/temp_94029.csv")
TAS_temp$Date <- as.Date(VIC_temp$Date,origin = "1899-12-30")
# Summer months (December - February)
TAS_temperature <- TAS_temp %>%
mutate(Date = case_when(
month(Date) %in% c(12, 1, 2) ~ 'Summer',
month(Date) %in% c(3, 4, 5) ~ 'Autumn',
month(Date) %in% c(6, 7, 8) ~ 'Winter',
month(Date) %in% c(9, 10,11) ~ 'Spring',
TRUE ~ as.character(Date)))
temp_sum_TAS <- TAS_temperature %>% group_by(Date) %>%
do({x <- .$Temp
map_dfr(.x = c(seq(0.5,0.9,0.1), 0.95, 0.99),
.f = ~ tibble(Quantile = .x,
Value = quantile(x, probs = .x,na.rm=TRUE)))
}) %>% filter(Date %in% c("Summer", "Winter"))
```
Temperature of Victoria
```{r temp"_VC, echo=FALSE}
temp_sum_VIC
```
Temperature of Tasmania
```{r, echo=FALSE}
temp_sum_TAS
```
3) The title of the first Buildings plot should be DoW not DoY. Will you automate the correct choice of heading?
Good idea. I can work on it.
4) Your comments on the Buildings plots seem to me to be too strong. Sunday is the day of highest consumption (why?), but Saturday is not so high. Is it correct that you are only looking at 7 weeks of data?Boxplots are poor then and you cannot draw conclusions from such small datasets.
The idea is to hence throw warnings or summarise when can boxplots(or summary plots based on probability) can/cannot be used. Or, which summary plots one should choose for few observations?
5) Why did you drop Monday data in (c) and (d)? The boxplots are again an odd choice. Why not use time series plots? Your conclusions here are again open to debate.
6) Presumably the quantiles in (e) and (f) are based on 35 and 14 days respectively, not a lot of data to estimate quantiles. There is an interesting question here of whether quantile plots look so nice because they are too good to be true. I would at least like to see the individual time series plots before drawing conclusions like yours.
Calendar plot of B4 29
```{r calendar, echo = FALSE}
DHR <-read_rds("DHResidence.rds")
selected_units <- DHR %>% filter(Source %in% c("B3 37","B2 15","B3 37", "B4 29", "BG 50"))
selected_units$`Timestamp UTC` <-lubridate::ymd_hms(selected_units$`Timestamp UTC`)
# selected_units_tsibble <- as_tsibble(selected_units,key=id(Source),index=`Timestamp UTC`,tz="UTC")
vic_holidays <- holiday_aus(2018, state = "VIC")
SU_uniform_mutate <-selected_units %>% mutate(date = date(`Timestamp UTC`),wday = wday(date, label = TRUE, abbr = TRUE,
week_start = 1),
month = month(date, label = TRUE, abbr = TRUE),
year = year(date),
hour = hour(`Timestamp UTC`),
work = ifelse(wday %in% c("Mon", "Tue", "Wed", "Thu", "Fri"), "Yes", "No"))
p1 <- SU_uniform_mutate %>% filter(Source=="B4 29") %>%
frame_calendar(x = hour, y = Value, date = date, ncol = 5) %>%
ggplot(aes(x = .hour, y = .Value, group = date, colour=factor(work))) +
geom_line() +
scale_colour_brewer("work", palette = "Dark2") +
theme(legend.position="none")
prettify(p1)
```
Calendar plot of B3 37
```{r b337_calendar, echo=FALSE}
p2 <- SU_uniform_mutate %>% filter(Source=="B3 37") %>%
frame_calendar(x = hour, y = Value, date = date, ncol = 5) %>%
ggplot(aes(x = .hour, y = .Value, group = date, colour=factor(work))) +
geom_line() +
scale_colour_brewer("work", palette = "Dark2") +
theme(legend.position="none")
prettify(p2)
```
7) Have you considered using FDA?
Functional Data Analysis? I have not considered yet.
<file_sep># Install lubridate, data.table, and ggplot packages (this is only required once)
install.packages('lubridate', dependencies = TRUE)
y
install.packages('data.table', dependencies = TRUE)
install.packages('ggplot2', dependencies = TRUE)
# Load data.table
library(data.table)
# Load lubridate
library(lubridate)
# Load ggplot and scales
library(ggplot2)
library(scales)
# Load mapping libraries
library(leaflet)
library(maps)
library(sp)
library(rgdal)
library(rgeos)
# Read in Citibike bikeshare csv data file
rawbikedata <- read.csv(file="./bikeshare_nyc_raw.csv", head=TRUE,sep="\t")
# Create a working data frame
bikedata <- rawbikedata
# Remove any rows which the total docks is zero
bikedata <- bikedata[bikedata$tot_docks != 0 ,]
View(bikedata)
# Select data for the week of October 9th (10/16 - 10/22)
bikedata <- with(bikedata, bikedata[mday(date) <= 22 & mday(date) >= 9, ])
# Create a POSIXct date and time variable using available data
bikedata$date <- as.character.Date(bikedata$date)
bikedata$hour <- bikedata$hour + (bikedata$pm * 12) * (bikedata$hour != 12)
bikedata$hour <- sprintf("%02d",bikedata$hour)
bikedata$minute <- sprintf("%02d",bikedata$minute)
bikedata$hour <- paste(bikedata$hour, bikedata$minute, sep=":" )
bikedata$date <- paste(bikedata$date, bikedata$hour, sep="")
bikedata$date <- as.POSIXct(bikedata$date ,format= "%y-%m-%d %H:%M")
# Create a variable which measure how 'full' a bikeshare dock is
# 0 = empty, 1.0 = full
bikedata$avail_ratio <- bikedata$avail_bikes / bikedata$tot_docks
#Remove columns of data we don't need
bikedata <- bikedata[c("dock_id","dock_name","date","avail_bikes","avail_docks", "tot_docks", "avail_ratio","X_lat", "X_long")]
bikedata %>% as_tsibble(index = date) %>% mutate(hour_day = build_gran("hour", "day", time))
View(bikedata)
#Draw plot
Dwight_VanDyke <- with(bikedata, bikedata[dock_name == 3203 , ] )
theme_set(theme_classic())
# Allow Default X Axis Labels
ggplot(Dwight_VanDyke, aes(x=date, y=avail_ratio)) +
geom_point(col="tomato2", size=1) +
labs(title="Dwight St & Van Dyke St Citi Bike Station Available Bicycles and Docks",
subtitle="October 9-22, 2017 after 6 PM ET",
caption="Source: Open Bus",
y="Availability Ratio")
last_plot() + scale_x_datetime(breaks = date_breaks("1 day"))
<file_sep>---
title: "Matrix Demonstration"
author: "<NAME>"
date: "14/06/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(tsibbledata)
library(tidyr)
```
Suppose we have a granularity C1 which has levels {A, B, C, D}, and another granularity C2 with levels {X, Y, Z}. When we plot some observations with C1 and C2 used as aesthetics or facets, problems arise when we have empty combinations.
For example, C1 is Day-of-Month and C2 is Week-of-Month.
Here C1 can take 31 values while C2 can take 5 values. There will be 31 × 5 = 155 combinations of C1 and C2. Many of these are empty. For example (2,5), (21,1), etc, that is, second day of the month can never correspond to 5th week of the month and 21st day of the month can never correspond to 1st week of the month. Most of these 155 combinations will be empty set, making the combination of C1 and C2 in a graph unhelpful.
Some examples follow which will demonstrate the idea more. comp_tbl function in the package "gravitas" now allows to see the matrix given any lower and upper granularities. Please run the Rmd to view the entire matrix or try-out other values of lgran(required lower granularity) and ugran(required upper granularity). It is to be noted that the matrix is symmetric, that is, if (A, B) = FALSE then (B, A) is false too. It might appear to be NA in the matrix as both (A, B) and (B, A) combinations are populated while creating the matrix.
```{r matrix_demo, echo=TRUE}
#devtools::install_github("Sayani07/gravitas")
library(gravitas)
# Case 1
aus_elec %>% comp_tbl(lgran = "hour", ugran = "week")
# Case 2
aus_elec %>% comp_tbl(lgran = "hour", ugran = "fortnight")%>% print(n = nrow(.))
# Case 3
aus_elec %>% comp_tbl(lgran = "day", ugran = "month") %>% print(n = nrow(.))
# Case 4
aus_elec %>% comp_tbl(lgran = "month", ugran = "year") %>% print(n = nrow(.))
```<file_sep>---
title: "resi-smart-meter"
author: "<NAME>"
date: "01/08/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(lvplot)
library(ggridges)
library(viridis)
library(readr)
```
# Data description
This is half hourly interval meter readings (kWh) of electricity consumption and generation for few households in the Smart Grid Smart City customer trial(2010-2014).. The data was collected for each household over the duration of their participation in the trial. Data can be accessed at [https://data.gov.au](https://data.gov.au).
ˆˆî
```{r read_data}
Sys.setenv(R_MAX_VSIZE = 32e9)
data <- read_csv("Data/CD_INTERVAL_READING_ALL_NO_QUOTES-2.csv")
```
<file_sep>---
title: "How granplot works"
output: html_document
---
```{r setup, include=FALSE, echo=TRUE}
knitr::opts_chunk$set(echo = FALSE, message=FALSE, cache=TRUE)
# Load any R packages you need here
library(ggplot2)
library(dplyr)
library(lubridate)
library(ggplot2)
library(lvplot)
library(ggridges)
library(tsibbledata)
library(purrr)
library(tsibble)
library(gravitas)
```
<!--temporal granularities and why should we care -->
`granplot`
Usage: recommends statistical distribution plots of bivariate time granularities that aids systematic exploration
granplot(.data, gran1 = NULL, gran2 = NULL, response = NULL, plot_type = NULL, facet_h = 31, ...)
- gran1: the first granularity acting as the facet variable
- gran2: the granularity which is to be plotted across x-axis
- response: the univariate time series to be plotted
- plot_type: the type of distribution plot preferred
- facet_h: the highest number of levels for facet variables above which facetting is not recommended
granplot is useful for exploring statistical distributions for bivariate granularities. It provides the plot recommendations given two granularities. Recommendations for plotting will vary depending on which granularity is placed on the x-axis and which one across facets.
granplot uses `gran_advice` to obtain the recommendations of distribution plots depending on the levels(very high/high/medium/low) of the two granularities plotted. Assumptions are made to ensure display is not too cluttered by the space occupied by various kinds of distribution plots.
- very high (facet) and any levels of x-axis
plots_list <- c("decile", "percentile")
- high (facet) and very high(x-axis)
plots_list <- c("decile", "percentile")
- high (facet) and high(x-axis)
plots_list <- c("decile", "percentile")
- high(facet) and medium(x-axis)
plots_list <- c("decile", "percentile")
- high(facet), low(x-axis)
plots_list <- c("ridge", "violin", "lv", "density")
- medium(facet), very high (x-axis)
plots_list <- c("decile", "percentile")
- medium(facet), high (x-axis)
plots_list <- c("decile", "percentile")
}
- medium(facet), medium (x-axis)
plots_list <- c("decile", "percentile")
- medium(facet), low (x-axis)
plots_list <- c("ridge", "violin", "lv", "density")
- low(facet), very high (x-axis)
plots_list <- c("boxplot", "lv", "percentile", "decile")
- low(facet), medium (x-axis)
plots_list <- c("ridge", "violin", "lv", "density", "percentile", "decile")
- low(facet), low (x-axis)
plots_list <- c("ridge", "violin", "lv", "boxplot", density", "percentile", "decile")
# Default values
Default levels are chosen as very high/high/medium/low based on levels of common temporal granularities like day of the month, day of a fortnight or day of a week. Users are free to change these values.
levels_high = 31
levels_medium = 14
levels_low = 7
very high = levels <= levels_high
high = levels_medium < levels < levels_high
medium = levels_low < levels <= levels_medium
low = levels < levels_low
Minimum number of observations for combinations of time granularities
Assumptions are made to ensure decile/percentile/density based plots are avoided for too few observations
It uses gran_advise to choose the recommended plots if plot_type = NULL.
Now the user might want to plot two temporal granularities that are clashes, they are free to do so however, they will be shown a warning that they are plotting clashes. Warnings will also be shown if number of levels of facet variable too high (inappropriate for facetting), if number of observations are homogenous inter and intra facets.
However, warnings are generated in the following order:
- If two granularities fed are clashes, then no other warnings will be generated other than that they are clashes.
- If two granularities fed are harmonies, but levels of facets too high for facetting, warnings will be generated.
- If two granularities fed are harmonies and levels of facets not beyond the default or user assigned highest value of facets allowed, then warnings will be generated in case number of observations for any combination(s) too few to draw a distribution plot or if there is any inter or intra facet heterogeneity.
```{r}
data1 = tsibbledata::nyc_bikes %>% as_tsibble()
data2 = tsibbledata::vic_elec %>% as_tsibble()
gravitas::granplot(data2, gran1="hour_day", gran2 = "month_year", response = "Demand")
```
User is free to choose any one of the seven distribution plots ("ridge", "violin", "lv", "boxplot", density", "percentile", "decile") in plot_type.If plot_type is not specified, the first one from the recommended list is picked up. To see the list of recommended distribution plots, use the function `gran_advice`.
```{r, echo=TRUE}
gravitas:::gran_advice(data2, gran1="hour_day", gran2 = "month_year")
```
<file_sep>
library(data.table)
library(lubridate)
library(ggplot2)
library(scales)
# Load mapping libraries
library(leaflet)
library(maps)
library(sp)
library(rgdal)
library(rgeos)
# Read in Citibike bikeshare csv data file
# https://www.theopenbus.com/
# Go to Bike share data
# download folders for all months in Data/Docks Data 2018/ folder
# extract files using the code below - change year
file.paths <- glue::glue("Data/docks_data/2018-{formatC(1:12, width = 2, flag = '0')}/bikeshare_nyc_raw.csv")
tmp <- tempfile(fileext = ".csv")
data <- map_dfr(file.paths, function(fp){
read.csv(fp, header =TRUE,sep="\t")
})
bikedata_raw <- data %>% as_tibble()
# Remove any rows which the total docks is zero
# # Remove any rows which the in_service = 0
bikedata <- bikedata_raw %>% filter(tot_docks != 0, in_service != 0)
bikecheck <- bikedata %>% mutate(free_docks = tot_docks - avail_bikes - avail_docks)
quantile(bikecheck$free_docks, seq(0.1,0.9,0.1))
quantile(bikecheck$free_docks, seq(0.01,0.99,0.01))
quantile(bikecheck$free_docks, seq(0.99,0.999,0.001))
bikedata <- bikecheck %>% filter(free_docks<=5)
# Create a POSIXct date and time variable using available data
bikedata$date <- as.character.Date(bikedata$date)
# clean hour data using pm data
bikedata <- bikedata %>% mutate(PM=ifelse((hour>11 & minute>0), 1-pm, pm))
# bikedata$hour <- bikedata$hour + (bikedata$pm * 12) * (bikedata$hour != 12)
bikedata$hour <- bikedata$hour + (bikedata$PM * 12)
bikedata_new <- bikedata %>% mutate(date_time = make_datetime(year = year(date), month = month(date), day = day(date), hour = hour, min = minute))
save(bikedata_new, file = "Data/bikedata.Rda")
# entire 2018 data#
##### EXTRACT bikeshare data
##### using code below
##### change year to 2019
library(tidyverse)
library(tsibble)
set.seed(2018)
tmp <- tempfile(fileext = ".csv.zip")
url1 <- glue::glue("https://s3.amazonaws.com/tripdata/JC-2018{formatC(1:12, width = 2, flag = '0')}-citibike-tripdata.csv.zip")
nyc_bikes <- map_dfr(url1, function(url){
download.file(url, tmp)
read_csv(tmp, locale = locale(tz = "America/New_York"))
})
nyc_bikes <- nyc_bikes %>%
transmute(
bike_id = factor(bikeid),
start_time = starttime,
stop_time = stoptime,
start_station = factor(`start station id`),
start_lat = `start station latitude`,
start_long = `start station longitude`,
end_station = factor(`end station id`),
end_lat = `end station latitude`,
end_long = `end station longitude`,
type = factor(usertype),
birth_year = `birth year`,
gender = factor(gender, 0:2, c("Unknown", "Male", "Female")))
save(nyc_bikes, file = "Data/nyc_bikes.Rda")
<file_sep># Proposal for gravitas: exploring probability distributions for bivariate temporal granularities
**Student information**
-----------------------
Name: <NAME>
University: Monash University, Australia
Email: <EMAIL>
Student Email : <EMAIL>
Github: https://github.com/Sayani07
Twitter: https://twitter.com/SayaniGupta07
Timezone: AEST (UTC + 11:00)
Abstract
--------
Project gravitas aims to provide methods to operate on time in an automated way, to deconstruct it in many different ways. Deconstructions of time that respect the linear progression of time like days, weeks and months are defined as linear time granularities and those that accommodate for periodicities in time like hour of the day or day of the month are defined as circular granularities or calendar categorizations. Often visualizing data across these circular granularities are a way to go when we want to explore periodicities, pattern or anomalies in the data. Also, because of the large volume of data in recent days, using probability distributions for display is a potentially useful approach.The project will provide these techniques into the tidy workflow, so that probability distributions can be examined in the range of graphics available in the ggplot2 package.
Motivation
----------
Considerable data is accumulated by sensors today. An example is data measuring energy usage on a fine scale using smart meters. Smart meters are installed on many households in many countries now. Providing tools to explore this type of data is an important activity. Probability distributions are induced by various aggregations of the data, by temporal components, by spatial region or by type of household. Visualizing the probability distribution of different households across different circular granularities will help energy retailers find similar households or understand consumer behavior better and consequently increase efficiency in planning ahead.
Project gravitas
----------------
Project gravitas will consist of four parts:
1. **R Package**: Develop an R package consisting of modules **BUILD** and **COMPATIBLE**
2. **Shiny UI**: Develop an user interface using RShiny to enable user to walk through different modules of the package
3. **Application**: Provide examples of probability visualization of smart meter data collected on Australian households
4. **Vignette**: Document the R package functionality in a vignette
#### Module BUILD
The module **BUILD** will provide the methods to exhaustively construct any granularities. Some of the functions that will be created as part of this module are as follows:
| Function name | Description | Arg 1 | Arg 2 |
|--------------------------- |------------------------------------------------------------------------------------- |:----------------: |-----------: |
| ghour (.data, .grantype) | define granularities in combination with hour, e.g. hour of the week | a tsibble object | week |
| gqhour (.data, .grantype) | define granularities in combination with quarter hour, e.g. quarter hour of the day | a tsibble object | day |
| gweek (.data, .grantype) | define granularities in combination with week, e.g. week of the month | a tsibble object | month |
The data fed is a tsibble so that time indices are preserved as an essential data component. The function will create granularities in combination with any time index that are one or multiple levels higher in resolution than the time index in the given tsibble.
The idea in this module is to have exhaustive set of granularities at our disposal so that we can use them in later module to figure out periodicities, patterns or anomalies in the data.
#### Module COMPATIBLE
The module **COMPATIBLE** will provide checks on the feasibility of plotting or drawing inference from two granularities together. The function will categorize pairs of granularities as either a harmony or clash, where harmonies are pairs of circular granularities that aid exploratory data analysis. Clashes are pairs that are incompatible with each other for exploratory analysis. This module will provide appropriate data structures to visualize with the grammar of graphics for harmonies.
**Function name**: compatible
**Description**: provide checks on the feasibility of plotting or drawing inference from bivariate temporal granularities
**Usage**: compatible(.data, build1, build2)
**Arguments**:
.data - A tsibble
build1, build2 - granularities computed in module BUILD through functions like gqhour, ghhour, ghour, gweek, gmonth, gquarter, gsemester, gyear. gqhour and ghour imply granularities that are obtained in combination with quarter of an hour and hour respectively. Can be numeric vector or functions.
**Value**: a data structure specifying number of observations per combination of the two builds, variation in the number of observations across combinations and declare them as "harmony" or "clash". These suggestions will serve as a guide to users who are looking to explore distributions of variables across different harmonies.
Related work
---------
- *_lubridate_* is an R package that makes it easier to work with time and also has functions for creating calendar categorizations like hour of the day, day of the week, minutes of the hour. But it mostly creates calendar categorizations that are one step up. The proposed R package will allow creating calendar categorizations that are more than one step ahead, for example, hour of the week or one step up that are not present in lubridate package like week of the month.
- Calendar based graphics in the package *_sugrrants_* help explore data across linear time granularities in a calendar format, whereas this package would help explore circular time granularities.
- *_ggplot2_* facilitates the process of mapping different variables to a 2D frame through grammar of graphics. But it does not tell us which all variables to plot together to promote exploration of data. The proposed package would provide the list of harmonies given a time variable.
- This will use as inputs *_tsibble_* objects which complement the tibble and extend the tidyverse concept to temporal data.
Brief Timeline
--------------
- Phase 0 | Pre-GSoC Period | 11 Apr - 6 May: Literature reading, compiling application and test data
- Phase 1 | Community Bonding Period | 7 May: 26 May: Development related setup and brainstorming ideas
- Phase 2 | Coding Period 1 | 27 May - 23 June: Complete R package with CRAN tests
- Phase 3 | Phase 1 Evaluations | 24 June - 28 June: Communicate with social media community for inputs and code review
- Phase 4 | Coding Period 2 | 29 June -22 July: Incorporate suggestions from community and build Shiny UI for the package
- Phase 5 | Phase 2 Evaluations | 23 July - 26 July: Communicate with social media community for inputs and features review and create user documentation of shiny UI
- Phase 6 | Coding Period 3 | 27 July - 18 August: R package vignette, application on Australian smart meter data and improving features based on suggestions from community
- Phase 7 | Final week of submitting finished product | 19 August - 26 August: Wrap-up and finish working on remaining issues
- Phase 8 | Final evaluation | 26 August - 2 September: Blog on analysis of Australian smart meters using R package developed and upload progess report
Detailed Project Timeline
-------------------------
| Phase | Description |Time frame | Task Description |
|--------- |---------------------------------- |---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Phase 0 | Pre-GSoC Period (11 Apr - 6 May) | weeks 1-3 | Literature reading, and outline broad range of functions to be developed for each modules. Compiling range of applications and data, additional to smart meters, and creation of small testing sets. |
| Phase 1 | Community Bonding Period (7 May - 26 May) | weeks 1-2 | Lay out the road map for the project with the guidance of the mentors and establish modes of communication. Create and share github site for the project, and set up issues, code structure, invite mentors as collaborators. Add travis CI to site to continuously check code as it is developed. Brainstorm the ideas with mentors, range of applications and test data sets compiled, and code structure to be developed. |
| Phase 2 | Coding Period 1 (27 May - 23 June) | week 1 | Code simple granularity functions (BUILD). Create unit tests. |
| | | week 2 | Code remaining granularity functions (BUILD), and unit tests. Document with roxygen. Provide example code on test data sets. |
| | | week 3 | Code advice functions (COMPATIBILTY), and unit tests. Document with roxygen. Provide example code on test data sets. |
| | | week 4 | Documentation in the form of a vignette on broader range of data applications. CRAN tests completed. | |
| Phase 3 | Phase 1 Evaluations (24 June - 28 June) | | Announce package base to social media community, and request input, and code review. Report on current progress at project’s wiki page after feedback from mentors. <br><br> Deliverables: <br><br> 1. **R package with granularity and advice functions** <br>2. **documentation with roxygen** <br>3. **unit tests** <br>4. **example code on test data** <br>5. **CRAN tests**<br>6. **progess report** |
| Phase 4 | Coding Period 2 (29 June - 22 July) | week 1 | Address issues and improvements from community on functions (BUILD and COMPATIBILITY) and make the package ready for submission to CRAN. |
| | | weeks 2-3 | Develop shiny UI to guide an user to navigate through the modules of the R package. |
| Phase 5 | Phase 2 Evaluations (23 July - 26 July) | | Create user documentation for the shiny app. Announce shiny app to social media community, and request input, code and features review. Report on current progress at project’s wiki page after feedback from mentors.<br><br> Deliverables: <br><br> 1. **address issues and improvements on R package** <br>2. **Shiny UI** <br>3. **documentation for shiny app** <br>4. **progess report** |
| Phase 6 | Coding Period 3 (27 July - 18 August) | week 1 |Work on improving the shiny UI features based on reviews and issues. |
| | | week 2 |Document the R package functionality in a vignette |
| | | week 3 | Provide examples of probability visualization of smart meter data collected on Australian households |
| Phase 7 | Final Week of submitting product (19 August - 26 August) | |Use as buffer to wrap up and address remaining issues. Document ideas that resulted from discussion with mentors and community but could not be implemented due to time limitations. These can then form the basis of future work. |
| Phase 8 | Final evaluation (27 August - 2 September) | | Announce vignette to social media community. Write a blog on analysis of Australian smart meter data exemplifying the usefulness of functions developed in this project. Report on all work done at project’s wiki page after feedback from mentors.<br><br> Deliverables: <br><br> 1. **improve Shiny UI features** <br>2. **R package vignette** <br>3. **application on Australian smart meters** <br>4. **progess report** |
Additional information regarding timeline
-----------------------------------------
- The above timeline is tentative and gives a rough idea of my planned project work. I’ve no major commitments during summer (winter in Australia) and hence, will be able to dedicate 40 hours to 50 hours a week. During the last month of the project, my university will reopen and I’ll be able to dedicate around 30 hours a week. I plan to complete major chunk of the work before university reopens.
- I'll publish blogs at the end of each coding phase that will include highlights of the development process, hurdles that I came across and how I overcame them. Also, I would document some good practices that I learnt while looking at codes from developers of R community who are working in similar fields.
- I’ll be setting up weekly meetings with my mentors where I update them on where I am on the project and discussing ideas on improving functions and features.
## Mentors
- <NAME> <<EMAIL>>
- <NAME> <<EMAIL>>
Brief bio
----------------
I'm a PhD student in the Department of Econometrics and Business Statistics at Monash University, Australia. My research interests are in data visualization, exploratory analysis, time series analysis and computational statistics. I had completed M.Stat (Masters in Statistics) from the Indian Statistical Institute with Quantitative Economics specialization and Bachelors (Honors) in Statistics from St.Xavier’s College, University of Calcutta, following which I had worked with KPMG and PAYBACK in the Analytics/ Modelling team. Although I have had a training in Pure Statistics, I have always been fascinated by the role of statistics in real world applications. I love working with data and create useful tools that can be deployed by users in different applications. One of the interesting projects that I had implemented using R can be found [here](https://ieeexplore.ieee.org/abstract/document/7935757). Thus, I have used R as a tool to implement statistical techniques earlier. However, looking at it from the perspective of open source technology has given it a totally different meaning. It made me realize that working on an open source project amounts to improving the quality of the final product through transparent collaboration with others. Moreover, I also learnt the importance of documented and easy to read codes. Some of my open source contributions can be found [here](https://github.com/ropenscilabs/cricketdata).
<file_sep>library(shiny)
# Define several objects and store them to disk
# x <- rnorm(100)
# y <- rnorm(200)
# z <- "some text for the title of the plot"
#
# save(x, file = "x.RData")
# save(x, y, z, file = "xyz.RData")
# rm(x, y, z)
# Define UI
ui <- shinyUI(fluidPage(
titlePanel(".RData File Upload Test"),
mainPanel(
fileInput("file", label = ""),
actionButton(inputId="plot","Plot"),
tableOutput("contents"),
plotOutput("hist"))
)
)
# Define server logic
server <- shinyServer(function(input, output) {
observeEvent(input$plot,{
if ( is.null(input$file)) return(NULL)
inFile <- isolate({input$file })
file <- inFile$datapath
load(file, envir = .GlobalEnv)
# Plot the data
output$hist <- renderPlot({
plot(x,y[1:100],main=z)
})
})
})
# Run the application
shinyApp(ui = ui, server = server) | 604c4a5d373c100799017eb3abda01f54882e9cd | [
"Markdown",
"R",
"RMarkdown"
]
| 16 | RMarkdown | Sayani07/gsoc2019 | 53910be1eafa96d32e5a0addeb6b3b7cde334da5 | 9e38364e0d659786ff832b2e9dd265d15ce58ec5 |
refs/heads/master | <file_sep>package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/mitchellh/mapstructure"
)
// Definition ...
type Definition struct {
Title string `json:"title"`
Type string `json:"type"`
Properties interface{} `json:"properties"`
}
// Request ...
type Request struct {
RqBody BodyObj `json:"rqBody"`
}
// Response ...
type Response struct {
RsBody BodyObj `json:"rsBody"`
Error BodyArray `json:"error"`
}
// ResponseErr ...
type ResponseErr struct {
RsBody BodyObjNull `json:"rsBody"`
Error BodyArray `json:"error"`
}
// FilterErrorCode ...
type FilterErrorCode struct {
Code BodyBasicType `json:"errorCode"`
Message BodyBasicType `json:"errorDesc"`
}
// BodyObj ...
type BodyObj struct {
Type string `json:"type"`
Properties interface{} `json:"properties"`
}
// BodyObjNull ...
type BodyObjNull struct {
Type string `json:"type"`
Nullable string `json:"nullable"`
}
// BodyArray ...
type BodyArray struct {
Type string `json:"type"`
Items interface{} `json:"items"`
}
// BodyBasicType ...
type BodyBasicType struct {
Type string `json:"type"`
}
var (
dir = flag.String("dir", "swagger", "a directory")
)
func init() {
flag.Parse()
}
func main() {
filePath := *dir
if filePath != "" {
filePath += "/"
}
newDefinitions := make(map[string]interface{})
JSONString, _ := ioutil.ReadFile(filePath + "swagger.json")
var data map[string]interface{}
json.Unmarshal(JSONString, &data)
definitions := data["definitions"].(map[string]interface{})
for i := range definitions {
currentStruct := definitions[i].(map[string]interface{})
tempProp := currentStruct["properties"]
structName := strings.Split(i, ".")[1]
if strings.HasPrefix(strings.ToLower(strings.TrimSpace(structName)), "req") {
currentStruct["properties"] = Request{RqBody: BodyObj{Type: "object", Properties: tempProp}}
} else if strings.HasPrefix(strings.ToLower(strings.TrimSpace(structName)), "res") {
fmt.Println("tempProp")
fmt.Println(tempProp)
if tempProp == nil {
currentStruct["properties"] = ResponseErr{
RsBody: BodyObjNull{Type: "object", Nullable: "true"},
Error: BodyArray{Type: "array", Items: BodyObj{Type: "object", Properties: FilterErrorCode{Code: BodyBasicType{Type: "string"}, Message: BodyBasicType{Type: "string"}}}},
}
} else {
currentStruct["properties"] = Response{
RsBody: BodyObj{Type: "object", Properties: tempProp},
Error: BodyArray{Type: "array", Items: BodyObj{Type: "object", Properties: FilterErrorCode{Code: BodyBasicType{Type: "string"}, Message: BodyBasicType{Type: "string"}}}},
}
}
} else {
currentStruct["properties"] = tempProp
}
var newDef Definition
mapstructure.Decode(currentStruct, &newDef)
newDefinitions[i] = newDef
}
data["definitions"] = newDefinitions
myJSON, _ := json.Marshal(data)
f, err := os.Create(filePath + "swagger.json")
if err != nil {
log.Fatal("error create file", err)
return
}
defer f.Close()
w := bufio.NewWriter(f)
_, err = w.WriteString(string(myJSON))
if err != nil {
log.Fatal("error write to "+f.Name()+".js", err)
return
}
w.Flush()
}
<file_sep>how to use -->
. ./swaggerAppender -dir=directory_namer
will write swagger.json to directory
example -->
. ./swaggerAppender -dir=swagger
will write swagger/swagger.json
note: directory need to be created first (maybe will be improved in the future if needed) | 7bc011670675e5aac57fa0e596c8c648618def11 | [
"Text",
"Go"
]
| 2 | Go | ivan-ru/tnSwaggerAppender | d33821eb26a8adcd59052b7ba0fc206e66f189df | 41fb66b675f886f5103077933f35b06dd5016282 |
refs/heads/master | <repo_name>GabrielJd1/WebConsultas<file_sep>/WebConsultas/Models/Funcionario.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace WebConsultas.Models
{
[Table("Funcionario")]
public class Funcionario
{
public Funcionario()
{
telefones = new List<TelefonesFunc>();
}
[Key]
public int idFuncionario { get; set; }
[DisplayName("Nome Funcionário")]
[Required(ErrorMessage = "Digite o nome do funcionário.")]
public string nome { get; set; }
[DisplayName("Salário")]
[Required(ErrorMessage = "Digite o salário do funcionário.")]
public double salario { get; set; }
[DisplayName("Data Demissão")]
public DateTime? dataDemi { get; set; }
[ForeignKey("Cargo")]
[DisplayName("Cargo")]
public int Cargo_idCargo { get; set; }
[ForeignKey("Endereco")]
[DisplayName("Endereco")]
public int Endereco_idEndereco { get; set; }
public virtual Cargo Cargo { get; set; }
public virtual Endereco Endereco { get; set; }
public virtual IEnumerable<TelefonesFunc> telefones { get; set; }
}
}<file_sep>/WebConsultas/Models/Usuario.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace WebConsultas.Models
{
[Table("Usuario")]
public class Usuario
{
[Key]
public int idUsuario { get; set; }
public string nick { get; set; }
public string senha { get; set; }
[ForeignKey("Funcionario")]
public int Funcionario_idFuncionario { get; set; }
public virtual Funcionario Funcionario { get; set; }
}
}<file_sep>/WebConsultas/Models/Bairro.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace WebConsultas.Models
{
[Table("Bairro")]
public class Bairro
{
//editei
[Key]
public int idBairro { get; set; }
[DisplayName("Bairro")]
public string descricao { get; set; }
[ForeignKey("Cidade")]
public int Cidade_idCidade { get; set; }
public virtual Cidade Cidade { get; set; }
}
}<file_sep>/WebConsultas/Models/Endereco.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace WebConsultas.Models
{
[Table("Endereco")]
public class Endereco
{
[Key]
public int idEndereco { get; set; }
[DisplayName("Rua")]
public string rua { get; set; }
[DisplayName("Número")]
public int numero { get; set; }
[DisplayName("Complemento")]
public string complemento { get; set; }
[DisplayName("Observações")]
public string obs { get; set; }
[ForeignKey("Estado")]
public int Estado_idEstado { get; set; }
public virtual Estado Estado { get; set; }
}
}<file_sep>/WebConsultas/Migrations/201803071649162_InitialCreate.cs
namespace WebConsultas.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class InitialCreate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Bairro",
c => new
{
idBairro = c.Int(nullable: false, identity: true),
descricao = c.String(),
Cidade_idCidade = c.Int(nullable: false),
})
.PrimaryKey(t => t.idBairro)
.ForeignKey("dbo.Cidade", t => t.Cidade_idCidade, cascadeDelete: true)
.Index(t => t.Cidade_idCidade);
CreateTable(
"dbo.Cidade",
c => new
{
idCidade = c.Int(nullable: false, identity: true),
descricao = c.String(),
Estado_idEstado = c.Int(nullable: false),
})
.PrimaryKey(t => t.idCidade)
.ForeignKey("dbo.Estado", t => t.Estado_idEstado, cascadeDelete: true)
.Index(t => t.Estado_idEstado);
CreateTable(
"dbo.Estado",
c => new
{
idEstado = c.Int(nullable: false, identity: true),
descricao = c.String(),
})
.PrimaryKey(t => t.idEstado);
CreateTable(
"dbo.Cargo",
c => new
{
idCargo = c.Int(nullable: false, identity: true),
descricao = c.String(),
})
.PrimaryKey(t => t.idCargo);
CreateTable(
"dbo.Endereco",
c => new
{
idEndereco = c.Int(nullable: false, identity: true),
rua = c.String(),
numero = c.Int(nullable: false),
complemento = c.String(),
obs = c.String(),
Estado_idEstado = c.Int(nullable: false),
})
.PrimaryKey(t => t.idEndereco)
.ForeignKey("dbo.Estado", t => t.Estado_idEstado, cascadeDelete: true)
.Index(t => t.Estado_idEstado);
CreateTable(
"dbo.Funcionario",
c => new
{
idFuncionario = c.Int(nullable: false, identity: true),
nome = c.String(),
salario = c.Decimal(precision: 18, scale: 2),
dataDemi = c.DateTime(),
Cargo_idCargo = c.Int(nullable: false),
Endereco_idEndereco = c.Int(nullable: false),
})
.PrimaryKey(t => t.idFuncionario)
.ForeignKey("dbo.Cargo", t => t.Cargo_idCargo, cascadeDelete: true)
.ForeignKey("dbo.Endereco", t => t.Endereco_idEndereco, cascadeDelete: true)
.Index(t => t.Cargo_idCargo)
.Index(t => t.Endereco_idEndereco);
CreateTable(
"dbo.TelefonesFunc",
c => new
{
idTelefone = c.Int(nullable: false, identity: true),
numero = c.String(),
Funcionario_idFuncionario = c.Int(nullable: false),
})
.PrimaryKey(t => t.idTelefone)
.ForeignKey("dbo.Funcionario", t => t.Funcionario_idFuncionario, cascadeDelete: true)
.Index(t => t.Funcionario_idFuncionario);
}
public override void Down()
{
DropForeignKey("dbo.TelefonesFunc", "Funcionario_idFuncionario", "dbo.Funcionario");
DropForeignKey("dbo.Funcionario", "Endereco_idEndereco", "dbo.Endereco");
DropForeignKey("dbo.Funcionario", "Cargo_idCargo", "dbo.Cargo");
DropForeignKey("dbo.Endereco", "Estado_idEstado", "dbo.Estado");
DropForeignKey("dbo.Bairro", "Cidade_idCidade", "dbo.Cidade");
DropForeignKey("dbo.Cidade", "Estado_idEstado", "dbo.Estado");
DropIndex("dbo.TelefonesFunc", new[] { "Funcionario_idFuncionario" });
DropIndex("dbo.Funcionario", new[] { "Endereco_idEndereco" });
DropIndex("dbo.Funcionario", new[] { "Cargo_idCargo" });
DropIndex("dbo.Endereco", new[] { "Estado_idEstado" });
DropIndex("dbo.Cidade", new[] { "Estado_idEstado" });
DropIndex("dbo.Bairro", new[] { "Cidade_idCidade" });
DropTable("dbo.TelefonesFunc");
DropTable("dbo.Funcionario");
DropTable("dbo.Endereco");
DropTable("dbo.Cargo");
DropTable("dbo.Estado");
DropTable("dbo.Cidade");
DropTable("dbo.Bairro");
}
}
}
<file_sep>/WebConsultas/Controllers/BairrosController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebConsultas.Models;
namespace WebConsultas.Controllers
{
public class BairrosController : Controller
{
private WebConsultasContext db = new WebConsultasContext();
// GET: Bairros
public ActionResult Index()
{
var bairros = db.bairros.Include(b => b.Cidade);
return View(bairros.ToList());
}
// GET: Bairros/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Bairro bairro = db.bairros.Find(id);
if (bairro == null)
{
return HttpNotFound();
}
return View(bairro);
}
// GET: Bairros/Create
public ActionResult Create()
{
ViewBag.Cidade_idCidade = new SelectList(db.cidades, "idCidade", "descricao");
return View();
}
// POST: Bairros/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "idBairro,descricao,Cidade_idCidade")] Bairro bairro)
{
if (ModelState.IsValid)
{
db.bairros.Add(bairro);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Cidade_idCidade = new SelectList(db.cidades, "idCidade", "descricao", bairro.Cidade_idCidade);
return View(bairro);
}
// GET: Bairros/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Bairro bairro = db.bairros.Find(id);
if (bairro == null)
{
return HttpNotFound();
}
ViewBag.Cidade_idCidade = new SelectList(db.cidades, "idCidade", "descricao", bairro.Cidade_idCidade);
return View(bairro);
}
// POST: Bairros/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "idBairro,descricao,Cidade_idCidade")] Bairro bairro)
{
if (ModelState.IsValid)
{
db.Entry(bairro).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Cidade_idCidade = new SelectList(db.cidades, "idCidade", "descricao", bairro.Cidade_idCidade);
return View(bairro);
}
// GET: Bairros/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Bairro bairro = db.bairros.Find(id);
if (bairro == null)
{
return HttpNotFound();
}
return View(bairro);
}
// POST: Bairros/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Bairro bairro = db.bairros.Find(id);
db.bairros.Remove(bairro);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>/WebConsultas/Models/Estado.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace WebConsultas.Models
{
[Table("Estado")]
public class Estado
{
public Estado()
{
Cidades = new List<Cidade>();
}
[Key]
public int idEstado { get; set; }
[DisplayName("Estado")]
public string descricao { get; set; }
public virtual IEnumerable<Cidade> Cidades { get; set; }
}
}<file_sep>/WebConsultas/Controllers/TelefonesFuncsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebConsultas.Models;
namespace WebConsultas.Controllers
{
public class TelefonesFuncsController : Controller
{
private WebConsultasContext db = new WebConsultasContext();
// GET: TelefonesFuncs
public ActionResult Index()
{
var telefones = db.telefones.Include(t => t.Funcionario);
return View(telefones.ToList());
}
// GET: TelefonesFuncs/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TelefonesFunc telefonesFunc = db.telefones.Find(id);
if (telefonesFunc == null)
{
return HttpNotFound();
}
return View(telefonesFunc);
}
// GET: TelefonesFuncs/Create
public ActionResult Create()
{
ViewBag.Funcionario_idFuncionario = new SelectList(db.funcionarios, "idFuncionario", "nome");
return View();
}
// POST: TelefonesFuncs/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "idTelefone,numero,Funcionario_idFuncionario")] TelefonesFunc telefonesFunc)
{
if (ModelState.IsValid)
{
db.telefones.Add(telefonesFunc);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Funcionario_idFuncionario = new SelectList(db.funcionarios, "idFuncionario", "nome", telefonesFunc.Funcionario_idFuncionario);
return View(telefonesFunc);
}
// GET: TelefonesFuncs/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TelefonesFunc telefonesFunc = db.telefones.Find(id);
if (telefonesFunc == null)
{
return HttpNotFound();
}
ViewBag.Funcionario_idFuncionario = new SelectList(db.funcionarios, "idFuncionario", "nome", telefonesFunc.Funcionario_idFuncionario);
return View(telefonesFunc);
}
// POST: TelefonesFuncs/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "idTelefone,numero,Funcionario_idFuncionario")] TelefonesFunc telefonesFunc)
{
if (ModelState.IsValid)
{
db.Entry(telefonesFunc).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Funcionario_idFuncionario = new SelectList(db.funcionarios, "idFuncionario", "nome", telefonesFunc.Funcionario_idFuncionario);
return View(telefonesFunc);
}
// GET: TelefonesFuncs/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TelefonesFunc telefonesFunc = db.telefones.Find(id);
if (telefonesFunc == null)
{
return HttpNotFound();
}
return View(telefonesFunc);
}
// POST: TelefonesFuncs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
TelefonesFunc telefonesFunc = db.telefones.Find(id);
db.telefones.Remove(telefonesFunc);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>/WebConsultas/Models/WebConsultasContext.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace WebConsultas.Models
{
public class WebConsultasContext : DbContext
{
public WebConsultasContext() : base("WebConsultas")
{
Database.CreateIfNotExists();
}
public DbSet<Funcionario> funcionarios { get; set; }
public DbSet<TelefonesFunc> telefones { get; set; }
public DbSet<Estado> estados { get; set; }
public DbSet<Endereco> enderecos { get; set; }
public DbSet<Cidade> cidades { get; set; }
public DbSet<Cargo> cargos { get; set; }
public DbSet<Bairro> bairros { get; set; }
public System.Data.Entity.DbSet<WebConsultas.Models.Perfil> Perfils { get; set; }
public System.Data.Entity.DbSet<WebConsultas.Models.Usuario> Usuarios { get; set; }
}
}<file_sep>/WebConsultas/Models/TelefonesFunc.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace WebConsultas.Models
{
[Table("TelefonesFunc")]
public class TelefonesFunc
{
[Key]
public int idTelefone { get; set; }
[DisplayName("Número")]
public string numero { get; set; }
[ForeignKey("Funcionario")]
public int Funcionario_idFuncionario { get; set; }
public virtual Funcionario Funcionario { get; set; }
}
} | 085eed30e9abe9115d17aaff6a14951bf75a78d6 | [
"C#"
]
| 10 | C# | GabrielJd1/WebConsultas | 57e4321f38bdb7ae6d3215241d4d47de3446c310 | 9dfdac37f240fc6f7e5833b0c729d7f554fdfeff |
refs/heads/master | <repo_name>pooja291/ML-Precourse<file_sep>/precourse.py
# Machine Learning/Data Science Precourse Work
# ###
# LAMBDA SCHOOL
# ###
# MIT LICENSE
# ###
# Free example function definition
# This function passes one of the 11 tests contained inside of test.py. Write the rest, defined in README.md, here, and execute python test.py to test. Passing this precourse work will greatly increase your odds of acceptance into the program.
import numpy as np
def f(x):
return (x**2)
def f_2(x):
return (x**3)
def f_3(x):
return (x**3)+(x*5)
def d_f(x):
return x*2
def d_f_2(x):
return 3*(x**2)
def d_f_3(x):
return 3*(x**2)+5
def vector_sum(x,y):
return np.add(x,y)
def vector_less(x,y):
return np.subtract(x,y)
def vector_magnitude(x):
return np.linalg.norm(x)
def vec5():
return np.array([1,1,1,1,1])
def vec3():
return np.array([0,0,0])
def vec2_1():
return np.array([1,0])
def vec2_2():
return np.array([0,1])
def matrix_multiply(vec,matrix):
return np.inner(vec,matrix)
| aa8e7479f7d2358b2a450fe82c3f0972e83c7656 | [
"Python"
]
| 1 | Python | pooja291/ML-Precourse | 3f75fb39fc5b61dbb4de58815918470579b8e701 | d4b7b32be72aef4794e46047125372fddaf6ac17 |
refs/heads/master | <repo_name>fredesere/aleph<file_sep>/services/ingest-file/requirements.txt
banal==0.4.2
normality==2.0.0
pantomime==0.3.3
servicelayer[google,amazon]==1.8.4
balkhash[leveldb,sql]==1.0.2
followthemoney==1.21.5
languagecodes==1.0.5
psycopg2-binary==2.8.4
pyicu==2.3.1
grpcio==1.24.3
google-cloud-vision==0.39.0
google-cloud-storage==1.20.0
# Development
nose==1.3.7
click==7.0
# File format support
dbf==0.98.3
pdflib==0.2.1
pymediainfo==4.1
python-magic==0.4.15
pypdf2==1.26.0
rarfile==3.1
xlrd==1.2.0
openpyxl==3.0.0
odfpy==1.4.0
cchardet==2.1.4
lxml==4.4.1
olefile==0.46
pillow==6.2.1
vobject==0.9.6.1
msglite==0.26.0
cryptography==2.8
requests[security]==2.22.0<file_sep>/aleph/logic/processing.py
import logging
from banal import is_mapping
from followthemoney import model
from followthemoney.exc import InvalidData
from followthemoney.pragma import remove_checksums
from aleph.model import Entity, Document
from aleph.queues import ingest_entity
from aleph.analysis import analyze_entity
from aleph.queues import queue_task, OP_INDEX
from aleph.index.entities import index_bulk
from aleph.logic.entities import refresh_entity_id
from aleph.logic.collections import refresh_collection, reset_collection
from aleph.logic.aggregator import get_aggregator
log = logging.getLogger(__name__)
def _collection_proxies(collection):
for entity in Entity.by_collection(collection.id).yield_per(1000):
yield entity.to_proxy()
for document in Document.by_collection(collection.id).yield_per(1000):
yield document.to_proxy()
def process_collection(stage, collection, ingest=True,
reset=False, sync=False):
"""Trigger a full re-parse of all documents and re-build the
search index from the aggregator."""
ingest = ingest or reset
if reset:
reset_collection(collection, sync=True)
aggregator = get_aggregator(collection)
try:
writer = aggregator.bulk()
for proxy in _collection_proxies(collection):
writer.put(proxy, fragment='db')
stage.report_finished(1)
writer.flush()
if ingest:
for proxy in aggregator:
ingest_entity(collection, proxy, job_id=stage.job.id)
else:
queue_task(collection, OP_INDEX,
job_id=stage.job.id,
context={'sync': sync})
finally:
aggregator.close()
def _process_entity(entity, sync=False):
"""Perform pre-index processing on an entity, includes running the
NLP pipeline."""
if entity.id is None:
raise InvalidData("No ID for entity", errors=entity.to_dict())
analyze_entity(entity)
if sync:
refresh_entity_id(entity.id)
# log.debug("Index: %r", entity)
return entity
def _fetch_entities(stage, collection, entity_id=None, batch=50):
aggregator = get_aggregator(collection)
try:
if entity_id is None:
yield from aggregator
return
yield from aggregator.iterate(entity_id=entity_id)
# WEIRD: Instead of indexing a single entity, this will try
# pull a whole batch of them off the queue and do it at once.
done = 0
for task in stage.get_tasks(limit=batch):
entity_id = task.payload.get('entity_id')
for entity in aggregator.iterate(entity_id=entity_id):
yield entity
done += 1
stage.mark_done(done)
finally:
aggregator.close()
def index_aggregate(stage, collection, entity_id=None, sync=False):
"""Project the contents of the collections aggregator into the index."""
entities = _fetch_entities(stage, collection, entity_id=entity_id)
entities = (_process_entity(e, sync=sync) for e in entities)
index_bulk(collection, entities, job_id=stage.job.id)
refresh_collection(collection.id)
def bulk_write(collection, entities, job_id=None, unsafe=False):
"""Write a set of entities - given as dicts - to the index."""
def _generate():
for data in entities:
if not is_mapping(data):
raise InvalidData("Failed to read input data", errors=data)
entity = model.get_proxy(data)
if not unsafe:
entity = remove_checksums(entity)
yield _process_entity(entity)
index_bulk(collection, _generate(), job_id=job_id)
refresh_collection(collection.id)
| ea9c14f1007fb62cb1e8978755379a6ab4a56518 | [
"Python",
"Text"
]
| 2 | Text | fredesere/aleph | 03d80bc74ebb4aab5dc4259fdce8073628f06b70 | b0013c1bd0b16d900655e80c1342d2a802e8b07d |
refs/heads/master | <repo_name>CiffSCR/repositorioPrueba<file_sep>/src/proyecto2/funcionSegunda.r
# V 1.0.0 version inicial para pruebas de repositorio
# proyecto 2
library(lpsolve)
prueba2<-function(paramA, paramB){
resultado<-paramA*paramB
return (resultado)
}
<file_sep>/src/proyecto1/funcionPrimera.r
# V 1.0.0 version inicial para pruebas de repositorio
# proyecto 1
library(lpsolve)
prueba1<-function(paramA, paramB){
resultado<-paramA+paramB
return (resultado)
}
| a50918a606c98159a1330e9697b8b0b7011d1e4a | [
"R"
]
| 2 | R | CiffSCR/repositorioPrueba | d0ae264ba0cb995f3a9ab75dabf8a054bcf38795 | bb5b7b475cbc7d569fd46a55bf2d475da6813665 |
refs/heads/main | <file_sep>'use strict';
console.log("Greeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeen Day");<file_sep>'use strict';
function User (name, age) {
let userName = name;
this.age = age;
this.say = () => {
console.log(`Username: ${userName}\nAge: ${this.age}`);
};
this.getMge = () => {
return userName;
};
this.setName = (name) => {
if (typeof name != 'number' && name.length < 30 && name.length > 2) {
userName = name;
} else {
console.log('\n\n[!] Invalid name\n\n');
}
}
};
const alex = new User('Alex', 25);
alex.userName = 'sdf'; // Не сработает!
alex.say();
alex.setName('ssssssssssssssssssssssssssssssssssssssssssssssssJimmy');
alex.setName('Jimmy');
alex.say();
class ClassUser {
constructor (name, age) {
let _name = name;
this._age = age;
}
say () {
console.log(`Username: ${this._name}\nAge: ${this._age}`);
}
get name () {
return this._name;
}
set name(newName) {
if (typeof newName != 'number' && newName.length < 30 && newName.length > 2) {
this._name = newName;
} else {
console.log('Invalid name');
}
}
}
const userObj = new ClassUser("Jimmy", 17);
userObj._name = 'Alex';
userObj.say();<file_sep>"use strict";
const script = document.createElement('script'); // Создал конст. script, куда поместил значение, (тэг script).
script.src = 'js/test1.js'; // Указал атрибут для тега script из конст. script, путём src.
script.defer = true; // Добавляю артибут для defer для тега script.
document.body.append(script); // Добавляю тег script в body (в самый конец).<file_sep>function calc () {
const gender = document.querySelectorAll('[data-gender]');
const inputs = document.querySelectorAll('[data-calc-inputs]');
const activity = document.querySelectorAll('[data-activity]');
const calcValue = document.querySelector('.calculating__result span');
const calcDB = {
gender: gender[0].innerText,
height: '',
weight: '',
age: '',
activity: activity[1].getAttribute('data-activity')
};
const checkValue = (obj) => {
for (let i in obj) {
if (obj[i] == '') {
return false;
}
}
return true;
};
const changeValue = (obj) => {
if (checkValue(obj)) {
let result = 0;
if (obj.gender == 'Мужчина') {
result = Math.round((447.6 + (9.2 * obj.weight) + (3.1 * obj.height) - (4.3 * obj.age)) * calcDB.activity);
} else {
result = Math.round((88.36 + (13.4 * obj.weight) + (4.8 * obj.height) - (5.7 * obj.age)) * calcDB.activity);
}
if (result < 0) {
calcValue.innerHTML = '0';
} else if (result > 5000) {
calcValue.innerHTML = '0';
} else {
calcValue.innerHTML = result;
localStorage.setItem('calcValues', obj);
}
}
};
gender.forEach(item => {
item.addEventListener('click', (event) => {
gender.forEach(tag => {
tag.classList.remove('calculating__choose-item_active');
});
calcDB.gender = event.target.innerText;
event.target.classList.add('calculating__choose-item_active');
changeValue(calcDB);
});
});
inputs.forEach(item => {
item.addEventListener('input', (event) => {
calcDB[event.target.id] = event.target.value;
changeValue(calcDB);
});
});
activity.forEach(item => {
item.addEventListener('click', (event) => {
activity.forEach(tag => {
tag.classList.remove('calculating__choose-item_active');
});
calcDB.activity = event.target.getAttribute('data-activity');
event.target.classList.add('calculating__choose-item_active');
changeValue(calcDB);
});
});
}
export default calc;<file_sep>"use strict";
function User (name, id) { // Старый формат, не нуждающийся в представлении.
this.name = name;
this.id = id;
this.human = true;
this.sayHello = () => {
console.log(`${this.name} says "Hello!"`);
};
this.saySomeThing = (text) => {
console.log(`${this.name} says "${text}"`);
};
}
const ivan = new User('Ivan', '0');
const alex = new User('Alex', '1');
console.log(ivan);
console.log(alex);
alex.saySomeThing("HW");
<file_sep>"use strict";
let hw = "Hello world"; // Создал переменную, присвоил ей значение в виде строки.
console.log(hw.length); // Выбрасываю в консоль длину значения переменной hw.
console.log(hw.toUpperCase()); // Выбрасываю в консоль значение переменной hw в верхнем регистре.
console.log(hw.toLowerCase()); // Выбрасываю в консоль значение переменной hw в нижнем регистре.
const world = "world"; // Создаю констану и присваиваю ей значение в виде строки.
console.log(world.slice(3)); // slice - это срез.<file_sep>"use strict";
function showFirstMessage() { // Создаю функцию...
console.log("Hello world"); // Которая выводит на экран слово Hello world
}
showFirstMessage(); // Вызываю функцию showFirstMessage, чтобы она заработала.
function plus(x, y) { // Создаю функцию, которая принимает на вход 2 значения.
console.log(x + y); // И выбраывает в консоль сумму этих чисел
}
plus(5, 2); // Вызываю функцию, которая имеет на вход 2 числа (5 и 2).
function returntext(text) { // Создаю функцию, которая принимает на вход одно значение.
return text; // Функция возвращает то, что было передано в эту функцию.
}
console.log(returntext("hw")); // Выбрасываю в консоль то, что вернёт функция returntext
let logger = function() { /* Создал expression function. Имеет особенность, что её можно
вызывать ТОЛЬКО ТОГДА, когда её создадут. Но никак не до её создания.*/
console.log("Hello"); // Выбрасываю в консоль слово Hello.
};
logger(); // Вызываю экспрешн функцию.
let calc = (a, b, c, d) => {return a + b + c + d}; /* Я создал стрелочную функцию, которая
принимает на вход 4 значения. Так же эта функция возвращает сумму. */
console.log(calc(1, 2, 3, 4)); // Самым обычным образом выбрасываю в консоль то, что вернёт функция.<file_sep>"use strict";
let num = prompt("Введите абсолютно любое число меньше нуля:"); // Запрашиваю у пользователя данные.
if (+num > 0) { // Если введенное им ЧИСЛО будет больше нуля, то тогда...
alert("Вы ввели число больше нуля."); // Оповестить его о том, что он ввёл число больше нуля.
} else if (+num === 0) { // В другом случае, если ЧИСЛО будет равно нулю и по типу и по значению, то...
alert("Вы ввели ноль."); // Оповестить его о том, что он ввёл ноль.
} else if (+num < 0) { // В другом случае, если ЧИСЛО будет меньше нуля, то...
alert("Вы ввели всё верно."); // Оповестить его о том, что всё сделано верно.
} else { // Во всех других случаях...
alert("Вы ввели что-то не то."); // Оповестить его о том, что пользователь ввёл что-то не то.
}
let userColour = prompt("Введите число от нуля до трёх:"); // Запрашиваю у пользователя данные.
switch (+userColour) { // Проверяю значение ЧИСЛОВОЙ переменной на условия ниже...
case 1: // Если значение переменной равно цифре 1, то...
alert("Вы ввели всё верно"); // Оповестить пользователь, что введено всё верно.
break; // Завершить блок. (Прервать цикл)
case 2: // Если значение переменной равно цифре 2, то...
alert("Вы ввели всё верно");// Оповестить пользователь, что введено всё верно.
break;// Завершить блок. (Прервать цикл)
case 3: // Если значение переменной равно цифре 3, то...
alert("Вы ввели всё верно");// Оповестить пользователь, что введено всё верно.
break;// Завершить блок. (Прервать цикл)
default: // Во всех других случаях...
alert("Вы не соблюдали условия."); // Оповестить пользователя, что он не соблюдал условия.
}<file_sep>"use strict";
let i = 0; // Создаю переменную и присваиваю ей значение 0.
while ( i != 10 ) { // ПОКА значение переменной i не будет равно 10.
console.log(i); // Выбросить в консоль значение переменной i.
i++; // Увеличивать значение переменной на одну единицу.
}
i = 0; // Присваиваю переменной i, значение 0.
do { // СДЕЛАТЬ (то что ниже)
console.log(i); // Выбросить в консоль значение переменной i.
i++; // Увеличивать значение переменной на одну единицу.
} while ( i != 10 ); // ПОКА значение переменной i не будет равно 10.
for(i = 0; i != 10; i++) { /* Присваиваю значение 0, перменной, i. Итерировать, пока
ёё значение не будет равно десяти и увеличивать её значение
на одну единицу с каждой итерацией */
console.log(i); // Выбросить в консоль значение переменной i.
}<file_sep>'use strict';
const now = new Date(); // Вот тут я получил конструктор Date.
console.log(now.getFullYear()); // Вот тут я, воспользовавшись его методом получил текущий год.
console.log(now.getHours()); // Тут часы.
console.log(now.getMinutes()); // Тут минуты.
console.log(now.getSeconds()); // А тут секунды.<file_sep>'use strict';
function* justAGenerator() {
yield 'h';
yield 'e';
yield 'l';
yield 'l';
yield 'o';
}
const str = justAGenerator();
console.log(str.next().value);
console.log(str.next().value);
console.log(str.next().value);
console.log(str.next().value);
console.log(str.next().value);<file_sep>'use strict';
const inputRUB = document.querySelector('#rub'), // Получаю элементы по их IDшнику.
inputUSD = document.querySelector('#usd');
inputRUB.addEventListener('input', () => { // Добавляю эвент листенер при вводе чего-либо в input.
const request = new XMLHttpRequest(); // Создаю объект на основе класса XMLHttpRequest.
request.open("GET", "./js/current.json"); // При получении GET запроса, я открываю файл current.json.
request.overrideMimeType("application/json"); // Я даю понять что всё будет передаваться в json формате.
request.setRequestHeader("Content-type", "application/json; charset=utf-8"); // Тут я создаю хедер, для успешного GET запроса.
request.send(); // Тут я отправляю запрос.
request.addEventListener('load', () => { // Добавляю эвент листенер на запрос, при его ЗАГРУЗКЕ.
if (request.status === 200) { // Проверяю статус, который вернет нам запрос. Если он будет равен 200, то тогда...
console.log(request.response); // Вывести в консоль то, что он получил.
const data = JSON.parse(request.response);
inputUSD.value = +inputRUB.value / data.current.usd.toFixed(2);
} else { // Во всех других случаях.
inputUSD.value = 'Ошибка';
}
});
});<file_sep>"use strict";
const log = (a, b, ...rest) => {
console.log(`a: ${a}\nb: ${b}\nRest: ${rest}`);
console.log(rest);
};
log(1, 2, 'hello', 'world', 'I', 'love', 'it');<file_sep>'use strict';
const ans = prompt('Enter your name');
const reg = /n/i;
console.log(ans.match(reg));<file_sep>"use strict";
const options = { // Создаю объект options.
name: 'test', // Даю ему первое свойство name со значением test.
width: 1024, // Даю ему второе свойство со значением.
height: 1024, // Даю ему третье свойство со значением.
colors: { // Даю ему четвёртое свойство, которое является объектом.
border: 'black', // Даю четвёртому свойству options, свойству border значение black.
bg: 'red' // Даю четвёртому свойству options, свойству bg значение red.
},
showtext: function(text) { // Даю пятому свойству в значения - функцию.
console.log(text); // Данная функция будет выводить на экран текст, который передан в параметры.
}
};
console.log(options['name']); // Вывожу на экран значение свойства name, объекта options.
delete options.name; // Удаляю свойство name у объекта options.
console.log(options); // Вывожу на экран объект options.
for (let i in options) { // Пробегаюсь циклом по свойствам объекта options
if (typeof options[i] === 'object') { // Если вдруг, значение свойства будет равна объекту, то...
console.log(`Ключ ${i} равен объекту. Который состоит из следующих частей:`); // Вывести на экран строку.
for (let j in options[i]) { // Пробежаться циклом по этому объекту, внутри объекта.
console.log(`Свойство ${j} равно ${options[i][j]}`); // Вывожу на экран строку.
}
continue; // Продолжаю цикл.
} else { // Во всех других случаях...
console.log(`Свойство ${i} равно ${options[i]}`); // Вывожу на экран строку.
}
}
let optionsKeys = Object.keys(options); // Создаю переменную, которая равна всем свойствам option, НО это уже получается массив.
console.log(optionsKeys); // Вывожу на экран этот массив.
options.showtext("Hello world"); // Использую метод объекта options, под названием showtext, который выводин на экран текст, пераданный в параметры.
let {border, bg} = options.colors; // Создаю 2 переменные, которые равняются свойстам, которые лежат в объекте colors, лежащим в объекте options
console.log(border); // Вывожу на экран значение переменной border.
console.log(bg); // Вывожу на экран значение переменно bg.
<file_sep>const showModalWindow = (modalSelector) => {
const modalWindow = document.querySelector(modalSelector);
if (modalWindow.classList.contains('hide')) {
modalWindow.classList.add('show');
modalWindow.classList.remove('hide');
modalWindow.classList.add('fade');
}
};
const closeModalWindow = (modalSelector) => {
const modalWindow = document.querySelector(modalSelector);
if (modalWindow.classList.contains('show')) {
modalWindow.classList.remove('show');
modalWindow.classList.add('hide');
}
};
function modal (triggerSelector, modalSelector, closeSelector) {
const showModalElement = document.querySelectorAll(triggerSelector);
const modalWindow = document.querySelector(modalSelector);
const closeModalWindowElement = document.querySelector(closeSelector);
showModalElement.forEach((element) => {
element.addEventListener('click', () => {
showModalWindow(modalSelector);
});
});
closeModalWindowElement.addEventListener('click', () => {
closeModalWindow(modalSelector);
});
modalWindow.addEventListener('click', (event) => {
if (event.target === modalWindow || event.target.getAttribute('data-modal-close' == '')) {
closeModalWindow(modalSelector);
}
});
document.addEventListener('keydown', (e) => {
if (e.code === 'Escape' && modalWindow.classList.contains('show')) {
closeModalWindow(modalSelector);
}
});
// Open modal window by timeout&by scroll down
const modalTimer = 50000;
const modalTimeOut = setTimeout(() => {
showModalWindow(modalSelector);
}, modalTimer);
const showModalScroll = () => {
if (window.pageYOffset + document.documentElement.clientHeight >= document.documentElement.scrollHeight) {
showModalWindow(modalSelector);
window.removeEventListener('scroll', showModalScroll);
}
};
window.addEventListener('scroll', showModalScroll);
}
export default modal;
export {closeModalWindow};
export {showModalWindow};<file_sep>"use strict";
let buttons = document.querySelectorAll('button'); // Создаю пвсеводмассив с элементами со страницы.
let i = 0; // Создаю переменную i и присваиваю ей значение 0.
const deleteElement = function (e) { // Создаю функцию, которая принимает к себе на вход один параметр (e).
e.target.remove(); // Удаляю элемент со страницы.
i++; // Увеличиваю значение переменной i на единицу.
if (i == 1) { // Условие: если значение переменной i равно единице, то...
buttons.forEach(element => { // Пробегаюсь циклом по псевдомассиву с элементами и ...
element.removeEventListener('click',deleteElement); // Удаляю лисенер.
});
}
};
buttons.forEach(element => { // Пробегаюсь циклом по псевдомассиву и...
element.addEventListener('click', deleteElement); // Добавляю обработчик событий. (При клике на этот элемент, будет вызываться функция)
});
let a = document.querySelector('a'); // Создаю переменную, которая содержит в себе элемент ссылки со страницы.
a.addEventListener('click', function (event) { // Добавляю обработчик событий к этой ссылки, при клике и сразу создаю функцию.
event.preventDefault(); // Запрещаю ссылке функционировать в свойственной ей форме и перехода по href не будет, а произойдёт...
alert('Не нажимай сюда больше'); // Вот эта часть (выведится сообщение "Не нажимай сюда больше.")
});<file_sep>"use strict";
let a = 5; // Создаю переменную и присваиваю ей значение 5.
let b = a; // Создаю переменную и присваиваю ей значение того, что лежит в переменной a.
b = b + 5; // Увеличиваю значение переменной b на 5.
b += 3; // Увеличиваю значение переменной b на 3.
console.log(a); // Вывожу на экран значение перменной a.
console.log(b); // Вывожу на экран значение переменной b.
let obj = { // Создаю объект, который имеет 2 свойства.
a: 5, // Создаю свойство a и присваиваю ему значение 5.
b: 1 // Создаю свойство b и присваиваю ему значение 1.
};
let copy = obj; // Создаю переменную, которая будет являть ССЫЛКОЙ на объект.
copy.a = 356; // Изменяю значение ссылки объекта obj, следовательно изменяется само значение obj.
console.log(obj.a); // Вывожу на экран свойство объекта obj, переменню, которую я изменил через ССЫЛКУ.
function copyobj (mainObj) { // Вот тут я создаю функцию, которая принимает на вход один параметр.
let newObj = {}; // Вот тут я создаю пустой объект.
for (let i in mainObj) { // Вот тут я пробегаюсь циклом по тому объекту, который есть в параметрах.
newObj[i] = mainObj[i]; // Вот тут я присваиваю значение новому пустому объекту те, что указаны в объекте из параметров.
}
return newObj; /* Вот тут я возвращаю этот новый объект, который уже НЕ является ссылкой на другой
объект, НО ТОЛЬКО В ТОМ СЛУЧАЕ, если этот новый объект внутри себя не имеет другой объект. Иначе он
будет являть ссылкой. */
}
let copiedObj = copyobj(obj); /* Создаю переменную и присваиваю ей значение, которые вернет функция copyobj,
в параметрах которой указан объект. */
copiedObj.a = 323; // Меняю свойство только что созданного объекта на 323.
console.log(copiedObj); // Вывожу на экран только что созданный объект.
console.log(obj); // Вывожу на экран объект, созданный ранее (obj).
let obj1 = { // Создаю я объект.
a: 1, // Даю ему свойства и значения.
b: 2, // Даю ему свойства и значения.
c: 3 // Даю ему свойства и значения.
};
let obj2 = { // Создаю ещё один объект.
d: 4, // Даю ему свойства и значения.
e: 5, // Даю ему свойства и значения.
f: 6 // Даю ему свойства и значения.
}
console.log(Object.assign(obj1, obj2)); // И теперь я объединяю эти 2 объекта и вывожу их на экран.
// Метод assig делает почти то же самое, что и функция copyObj, которую я создал выше.
// Всё то, что будет в новом объекте НЕ будет являть ссылкой на другой объект, но ТОЛЬКО В ТОМ СЛУЧАЕ,
// Если этот объект не содержит вложенных объектов.
// С массивами абсолютно та же самая история.
let testarr = [1, 2, 3, 4, 5, 6, 7, 8]; // Вот я создаю массив testarr.
let test = testarr; // Создаю переменную, которая будет являться ССЫЛКОЙ на массив testarr.
test[0] = "Hello world"; // И теперь изменяя значения у test2, изменяется значение у testarr.
console.log(testarr); // Выбрасываю в консоль значение массива testarr.
let testarr2 = [1, 2, 3, 4, 5, 5, 6, 7, 8]; // Создаю массив.
let test2 = testarr2.slice(); // Создаю переменную, которая будет равняться уже НЕ ссылке, а КОПИИ массива.
test2[0] = "Hello world"; // Указываю, что самое первое значение элемента массива test2 будет равное строке.
console.log(testarr2); // Выбрасываю в консоль массив testarr2.
console.log(test2); // Выбрасываю в консоль массив test2.
let video = ["youtube", "vimeo", "rutube"], // Я создаю массив, в котором есть 3 элемента.
blogs = ["wordpress", "livejournal", "blogger"], // Созда ещё один с 3мя элементами.
internet = [...video, ...blogs, "vk", "facebook"]; /* Создаю массив, в котором РАЗВОРАЧИВАЮ
2 массива video и blogs, причем я на них НЕ ссылаюсь, а можно сказать копирую, словно методом slice. */
console.log(internet); // Вывожу на экран массив internet.<file_sep>'use strict';
const anonPrivate = (function () {
const username = 'Alex';
const age = 27;
const hobby = 'guitar';
const showInfo = () => {
console.log(`
Username: ${username}\n
Age: ${age}\n
Hobby: ${hobby};
`);
};
const saySomething = () => {
console.log(`
Listen yourself!
`);
};
return {
info: showInfo,
words: saySomething
};
}());
anonPrivate.info();
anonPrivate.words();<file_sep>import { closeModalWindow, showModalWindow } from './modal';
const showThanksModal = (message, modalSelector) => {
const prevModalDialog = document.querySelector('.modal__dialog');
prevModalDialog.classList.add('hide');
showModalWindow(modalSelector);
const thanksModal = document.createElement('div');
thanksModal.classList.add('modal__dialog');
thanksModal.innerHTML = `
<div class="modal__content">
<div data-modal-close class="modal__close">×</div>
<div class="modal__title">${message}</div>
</div>
`;
document.querySelector('.modal').append(thanksModal);
setTimeout(() => {
thanksModal.remove();
prevModalDialog.classList.add('show');
prevModalDialog.classList.remove('hide');
closeModalWindow(modalSelector);
}, 4000);
};
export default showThanksModal;
<file_sep>"use strict";
let a = [1, 2, 3, 4, 5, 6, 7, 8]; // Создаю массив.
a.forEach(function(item, number, a) { /* Пробегаюсь циклом по массиву, указывая, что переменная item
равна значению, переменная number равна порядковому номеру, а переменная a равна самому массиву.*/
console.log(item); // Вывожу на экран переменную, равную значению массива.
console.log(number); // Вывожу на экран порядковый номер значения массива.
console.log(a); // Вывожу на экран целый массив.
});
for (let i of a) { // Пробегаюсь циклом по массиву.
console.log(i); // Вывожу на экран значение переменной i.
}
let str = prompt("Введите 3 слова через пробел:", ""); // Жду от пользователя ввода данных.
let products = str.split(" "); // Разбиваю ту строку, которую ввёл пользователь на массив, разделителем служит пробел.
console.log(products); // Вывожу в консоль массив, который сформировался из строки.
console.log(products.join('; ')); // Объединяю все элементы массива в строку, после каждого будет стоять ;.<file_sep>function cards () {
class MenuCard {
constructor(imageSrc, alt, title, description, price, parentSelector) {
this.imageSrc = imageSrc;
this.alt = alt;
this.title = title;
this.description = description;
this.price = price;
this.parentSelector = document.querySelector(parentSelector);
}
render() {
const element = document.createElement('div');
element.innerHTML =
`
<div class="menu__item">
<img data-menu-img src=${this.imageSrc} alt=${this.alt}>
<h3 class="menu__item-subtitle">${this.title}</h3>
<div class="menu__item-descr">${this.description}</div>
<div class="menu__item-divider"></div>
<div class="menu__item-price">
<div class="menu__item-cost">Цена:</div>
<div class="menu__item-total"><span class="span-price">${this.price}</span> грн/день</div>
</div>
</div>
`;
this.parentSelector.append(element);
}
}
axios.get('http://localhost:3000/menu').then(data => {
data.data.forEach(({img, altimg, title, descr, price}) => {
new MenuCard(img, altimg, title, descr, price, '.menu .container').render();
});
});
}
export default cards;<file_sep>'use strict';
const names = ['Alex', 'John', 'Kim', 'Ann', 'Ksenia', 'Voldemart'];
const shortNames = names.filter((name) => {
return name.length < 5;
});
console.log(shortNames);
let answers = ['IvAnn', 'JojN', 'HellO'];
answers = answers.map((item) => {
return item.toLowerCase();
});
console.log(answers);
const allNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const evenNumber = [2, 4, 6, 8];
const sum = allNumbers.reduce((sum, current) => sum + current);
console.log(sum);
const newArr = {
ivan: 'person',
ann: 'person',
dog: 'animal',
cat: 'animal'
};
const persons = Object.entries(newArr).filter((item) => {
return item[1] === 'person';
}).map((item) => item[0]);
console.log(persons);
<file_sep>function slider () {
const slideElement = document.querySelector('.offer__slider-wrapper img'),
prevSlideButton = document.querySelector('.offer__slider-counter .offer__slider-prev'),
nextSlideButton = document.querySelector('.offer__slider-counter .offer__slider-next'),
currentSlideCount = document.querySelector('#current'),
totalSlidesCount = document.querySelector('#total');
let currentSlideNumber = 1;
currentSlideCount.innerHTML = `01`;
axios.get('http://localhost:3000/slides').then(data => {
const totalSlideNumber = `` + Object.entries(data.data[0]).length;
totalSlidesCount.innerHTML = `0${totalSlideNumber}`;
});
nextSlideButton.addEventListener('click', () => {
if (currentSlideNumber != 4) {
currentSlideNumber++;
axios.get('http://localhost:3000/slides').then(data => {
slideElement.classList.add('fade');
slideElement.src = data.data[0]["slide_" + currentSlideNumber];
});
currentSlideCount.innerHTML = `0${currentSlideNumber}`;
slideElement.classList.remove('fade');
}
});
prevSlideButton.addEventListener('click', () => {
if (currentSlideNumber != 1) {
currentSlideNumber--;
axios.get('http://localhost:3000/slides').then(data => {
slideElement.classList.add('fade');
slideElement.src = data.data[0]["slide_" + currentSlideNumber];
});
currentSlideCount.innerHTML = `0${currentSlideNumber}`;
slideElement.classList.remove('fade');
}
});
// Slides navigation
const dots = Array.from(document.querySelectorAll('.dot'));
dots[0].classList.add('active');
dots.forEach(item => {
item.addEventListener('click', (event) => {
dots.forEach(item => {
item.classList.remove('active');
});
const index = dots.indexOf(event.target) + 1;
axios.get('http://localhost:3000/slides').then(data => {
slideElement.classList.add('fade');
slideElement.src = data.data[0]["slide_" + index];
});
currentSlideCount.innerHTML = `0${index}`;
slideElement.classList.remove('fade');
currentSlideNumber = index;
event.target.classList.add('active');
});
});
}
export default slider;<file_sep>"use strict";
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
calcArea() {
return this.width * this.height;
}
}
class ColoredRectangleWithText extends Rectangle {
constructor (height, width, text, bgColor) {
super(height, width);
this.text = text;
this.bgColor = bgColor;
}
showMyProps() {
console.log(`Height: ${this.height}\nWidth: ${this.width}\nText: ${this.text}\nBackground Color: ${this.bgColor}`);
}
}
const rectObj = new Rectangle(10, 10);
console.log(rectObj.calcArea());
const coloredRectObj = new ColoredRectangleWithText(200, 30, 'Hello world', 'red');
coloredRectObj.showMyProps(); | 5fb624caeec94783f5d5f1f3e7afaa43efeef1aa | [
"JavaScript"
]
| 25 | JavaScript | isaev4lex/learning-javascript | be22df5acc30c87a1c2a6a89a5e5c95f7567cf92 | f44abb986f1cade058aa4e345010d950ccd5ff1b |
refs/heads/master | <repo_name>andersonqueiroz/zoopy<file_sep>/zoopy/models/token.py
from zoopy.utils import get, put, post, delete, get_marketplace_id
from zoopy.models import marketplace
BASE_MODEL_URL = '/tokens'
BASE_MODEL_CARD_URL = '/cards'
BASE_MODEL_BANK_ACCOUNT_URL = '/bank_accounts'
def get_full_url(token_type):
if token_type == 'bank_account':
return f'{BASE_MODEL_BANK_ACCOUNT_URL}{BASE_MODEL_URL}'
return f'{BASE_MODEL_CARD_URL}{BASE_MODEL_URL}'
def details(token_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{token_id}'
return get(url)
def create(token_type, params):
url = f'{marketplace.get_full_url()}{get_full_url(token_type)}'
return post(end_point=url, data=params)
def attach_bank_account(token_id, customer_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_BANK_ACCOUNT_URL}'
data = {'customer':customer_id, 'token':token_id}
return post(end_point=url, data=data)
def attach_card(token_id, customer_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_CARD_URL}'
data = {'customer':customer_id, 'token':token_id}
return post(end_point=url, data=data)
def delete_bank_account(bank_account_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_BANK_ACCOUNT_URL}/{bank_account_id}'
return delete(url)<file_sep>/zoopy/models/transaction.py
from zoopy.utils import get, put, post, delete
from zoopy.models import marketplace
BASE_MODEL_URL = '/transactions'
def get_full_url():
return BASE_MODEL_URL
def list(params={}):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}'
return get(url, params=params)
def details(transaction_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{transaction_id}'
return get(url)
def create(params):
url = f'{marketplace.get_full_url()}{(get_full_url())}'
return post(end_point=url, data=params)
def update(transaction_id, params):
url = f'{marketplace.get_full_url()}{get_full_url()}/{transaction_id}'
return put(end_point=url, data=params)
def void(transaction_id, params):
url = f'{marketplace.get_full_url()}{get_full_url()}/{transaction_id}/void'
return post(end_point=url, data=params)
<file_sep>/tests/test_bank_account.py
import unittest
from zoopy import token, bank_account
from tests.base_unittest import BaseTest
from tests.resources import token_data_sample
class TestBankAccount(BaseTest):
def setUp(self):
super(TestBankAccount, self).setUp()
self.__class__._bank_account = token.create(token_type='bank_account',
params=token_data_sample.TOKEN_BANK_ACCOUNT).get('bank_account')
def test01_list_bank_accounts(self):
all_bank_accounts = bank_account.list()
self.assertIsNotNone(all_bank_accounts)
def test01_details_bank_account(self):
details = bank_account.details(bank_account_id=self.__class__._bank_account['id'])
self.assertEqual(self.__class__._bank_account['id'], details['id'])
# def test02_update_bank_account(self):
# update = bank_account.update(bank_account_id=self.__class__._bank_account['id'],
# params={'is_active': 'True'})
# print(update)
# self.assertTrue(update['is_active'])
def test02_delete_bank_account(self):
response = bank_account.remove(bank_account_id=self.__class__._bank_account['id'])
self.assertTrue(response["deleted"])
if __name__ == '__main__':
unittest.main()<file_sep>/zoopy/models/invoice.py
from zoopy.utils import get, put, post, delete, get_marketplace_id
from zoopy.models import marketplace
BASE_MODEL_URL = '/invoices'
def get_full_url():
return BASE_MODEL_URL
def list(params={}, is_beta=False):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}'
return get(url, params=params, is_beta=is_beta)
def list_by_seller(seller_id, params={}, is_beta=False):
url = f'{marketplace.get_full_url()}/sellers/{seller_id}{BASE_MODEL_URL}'
return get(url, params=params, is_beta=is_beta)
def details(invoice_id, is_beta=False):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{invoice_id}'
return get(url, is_beta=is_beta)
def create(params, is_beta=False):
url = f'{marketplace.get_full_url()}{get_full_url()}'
return post(end_point=url, data=params, is_beta=is_beta)
def approve(invoice_id, is_beta=False):
url = f'{marketplace.get_full_url()}{get_full_url()}/{invoice_id}/approve'
return post(end_point=url, is_beta=is_beta)
def void(invoice_id, is_beta=False):
url = f'{marketplace.get_full_url()}{get_full_url()}/{invoice_id}/void'
return delete(end_point=url, is_beta=is_beta) #Na documentação está POST mas a API só responde ao DELETE
def update(invoice_id, params, is_beta=False):
url = f'{marketplace.get_full_url()}{get_full_url()}/{invoice_id}'
return put(end_point=url, data=params, is_beta=is_beta)
def remove(invoice_id, is_beta=False):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{invoice_id}'
return delete(url, is_beta=is_beta)
<file_sep>/zoopy/models/bank_account.py
from zoopy.utils import get, put, post, delete, get_marketplace_id
from zoopy.models import marketplace
BASE_MODEL_URL = '/bank_accounts'
def get_full_url():
return BASE_MODEL_URL
def list():
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}'
return get(url)
def details(bank_account_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{bank_account_id}'
return get(url)
def update(bank_account_id, params):
url = f'{marketplace.get_full_url()}{get_full_url()}/{bank_account_id}'
return put(end_point=url, data=params)
def remove(bank_account_id):
url = f'{marketplace.get_full_url()}{get_full_url()}/{bank_account_id}'
return delete(end_point=url)<file_sep>/setup.py
import setuptools
with open('README.md', 'r') as fh:
long_description = fh.read()
requires = [i.strip() for i in open('requirements.txt').readlines()]
setuptools.setup(
name='zoopy',
version='1.0.0',
description='Python Library to ZOOP.',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/andersonqueiroz/zoopy',
author='<NAME>, <NAME>',
author_email='<EMAIL>',
license='MIT',
packages=setuptools.find_packages(),
install_requires=requires,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
)<file_sep>/zoopy/models/card.py
from zoopy.utils import get, put, post, delete, get_marketplace_id
from zoopy.models import marketplace
BASE_MODEL_URL = '/cards'
def get_full_url():
return BASE_MODEL_URL
def details(card_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{card_id}'
return get(url)
def attach(params):
url = f'{marketplace.get_full_url()}{get_full_url()}'
return post(end_point=url, data=params)
def update(card_id, params):
url = f'{marketplace.get_full_url()}{get_full_url()}/{card_id}'
return put(end_point=url, data=params)
def remove(card_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{card_id}'
return delete(url)<file_sep>/zoopy/utils/object_to_json.py
import json
from future.utils import integer_types
class ObjectJSON(object):
def to_json(self):
dicionary = json.loads(json.dumps(self, default=lambda o: o.__dict__))
return json.dumps(dicionary)
def process_name_key(dictionary):
if not isinstance(dictionary, dict):
return dictionary
new_dictionary = {}
for key in dictionary:
new_dictionary[key] = process_name_key(dictionary[key])
return new_dictionary
def remove_none(data):
if isinstance(data, dict):
return remove_none_dict(data)
elif isinstance(data, list):
return remove_none_list(data)
return data
def remove_none_dict(obj):
retorno = {}
for chave in obj:
valor = obj[chave]
types = integer_types + (float, complex)
if (valor or isinstance(valor, types)):
if valor:
retorno[chave] = remove_none(valor)
return retorno
def remove_none_list(lista):
resposta = []
for linha in lista:
valor = remove_none(linha)
resposta.append(valor)
return resposta<file_sep>/tests/resources/buyer_data_sample.py
BUYER = {
"first_name":"<NAME>",
"taxpayer_id":"14330453037",
"email":"<EMAIL>",
"address":{
"line1":"Av Americas, 500",
"line2":"Citta América",
"neighborhood":"Barra da Tijuca",
"city":"Rio de Janeiro",
"state":"RJ",
"postal_code":"22845046",
"country_code":"BR"
}
}
<file_sep>/tests/test_transfer.py
import unittest
from tests.base_unittest import BaseTest
from zoopy import transfer, seller
from tests.resources import transfer_data_sample, seller_data_sample
class TestTransfer(BaseTest):
def test01_list_transfers(self):
all_trasnfers = transfer.list_all()
self.assertIsNotNone(all_trasnfers)
if __name__ == '__main__':
unittest.main()<file_sep>/tests/resources/seller_data_sample.py
SELLER_INDIVIDUAL = {
"type": "individual",
"taxpayer_id": "66045919050",
"first_name": "Fulano",
"last_name": "<NAME>",
}
SELLER_BUSINESS = {
"business_name": "Empresa",
"business_description": "vendedora de testes",
"ein": "12750513000107",
"owner": {
"first_name": "Fulano",
"last_name": "<NAME>",
"taxpayer_id": "44410220004"
}
}<file_sep>/tests/test_token.py
import unittest
from zoopy import token, seller
from tests.base_unittest import BaseTest
from tests.resources import token_data_sample, seller_data_sample
class TestToken(BaseTest):
_token_card = None
_token_bank_account = None
def test01_create_token_card(self):
self.__class__._token_card = token.create(token_type='card',
params=token_data_sample.TOKEN_CARD)
self.assertIsNotNone(self.__class__._token_card['id'])
def test02_create_token_bank_account(self):
self.__class__._token_bank_account = token.create(token_type='bank_account',
params=token_data_sample.TOKEN_BANK_ACCOUNT)
self.assertIsNotNone(self.__class__._token_bank_account['id'])
def test03_details_token_card(self):
details = token.details(str(self.__class__._token_card['id']))
self.assertEqual(self.__class__._token_card['id'], details['id'])
# def test04_details_token_bank_account(self):
# details = token.details(str(self.__class__._token_bank_account['id']))
# self.assertEqual(self.__class__._token_bank_account['id'], details['id'])
def test05_attach_bank_account(self):
seller_id = seller.create(params=seller_data_sample.SELLER_INDIVIDUAL,
seller_type='individual').get('id')
attach = token.attach_bank_account(seller_id=seller_id,
token_id=self.__class__._token_bank_account['id'])
seller.remove(seller_id=seller_id)
self.assertEqual(seller_id, attach['customer'])
def test06_attach_card(self):
seller_id = seller.create(params=seller_data_sample.SELLER_INDIVIDUAL,
seller_type='individual').get('id')
attach = token.attach_card(seller_id=seller_id,
token_id=self.__class__._token_card['id'])
seller.remove(seller_id=seller_id)
self.assertEqual(seller_id, attach['customer'])
if __name__ == '__main__':
unittest.main()<file_sep>/tests/resources/transfer_data_sample.py
TRANSFER = {
"amount": 1,
"statement_descriptor": "Zoop transfer",
"description": 'Zoopy test'
}
TRANSFER_P2P = {
"amount": 300,
"description": "Zoopy test transfer",
"transfer_date": "2021-01-01"
}<file_sep>/tests/resources/transaction_data_sample.py
TRANSACTION = {
"amount": 300,
"currency": "BRL",
"description": "venda",
"on_behalf_of": "",
"customer": "",
"payment_type": "boleto"
}<file_sep>/tests/test_buyer.py
import time
import unittest
from zoopy import buyer
from tests.base_unittest import BaseTest
from tests.resources import buyer_data_sample
class TestBuyer(BaseTest):
buyer = None
def test01_list_buyers(self):
all_buyers = buyer.list()
self.assertIsNotNone(all_buyers)
def test02_create_buyer(self):
self.__class__._buyer = buyer.create(params=buyer_data_sample.BUYER)
self.assertIsNotNone(self.__class__._buyer['id'])
def test03_details(self):
details = buyer.details(str(self.__class__._buyer['id']))
self.assertEqual(self.__class__._buyer['id'], details['id'])
def test04_update(self):
updated = buyer.update(buyer_id=str(self.__class__._buyer['id']),
params={'first_name':'<NAME>'})
self.assertEqual('New name', updated['first_name'])
def test05_delete(self):
response = buyer.remove(buyer_id=str(self.__class__._buyer['id']))
self.assertTrue(response["deleted"])
if __name__ == '__main__':
unittest.main()<file_sep>/tests/test_seller.py
import os, hashlib
import unittest
from zoopy import seller
from tests.base_unittest import BaseTest
from tests.resources import seller_data_sample
class TestSeller(BaseTest):
_seller_individual = None
_seller_business = None
_document = None
def test01_list_sellers(self):
all_sellers = seller.list()
self.assertIsNotNone(all_sellers)
def test02_create_seller_individual(self):
self.__class__._seller_individual = seller.create(params=seller_data_sample.SELLER_INDIVIDUAL,
seller_type='individual')
self.assertIsNotNone(self.__class__._seller_individual['id'])
def test03_create_seller_business(self):
self.__class__._seller_business = seller.create(params=seller_data_sample.SELLER_BUSINESS,
seller_type='business')
self.assertIsNotNone(self.__class__._seller_business['id'])
def test04_details_individual(self):
details = seller.details(str(self.__class__._seller_individual['id']))
self.assertEqual(self.__class__._seller_individual['id'], details['id'])
def test05_details_business(self):
details = seller.details(str(self.__class__._seller_business['id']))
self.assertEqual(self.__class__._seller_business['id'], details['id'])
def test06_update_individual(self):
updated = seller.update(seller_id=str(self.__class__._seller_individual['id']),
seller_type='individual', params={'first_name':'<NAME>'})
self.assertEqual('New name', updated['first_name'])
def test07_update_business(self):
updated = seller.update(seller_id=str(self.__class__._seller_business['id']),
seller_type='business', params={'business_name':'New name'})
self.assertEqual('New name', updated['business_name'])
def test08_create_document(self):
test_dir = os.path.dirname(__file__)
document_path = 'resources/document.jpg'
image = open(os.path.join(test_dir, document_path), 'rb')
self.__class__._document = seller.add_documment(seller_id=str(self.__class__._seller_individual['id']),
params={'category':'identificacao'}, files={"file": image})
image.close()
self.assertEqual('identificacao', self.__class__._document['category'])
def test09_get_documents(self):
documents = seller.get_documents(seller_id=str(self.__class__._seller_individual['id']))
self.assertNotEqual(documents['items'], [])
#Retornando vazio na zoop
# def test10_update_document(self):
# document = seller.update_document(document_id=str(self.__class__._document['id']),
# params={'description':'anderson', 'id':str(self.__class__._document['id'])})
# self.assertEqual('anderson', document['category'])
def test10_get_transfers(self):
transfers = seller.transfers(seller_id=str(self.__class__._seller_business['id']))
self.assertEqual(transfers['items'], [])
def test11_delete_inidvidual(self):
response = seller.remove(seller_id=str(self.__class__._seller_individual['id']))
self.assertTrue(response["deleted"])
def test11_delete_business(self):
response = seller.remove(seller_id=str(self.__class__._seller_business['id']))
self.assertTrue(response["deleted"])
if __name__ == '__main__':
unittest.main()<file_sep>/README.md
# Zoopy
Biblioteca desenvolvida para interfacear a comunicação com a API da [Zoop](https://docs.zoop.co/reference#introducao).
## Instalação
Adicionar o requirements.txt da aplicação:
-e git+https://github.com/andersonqueiroz/zoopy.git#egg=zoopy
E executar pip install -r requirements.txt
## Utilização
Para utilizar a biblioteca, deve-se autenticar e depois utilizar os métodos desejados:
from zoopy.utils import authentication_key
from zoopy import buyer
authentication_key(
api_key=config('ZOOP_API_KEY'),
marketplace_id=config('ZOOP_MARKETPLACE_ID')
)
buyers = buyer.list(params=<your data>)
## Desenvolvimento e testes
As dependências de desenvolvimento encontram-se no arquivo requirements-dev.txt
Para testar, deve-se renomear o arquivo **.env.TEMPLATE**, na raiz do projeto, para **.env** e especificar a API key e o ID do marketplace.
A execução dos testes se dá pelo comando:
python -m unittest
Ou especificando o serviço:
python -m unittest tests.test_buyer
<file_sep>/zoopy/models/seller.py
from zoopy.utils import get, put, post, delete, get_marketplace_id
from zoopy.models import marketplace
BASE_MODEL_URL = '/sellers'
DOCUMENTS_URL = '/documents'
INDIVIDUALS_URL = f"{BASE_MODEL_URL}/individuals"
BUSINESSES_URL = f"{BASE_MODEL_URL}/businesses"
def get_full_url(seller_type):
if seller_type == 'business':
return BUSINESSES_URL
return INDIVIDUALS_URL
def list():
marketplace_id = get_marketplace_id()
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}'
return get(url)
def details(seller_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{seller_id}'
return get(url)
def create(params, seller_type):
url = f'{marketplace.get_full_url()}{get_full_url(seller_type)}'
return post(end_point=url, data=params)
def update(seller_id, seller_type, params):
url = f'{marketplace.get_full_url()}{get_full_url(seller_type)}/{seller_id}'
return put(end_point=url, data=params)
def remove(seller_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{seller_id}'
return delete(url)
#Documentos
def add_documment(seller_id, params, files):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{seller_id}{DOCUMENTS_URL}'
return post(end_point=url, data=params, files=files)
def update_document(document_id, params):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}{DOCUMENTS_URL}/{document_id}/'
return put(end_point=url, data=params)
def get_documents(seller_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{seller_id}{DOCUMENTS_URL}'
return get(url)
#Transferencias
def transfers(seller_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{seller_id}/transfers'
return get(url)
#Contas bancárias
def bank_accounts(seller_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{seller_id}/bank_accounts'
return get(url)<file_sep>/zoopy/models/marketplace.py
from zoopy.utils import get, get_marketplace_id
MODEL_BASE_URL = '/marketplaces'
def get_full_url():
return f'{MODEL_BASE_URL}/{get_marketplace_id()}'
def get_details(params):
return get(get_full_url())<file_sep>/zoopy/models/transfer.py
from zoopy.utils import get, put, post, delete
from zoopy.models import marketplace
BASE_MODEL_URL = '/transfers'
BANK_ACCOUNTS_URL = '/bank_accounts/{0}/transfers'
def list_all():
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}'
return get(url)
def details(transfer_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{transfer_id}'
return get(url)
def transactions(transfer_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{transfer_id}/transactions'
return get(url)
def create(bank_account_id, params):
url = f'{marketplace.get_full_url()}{BANK_ACCOUNTS_URL.format(bank_account_id)}'
return post(end_point=url, data=params)
def create_p2p(owner, receiver, params):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{owner}/to/{receiver}'
return post(end_point=url, data=params, is_v2=True)
def delete(transfer_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{transfer_id}'
return delete(end_point=url, data=params)<file_sep>/zoopy/models/subscription.py
from zoopy.utils import get, put, post, delete, get_marketplace_id
from zoopy.models import marketplace
BASE_MODEL_URL = '/subscriptions'
def get_full_url():
return BASE_MODEL_URL
def list(params={}, is_beta=False):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}'
return get(url, params=params, is_beta=is_beta)
def list_by_seller(seller_id, params={}, is_beta=False):
url = f'{marketplace.get_full_url()}/sellers/{seller_id}{BASE_MODEL_URL}'
return get(url, params=params, is_beta=is_beta)
def details(subscription_id, params={}, is_beta=False):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{subscription_id}'
return get(url, params=params, is_beta=is_beta)
def create(params, is_beta=False):
url = f'{marketplace.get_full_url()}{get_full_url()}'
return post(end_point=url, data=params, is_beta=is_beta)
def suspend(subscription_id, is_beta=False):
url = f'{marketplace.get_full_url()}{get_full_url()}/{subscription_id}/suspend'
return post(end_point=url, is_beta=is_beta)
def reactivate(subscription_id, is_beta=False):
url = f'{marketplace.get_full_url()}{get_full_url()}/{subscription_id}/reactivate'
return post(end_point=url, is_beta=is_beta)
def update(subscription_id, params, is_beta=False):
url = f'{marketplace.get_full_url()}{get_full_url()}/{subscription_id}'
return put(end_point=url, data=params, is_beta=is_beta)
def remove(subscription_id, is_beta=False):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{subscription_id}'
return delete(url, is_beta=is_beta)
<file_sep>/tests/test_transaction.py
import unittest
from tests.base_unittest import BaseTest
from zoopy import transaction, buyer, seller
from tests.resources import transaction_data_sample, buyer_data_sample, seller_data_sample
class TestTransaction(BaseTest):
def test01_list_transactions(self):
all_transactions = transaction.list()
self.assertIsNotNone(all_transactions)
def test01_create_detail_update__void_transaction(self):
buyer_id = buyer.create(buyer_data_sample.BUYER).get('id')
transaction_data = transaction_data_sample.TRANSACTION
transaction_data['on_behalf_of'] = "7355b0f00ade4e5d88648c5f8f02681b"
transaction_data['customer'] = buyer_id
new_transaction = transaction.create(params=transaction_data)
self.assertIsNotNone(new_transaction['id'])
details = transaction.details(str(new_transaction['id']))
self.assertEqual(new_transaction['id'], details['id'])
updated = transaction.update(transaction_id=new_transaction['id'],
params={'description':'New description'})
self.assertEqual('New description', updated['description'])
if __name__ == '__main__':
unittest.main()<file_sep>/zoopy/__init__.py
from zoopy.utils import *
from zoopy.models import seller, buyer, transaction, token, bank_account, card, subscription, plan, invoice, transfer
<file_sep>/_main.py
# from zoopy.models import Marketplace, Seller, Owner, Address, Buyer, Transaction
from zoopy.utils import authentication_key
import zoopy
authentication_key(
api_key='TEST_API_KEY',
marketplace_id="MARKETPLACE_ID"
)
results = zoopy.plan.list(is_beta=True)
print(results)
<file_sep>/requirements-dev.txt
python-decouple==3.3.0<file_sep>/tests/base_unittest.py
import unittest
from decouple import config
from zoopy.utils import authentication_key
class BaseTest(unittest.TestCase):
def setUp(self):
authentication_key(
api_key=config('ZOOP_API_KEY'),
marketplace_id=config('ZOOP_MARKETPLACE_ID')
)<file_sep>/zoopy/models/__init__.py
from zoopy.models import seller
from zoopy.models import buyer
from zoopy.models import marketplace
from zoopy.models import transaction
from zoopy.models import token
from zoopy.models import bank_account
from zoopy.models import card
from zoopy.models import plan
from zoopy.models import invoice
from zoopy.models import subscription
from zoopy.models import transfer
# from zoopy.models import split_role
<file_sep>/zoopy/models/buyer.py
from zoopy.utils import get, put, post, delete, get_marketplace_id
from zoopy.models import marketplace
BASE_MODEL_URL = '/buyers'
def get_full_url():
return BASE_MODEL_URL
def list(params={}):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}'
return get(url, params=params)
def details(buyer_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{buyer_id}'
return get(url)
def create(params):
url = f'{marketplace.get_full_url()}{get_full_url()}'
return post(end_point=url, data=params)
def update(buyer_id, params):
url = f'{marketplace.get_full_url()}{get_full_url()}/{buyer_id}'
return put(end_point=url, data=params)
def remove(buyer_id):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{buyer_id}'
return delete(url)
<file_sep>/zoopy/models/plan.py
from zoopy.utils import get, put, post, delete, get_marketplace_id
from zoopy.models import marketplace
BASE_MODEL_URL = '/plans'
def get_full_url():
return BASE_MODEL_URL
def list(params={}, is_beta=False):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}'
return get(url, params=params, is_beta=is_beta)
def details(plan_id, is_beta=False):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{plan_id}'
return get(url, is_beta=is_beta)
def create(params, is_beta=False):
url = f'{marketplace.get_full_url()}{get_full_url()}'
return post(end_point=url, data=params, is_beta=is_beta)
def update(plan_id, params, is_beta=False):
url = f'{marketplace.get_full_url()}{get_full_url()}/{plan_id}'
return put(end_point=url, data=params, is_beta=is_beta)
def remove(plan_id, is_beta=False):
url = f'{marketplace.get_full_url()}{BASE_MODEL_URL}/{plan_id}'
return delete(url, is_beta=is_beta)
<file_sep>/zoopy/utils/handler_request.py
import json
import requests
from requests.auth import HTTPBasicAuth
BASE_URL = 'https://api.zoop.ws/v1'
BASE_URL_V2 = 'https://api.zoop.ws/v2'
BASE_URL_BETA = 'https://api-beta.zoop.ws/v2'
TOKEN = None
MARKETPLACE_ID = None
def get_base_url(is_beta=False, is_v2=False):
if is_v2:
return BASE_URL_V2
return BASE_URL_BETA if is_beta else BASE_URL
def validate_response(zoopy_response):
if zoopy_response.status_code in [200, 201, 204, 304]:
try:
return zoopy_response.json()
except:
return zoopy_response
else:
return error(zoopy_response)
def get_marketplace_id():
return MARKETPLACE_ID
def authentication_key(api_key=None, marketplace_id=None):
global TOKEN
global MARKETPLACE_ID
TOKEN = HTTPBasicAuth(api_key, '')
MARKETPLACE_ID = marketplace_id
def get(end_point, params = {}, is_beta=False, is_v2=False):
base_url = get_base_url(is_beta, is_v2)
url = f'{base_url}{end_point}'
zoopy_response = requests.get(url, params=params, headers=headers(), auth=TOKEN)
return validate_response(zoopy_response)
def post(end_point, data = {}, files = {}, is_beta=False, is_v2=False):
base_url = get_base_url(is_beta, is_v2)
url = f'{base_url}{end_point}'
if files:
zoopy_response = requests.post(url, data=data, files=files, auth=TOKEN)
else:
zoopy_response = requests.post(url, json=data, headers=headers(), auth=TOKEN)
return validate_response(zoopy_response)
def put(end_point, data = {}, files = {}, is_beta=False, is_v2=False):
base_url = get_base_url(is_beta, is_v2)
url = f'{base_url}{end_point}'
if files:
zoopy_response = requests.put(url, data=data, files=files, auth=TOKEN)
else:
zoopy_response = requests.put(url, json=data, headers=headers(), auth=TOKEN)
return validate_response(zoopy_response)
def delete(end_point, is_beta=False, is_v2=False):
base_url = get_base_url(is_beta, is_v2)
url = f'{base_url}{end_point}'
zoopy_response = requests.delete(url, headers=headers(), auth=TOKEN)
return validate_response(zoopy_response)
# def to_json(data):
# if data:
# dicionary = json.loads(json.dumps(data, default=lambda o: o.__dict__))
# return json.dumps(dicionary)
# return {}
def error(zoop_response):
error_response = {
"message":zoop_response.json() if zoop_response.content else 'Zoop API returned an error',
"status_code": zoop_response.status_code,
}
raise Exception(error_response)
def headers():
return {
'accept': 'application/json',
}
<file_sep>/tests/resources/token_data_sample.py
TOKEN_CARD = {
"holder_name":"<NAME>",
"expiration_month":"06",
"expiration_year":"2020",
"card_number":"4389355159877217",
"securiry_code":"137"
}
TOKEN_BANK_ACCOUNT = {
"holder_name":"<NAME>",
"bank_code":"001",
"routing_number":"4745",
"account_number":"2278456",
"taxpayer_id":"66045919050",
"ein":"",
"type":"checking"
}<file_sep>/requirements.txt
future==0.17.1
requests==2.4.3
<file_sep>/zoopy/utils/__init__.py
from .handler_request import * | e4b24fe980b1639a2dc73fe76fe38c1c920b8fc7 | [
"Markdown",
"Python",
"Text"
]
| 33 | Python | andersonqueiroz/zoopy | d43b14aa6814aec132622915f6c54cd0630ad090 | 8f16e6d03974708af0c2726df9bae76ce5f35f00 |
refs/heads/master | <file_sep># Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
RecipeParser::Application.initialize!
| 507e520caa742d3aecb4e959b0c0272e13486c9c | [
"Ruby"
]
| 1 | Ruby | jeanettehuang/recipe-parser | 8178ab630ecbe53c0e1c792472d3437b1b619c6b | b058ea21f78e720e2d26f0dacbda9f6e0910c855 |
refs/heads/master | <file_sep>package main
import (
"net/http"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
var db *gorm.DB
func init() {
//open a db connection
var err error
db, err = gorm.Open("mysql", "root:root@/semantic-browser?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic("failed to connect database")
}
//Migrate the schema
db.AutoMigrate(&favModel{})
}
func main() {
router := gin.Default()
v1 := router.Group("/api/v1/favs")
{
v1.POST("", addFav)
v1.GET("/all", fetchAllFavsFromUser)
v1.PUT("/:id", updateFav)
v1.DELETE("/:id", deleteFav)
}
router.Use(cors.Default())
router.Run()
}
type (
// favModel describes a favModel type
favModel struct {
gorm.Model
Link string `json:"link"`
IDUser string `json:"id-user"`
}
// transformedFav represents a formatted fav
transformedFav struct {
ID uint `json:"id"`
Link string `json:"link"`
IDUser string `json:"id-user"`
}
)
// addFav add a new fav
func addFav(c *gin.Context) {
fav := favModel{IDUser: c.PostForm("id-user"), Link: c.PostForm("link")}
db.Save(&fav)
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.JSON(http.StatusCreated, fav)
}
// fetchAllFavs fetch all favs
func fetchAllFavsFromUser(c *gin.Context) {
var favs []favModel
var _favs []transformedFav
userID := c.Query("id-user")
db.Where("id_user = ?", userID).Find(&favs)
if len(favs) <= 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No favs found!"})
return
}
//transforms the favs for building a good response
for _, item := range favs {
_favs = append(_favs, transformedFav{ID: item.ID, Link: item.Link, IDUser: item.IDUser})
}
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.JSON(http.StatusOK, _favs)
}
// fetchSingleFav fetch a single fav
func fetchSingleFav(c *gin.Context) {
var fav favModel
favID := c.Param("id")
db.First(&fav, favID)
if fav.ID == 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No fav found!"})
return
}
_fav := transformedFav{ID: fav.ID, Link: fav.Link, IDUser: fav.IDUser}
c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "data": _fav})
}
// updateFav update a fav
func updateFav(c *gin.Context) {
var fav favModel
favID := c.Param("id")
db.First(&fav, favID)
if fav.ID == 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No fav found!"})
return
}
fav.Link = c.PostForm("link")
db.Save(&fav)
c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "message": "Fav updated successfully!"})
}
// deleteFav remove a fav
func deleteFav(c *gin.Context) {
var fav favModel
favID := c.Param("id")
db.First(&fav, favID)
if fav.ID == 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "No fav found!"})
return
}
db.Delete(&fav)
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.JSON(http.StatusOK, favID)
}
| f3008d8ca87383bf859ab063c6f3c5b90b0c0915 | [
"Go"
]
| 1 | Go | JesseleDuran/semantic-browser-api | 030acede81c223fd39bf389fbd82189b32f5db30 | 570616460b68da8f79218652336897864bdf6b68 |
refs/heads/master | <file_sep>#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include "markdown.h"
int pipe_fd[2];
pid_t pid;
int argc = 0;
char **args = NULL;
void cmd_add(char *cmd)
{
argc++;
args = reallocarray(args, sizeof(char*), argc+1);
args[argc-1] = strdup(cmd);
args[argc] = NULL;
}
void cmd_start()
{
if(!argc) return;
pipe(pipe_fd);
fflush(stdout);
pid = fork();
if(pid == 0)
{
//child
dup2(pipe_fd[0], 0);
close(pipe_fd[0]);
close(pipe_fd[1]);
execvp(args[0], args);
exit(0);
}
else if(pid > 0)
{
//parent
close(pipe_fd[0]);
} else {
// Fork failed
printf("{Gerror]: %s\n",strerror(errno));
}
}
void cmd_write(char *buf, size_t count)
{
if(argc) {
write(pipe_fd[1], buf, count);
}
else{
printf("%s",buf);
}
}
void cmd_stop()
{
if(!argc) {
printf("\n```\n");
return;
}
close(pipe_fd[1]);
wait(0);
waitpid(pid, NULL, 0);
// Free cmd data
for(int i = 0; i < argc; i++){
free(args[i]);
}
free(args);
args = NULL;
argc = 0;
fflush(stdout);
printf("\n```\n");
}
int main(void)
{
while(yyparse());
return 0;
}
<file_sep>all: README.md
README.md: README.mds src/mds
./src/mds < README.mds > README.md
install:
make install -C src
<file_sep>/* A recursive-descent parser generated by peg 0.1.18 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define YYRULECOUNT 13
#ifndef YY_MALLOC
#define YY_MALLOC(C, N) malloc(N)
#endif
#ifndef YY_REALLOC
#define YY_REALLOC(C, P, N) realloc(P, N)
#endif
#ifndef YY_FREE
#define YY_FREE(C, P) free(P)
#endif
#ifndef YY_LOCAL
#define YY_LOCAL(T) static T
#endif
#ifndef YY_ACTION
#define YY_ACTION(T) static T
#endif
#ifndef YY_RULE
#define YY_RULE(T) static T
#endif
#ifndef YY_PARSE
#define YY_PARSE(T) T
#endif
#ifndef YYPARSE
#define YYPARSE yyparse
#endif
#ifndef YYPARSEFROM
#define YYPARSEFROM yyparsefrom
#endif
#ifndef YYRELEASE
#define YYRELEASE yyrelease
#endif
#ifndef YY_BEGIN
#define YY_BEGIN ( yy->__begin= yy->__pos, 1)
#endif
#ifndef YY_END
#define YY_END ( yy->__end= yy->__pos, 1)
#endif
#ifdef YY_DEBUG
# define yyprintf(args) fprintf args
#else
# define yyprintf(args)
#endif
#ifndef YYSTYPE
#define YYSTYPE int
#endif
#ifndef YY_STACK_SIZE
#define YY_STACK_SIZE 128
#endif
#ifndef YY_BUFFER_SIZE
#define YY_BUFFER_SIZE 1024
#endif
#ifndef YY_PART
typedef struct _yycontext yycontext;
typedef void (*yyaction)(yycontext *yy, char *yytext, int yyleng);
typedef struct _yythunk { int begin, end; yyaction action; struct _yythunk *next; } yythunk;
struct _yycontext {
char *__buf;
int __buflen;
int __pos;
int __limit;
char *__text;
int __textlen;
int __begin;
int __end;
int __textmax;
yythunk *__thunks;
int __thunkslen;
int __thunkpos;
YYSTYPE __;
YYSTYPE *__val;
YYSTYPE *__vals;
int __valslen;
#ifdef YY_CTX_MEMBERS
YY_CTX_MEMBERS
#endif
};
#ifdef YY_CTX_LOCAL
#define YY_CTX_PARAM_ yycontext *yyctx,
#define YY_CTX_PARAM yycontext *yyctx
#define YY_CTX_ARG_ yyctx,
#define YY_CTX_ARG yyctx
#ifndef YY_INPUT
#define YY_INPUT(yy, buf, result, max_size) \
{ \
int yyc= getchar(); \
result= (EOF == yyc) ? 0 : (*(buf)= yyc, 1); \
yyprintf((stderr, "<%c>", yyc)); \
}
#endif
#else
#define YY_CTX_PARAM_
#define YY_CTX_PARAM
#define YY_CTX_ARG_
#define YY_CTX_ARG
yycontext _yyctx= { 0, 0 };
yycontext *yyctx= &_yyctx;
#ifndef YY_INPUT
#define YY_INPUT(buf, result, max_size) \
{ \
int yyc= getchar(); \
result= (EOF == yyc) ? 0 : (*(buf)= yyc, 1); \
yyprintf((stderr, "<%c>", yyc)); \
}
#endif
#endif
YY_LOCAL(int) yyrefill(yycontext *yy)
{
int yyn;
while (yy->__buflen - yy->__pos < 512)
{
yy->__buflen *= 2;
yy->__buf= (char *)YY_REALLOC(yy, yy->__buf, yy->__buflen);
}
#ifdef YY_CTX_LOCAL
YY_INPUT(yy, (yy->__buf + yy->__pos), yyn, (yy->__buflen - yy->__pos));
#else
YY_INPUT((yy->__buf + yy->__pos), yyn, (yy->__buflen - yy->__pos));
#endif
if (!yyn) return 0;
yy->__limit += yyn;
return 1;
}
YY_LOCAL(int) yymatchDot(yycontext *yy)
{
if (yy->__pos >= yy->__limit && !yyrefill(yy)) return 0;
++yy->__pos;
return 1;
}
YY_LOCAL(int) yymatchChar(yycontext *yy, int c)
{
if (yy->__pos >= yy->__limit && !yyrefill(yy)) return 0;
if ((unsigned char)yy->__buf[yy->__pos] == c)
{
++yy->__pos;
yyprintf((stderr, " ok yymatchChar(yy, %c) @ %s\n", c, yy->__buf+yy->__pos));
return 1;
}
yyprintf((stderr, " fail yymatchChar(yy, %c) @ %s\n", c, yy->__buf+yy->__pos));
return 0;
}
YY_LOCAL(int) yymatchString(yycontext *yy, const char *s)
{
int yysav= yy->__pos;
while (*s)
{
if (yy->__pos >= yy->__limit && !yyrefill(yy)) return 0;
if (yy->__buf[yy->__pos] != *s)
{
yy->__pos= yysav;
return 0;
}
++s;
++yy->__pos;
}
return 1;
}
YY_LOCAL(int) yymatchClass(yycontext *yy, unsigned char *bits)
{
int c;
if (yy->__pos >= yy->__limit && !yyrefill(yy)) return 0;
c= (unsigned char)yy->__buf[yy->__pos];
if (bits[c >> 3] & (1 << (c & 7)))
{
++yy->__pos;
yyprintf((stderr, " ok yymatchClass @ %s\n", yy->__buf+yy->__pos));
return 1;
}
yyprintf((stderr, " fail yymatchClass @ %s\n", yy->__buf+yy->__pos));
return 0;
}
YY_LOCAL(void) yyDo(yycontext *yy, yyaction action, int begin, int end)
{
while (yy->__thunkpos >= yy->__thunkslen)
{
yy->__thunkslen *= 2;
yy->__thunks= (yythunk *)YY_REALLOC(yy, yy->__thunks, sizeof(yythunk) * yy->__thunkslen);
}
yy->__thunks[yy->__thunkpos].begin= begin;
yy->__thunks[yy->__thunkpos].end= end;
yy->__thunks[yy->__thunkpos].action= action;
++yy->__thunkpos;
}
YY_LOCAL(int) yyText(yycontext *yy, int begin, int end)
{
int yyleng= end - begin;
if (yyleng <= 0)
yyleng= 0;
else
{
while (yy->__textlen < (yyleng + 1))
{
yy->__textlen *= 2;
yy->__text= (char *)YY_REALLOC(yy, yy->__text, yy->__textlen);
}
memcpy(yy->__text, yy->__buf + begin, yyleng);
}
yy->__text[yyleng]= '\0';
return yyleng;
}
YY_LOCAL(void) yyDone(yycontext *yy)
{
int pos;
for (pos= 0; pos < yy->__thunkpos; ++pos)
{
yythunk *thunk= &yy->__thunks[pos];
int yyleng= thunk->end ? yyText(yy, thunk->begin, thunk->end) : thunk->begin;
yyprintf((stderr, "DO [%d] %p %s\n", pos, thunk->action, yy->__text));
thunk->action(yy, yy->__text, yyleng);
}
yy->__thunkpos= 0;
}
YY_LOCAL(void) yyCommit(yycontext *yy)
{
if ((yy->__limit -= yy->__pos))
{
memmove(yy->__buf, yy->__buf + yy->__pos, yy->__limit);
}
yy->__begin -= yy->__pos;
yy->__end -= yy->__pos;
yy->__pos= yy->__thunkpos= 0;
}
YY_LOCAL(int) yyAccept(yycontext *yy, int tp0)
{
if (tp0)
{
fprintf(stderr, "accept denied at %d\n", tp0);
return 0;
}
else
{
yyDone(yy);
yyCommit(yy);
}
return 1;
}
YY_LOCAL(void) yyPush(yycontext *yy, char *text, int count)
{
yy->__val += count;
while (yy->__valslen <= yy->__val - yy->__vals)
{
long offset= yy->__val - yy->__vals;
yy->__valslen *= 2;
yy->__vals= (YYSTYPE *)YY_REALLOC(yy, yy->__vals, sizeof(YYSTYPE) * yy->__valslen);
yy->__val= yy->__vals + offset;
}
}
YY_LOCAL(void) yyPop(yycontext *yy, char *text, int count) { yy->__val -= count; }
YY_LOCAL(void) yySet(yycontext *yy, char *text, int count) { yy->__val[count]= yy->__; }
#endif /* YY_PART */
#define YYACCEPT yyAccept(yy, yythunkpos0)
YY_RULE(int) yy_arg(yycontext *yy); /* 13 */
YY_RULE(int) yy_command(yycontext *yy); /* 12 */
YY_RULE(int) yy_block_label(yycontext *yy); /* 11 */
YY_RULE(int) yy_white_space(yycontext *yy); /* 10 */
YY_RULE(int) yy_block_encap(yycontext *yy); /* 9 */
YY_RULE(int) yy_block_tail(yycontext *yy); /* 8 */
YY_RULE(int) yy_block_content(yycontext *yy); /* 7 */
YY_RULE(int) yy_block_head(yycontext *yy); /* 6 */
YY_RULE(int) yy_end_of_line(yycontext *yy); /* 5 */
YY_RULE(int) yy_end_of_file(yycontext *yy); /* 4 */
YY_RULE(int) yy_block(yycontext *yy); /* 3 */
YY_RULE(int) yy_filler(yycontext *yy); /* 2 */
YY_RULE(int) yy_document(yycontext *yy); /* 1 */
YY_ACTION(void) yy_1_block_label(yycontext *yy, char *yytext, int yyleng)
{
#define __ yy->__
#define yypos yy->__pos
#define yythunkpos yy->__thunkpos
yyprintf((stderr, "do yy_1_block_label\n"));
{
#line 0
printf("\n```%s\n",yytext) ;
}
#undef yythunkpos
#undef yypos
#undef yy
}
YY_ACTION(void) yy_1_arg(yycontext *yy, char *yytext, int yyleng)
{
#define __ yy->__
#define yypos yy->__pos
#define yythunkpos yy->__thunkpos
yyprintf((stderr, "do yy_1_arg\n"));
{
#line 0
cmd_add(yytext) ;
}
#undef yythunkpos
#undef yypos
#undef yy
}
YY_ACTION(void) yy_1_block_tail(yycontext *yy, char *yytext, int yyleng)
{
#define __ yy->__
#define yypos yy->__pos
#define yythunkpos yy->__thunkpos
yyprintf((stderr, "do yy_1_block_tail\n"));
{
#line 0
cmd_stop() ;
}
#undef yythunkpos
#undef yypos
#undef yy
}
YY_ACTION(void) yy_1_block_head(yycontext *yy, char *yytext, int yyleng)
{
#define __ yy->__
#define yypos yy->__pos
#define yythunkpos yy->__thunkpos
yyprintf((stderr, "do yy_1_block_head\n"));
{
#line 0
cmd_start() ;
}
#undef yythunkpos
#undef yypos
#undef yy
}
YY_ACTION(void) yy_1_block_content(yycontext *yy, char *yytext, int yyleng)
{
#define __ yy->__
#define yypos yy->__pos
#define yythunkpos yy->__thunkpos
yyprintf((stderr, "do yy_1_block_content\n"));
{
#line 0
cmd_write(yytext, yyleng) ;
}
#undef yythunkpos
#undef yypos
#undef yy
}
YY_ACTION(void) yy_1_filler(yycontext *yy, char *yytext, int yyleng)
{
#define __ yy->__
#define yypos yy->__pos
#define yythunkpos yy->__thunkpos
yyprintf((stderr, "do yy_1_filler\n"));
{
#line 0
printf(yytext) ;
}
#undef yythunkpos
#undef yypos
#undef yy
}
YY_RULE(int) yy_arg(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "arg")); yyText(yy, yy->__begin, yy->__end); {
#define yytext yy->__text
#define yyleng yy->__textlen
if (!(YY_BEGIN)) goto l1;
#undef yytext
#undef yyleng
}
{ int yypos4= yy->__pos, yythunkpos4= yy->__thunkpos;
{ int yypos5= yy->__pos, yythunkpos5= yy->__thunkpos; if (!yymatchChar(yy, '"')) goto l6; goto l5;
l6:; yy->__pos= yypos5; yy->__thunkpos= yythunkpos5; if (!yy_white_space(yy)) goto l4;
}
l5:; goto l1;
l4:; yy->__pos= yypos4; yy->__thunkpos= yythunkpos4;
} if (!yymatchDot(yy)) goto l1;
l2:;
{ int yypos3= yy->__pos, yythunkpos3= yy->__thunkpos;
{ int yypos7= yy->__pos, yythunkpos7= yy->__thunkpos;
{ int yypos8= yy->__pos, yythunkpos8= yy->__thunkpos; if (!yymatchChar(yy, '"')) goto l9; goto l8;
l9:; yy->__pos= yypos8; yy->__thunkpos= yythunkpos8; if (!yy_white_space(yy)) goto l7;
}
l8:; goto l3;
l7:; yy->__pos= yypos7; yy->__thunkpos= yythunkpos7;
} if (!yymatchDot(yy)) goto l3; goto l2;
l3:; yy->__pos= yypos3; yy->__thunkpos= yythunkpos3;
} yyText(yy, yy->__begin, yy->__end); {
#define yytext yy->__text
#define yyleng yy->__textlen
if (!(YY_END)) goto l1;
#undef yytext
#undef yyleng
} yyDo(yy, yy_1_arg, yy->__begin, yy->__end);
yyprintf((stderr, " ok %s @ %s\n", "arg", yy->__buf+yy->__pos));
return 1;
l1:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "arg", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_command(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "command")); if (!yymatchClass(yy, (unsigned char *)"\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000")) goto l10;
{ int yypos13= yy->__pos, yythunkpos13= yy->__thunkpos; if (!yy_arg(yy)) goto l14; goto l13;
l14:; yy->__pos= yypos13; yy->__thunkpos= yythunkpos13; if (!yy_white_space(yy)) goto l10;
}
l13:;
l11:;
{ int yypos12= yy->__pos, yythunkpos12= yy->__thunkpos;
{ int yypos15= yy->__pos, yythunkpos15= yy->__thunkpos; if (!yy_arg(yy)) goto l16; goto l15;
l16:; yy->__pos= yypos15; yy->__thunkpos= yythunkpos15; if (!yy_white_space(yy)) goto l12;
}
l15:; goto l11;
l12:; yy->__pos= yypos12; yy->__thunkpos= yythunkpos12;
} if (!yymatchClass(yy, (unsigned char *)"\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000")) goto l10;
yyprintf((stderr, " ok %s @ %s\n", "command", yy->__buf+yy->__pos));
return 1;
l10:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "command", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_block_label(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "block_label")); yyText(yy, yy->__begin, yy->__end); {
#define yytext yy->__text
#define yyleng yy->__textlen
if (!(YY_BEGIN)) goto l17;
#undef yytext
#undef yyleng
}
l18:;
{ int yypos19= yy->__pos, yythunkpos19= yy->__thunkpos;
{ int yypos20= yy->__pos, yythunkpos20= yy->__thunkpos;
{ int yypos21= yy->__pos, yythunkpos21= yy->__thunkpos; if (!yy_white_space(yy)) goto l22; goto l21;
l22:; yy->__pos= yypos21; yy->__thunkpos= yythunkpos21; if (!yy_end_of_line(yy)) goto l20;
}
l21:; goto l19;
l20:; yy->__pos= yypos20; yy->__thunkpos= yythunkpos20;
} if (!yymatchDot(yy)) goto l19; goto l18;
l19:; yy->__pos= yypos19; yy->__thunkpos= yythunkpos19;
} yyText(yy, yy->__begin, yy->__end); {
#define yytext yy->__text
#define yyleng yy->__textlen
if (!(YY_END)) goto l17;
#undef yytext
#undef yyleng
} yyDo(yy, yy_1_block_label, yy->__begin, yy->__end);
yyprintf((stderr, " ok %s @ %s\n", "block_label", yy->__buf+yy->__pos));
return 1;
l17:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "block_label", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_white_space(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "white_space"));
{ int yypos24= yy->__pos, yythunkpos24= yy->__thunkpos; if (!yymatchChar(yy, ' ')) goto l25; goto l24;
l25:; yy->__pos= yypos24; yy->__thunkpos= yythunkpos24; if (!yymatchChar(yy, '\t')) goto l26; goto l24;
l26:; yy->__pos= yypos24; yy->__thunkpos= yythunkpos24; if (!yy_end_of_file(yy)) goto l23;
}
l24:;
yyprintf((stderr, " ok %s @ %s\n", "white_space", yy->__buf+yy->__pos));
return 1;
l23:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "white_space", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_block_encap(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "block_encap")); if (!yymatchString(yy, "```")) goto l27;
yyprintf((stderr, " ok %s @ %s\n", "block_encap", yy->__buf+yy->__pos));
return 1;
l27:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "block_encap", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_block_tail(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "block_tail")); if (!yy_end_of_line(yy)) goto l28; if (!yy_block_encap(yy)) goto l28; if (!yy_end_of_line(yy)) goto l28; yyDo(yy, yy_1_block_tail, yy->__begin, yy->__end);
yyprintf((stderr, " ok %s @ %s\n", "block_tail", yy->__buf+yy->__pos));
return 1;
l28:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "block_tail", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_block_content(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "block_content")); yyText(yy, yy->__begin, yy->__end); {
#define yytext yy->__text
#define yyleng yy->__textlen
if (!(YY_BEGIN)) goto l29;
#undef yytext
#undef yyleng
}
{ int yypos32= yy->__pos, yythunkpos32= yy->__thunkpos; if (!yy_block_tail(yy)) goto l32; goto l29;
l32:; yy->__pos= yypos32; yy->__thunkpos= yythunkpos32;
} if (!yymatchDot(yy)) goto l29;
l30:;
{ int yypos31= yy->__pos, yythunkpos31= yy->__thunkpos;
{ int yypos33= yy->__pos, yythunkpos33= yy->__thunkpos; if (!yy_block_tail(yy)) goto l33; goto l31;
l33:; yy->__pos= yypos33; yy->__thunkpos= yythunkpos33;
} if (!yymatchDot(yy)) goto l31; goto l30;
l31:; yy->__pos= yypos31; yy->__thunkpos= yythunkpos31;
} yyText(yy, yy->__begin, yy->__end); {
#define yytext yy->__text
#define yyleng yy->__textlen
if (!(YY_END)) goto l29;
#undef yytext
#undef yyleng
} yyDo(yy, yy_1_block_content, yy->__begin, yy->__end);
yyprintf((stderr, " ok %s @ %s\n", "block_content", yy->__buf+yy->__pos));
return 1;
l29:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "block_content", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_block_head(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "block_head")); yyText(yy, yy->__begin, yy->__end); {
#define yytext yy->__text
#define yyleng yy->__textlen
if (!(YY_BEGIN)) goto l34;
#undef yytext
#undef yyleng
} if (!yy_end_of_line(yy)) goto l34; if (!yy_block_encap(yy)) goto l34;
l35:;
{ int yypos36= yy->__pos, yythunkpos36= yy->__thunkpos; if (!yy_white_space(yy)) goto l36; goto l35;
l36:; yy->__pos= yypos36; yy->__thunkpos= yythunkpos36;
} if (!yy_block_label(yy)) goto l34;
l37:;
{ int yypos38= yy->__pos, yythunkpos38= yy->__thunkpos; if (!yy_white_space(yy)) goto l38; goto l37;
l38:; yy->__pos= yypos38; yy->__thunkpos= yythunkpos38;
}
{ int yypos39= yy->__pos, yythunkpos39= yy->__thunkpos; if (!yy_command(yy)) goto l39; goto l40;
l39:; yy->__pos= yypos39; yy->__thunkpos= yythunkpos39;
}
l40:;
l41:;
{ int yypos42= yy->__pos, yythunkpos42= yy->__thunkpos; if (!yy_white_space(yy)) goto l42; goto l41;
l42:; yy->__pos= yypos42; yy->__thunkpos= yythunkpos42;
} if (!yy_end_of_line(yy)) goto l34; yyDo(yy, yy_1_block_head, yy->__begin, yy->__end);
yyprintf((stderr, " ok %s @ %s\n", "block_head", yy->__buf+yy->__pos));
return 1;
l34:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "block_head", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_end_of_line(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "end_of_line"));
{ int yypos44= yy->__pos, yythunkpos44= yy->__thunkpos; if (!yymatchString(yy, "\r\n")) goto l45; goto l44;
l45:; yy->__pos= yypos44; yy->__thunkpos= yythunkpos44; if (!yymatchChar(yy, '\n')) goto l46; goto l44;
l46:; yy->__pos= yypos44; yy->__thunkpos= yythunkpos44; if (!yymatchChar(yy, '\r')) goto l43;
}
l44:;
yyprintf((stderr, " ok %s @ %s\n", "end_of_line", yy->__buf+yy->__pos));
return 1;
l43:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "end_of_line", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_end_of_file(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "end_of_file"));
{ int yypos48= yy->__pos, yythunkpos48= yy->__thunkpos; if (!yymatchDot(yy)) goto l48; goto l47;
l48:; yy->__pos= yypos48; yy->__thunkpos= yythunkpos48;
}
yyprintf((stderr, " ok %s @ %s\n", "end_of_file", yy->__buf+yy->__pos));
return 1;
l47:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "end_of_file", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_block(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "block")); if (!yy_block_head(yy)) goto l49; if (!yy_block_content(yy)) goto l49; if (!yy_block_tail(yy)) goto l49;
yyprintf((stderr, " ok %s @ %s\n", "block", yy->__buf+yy->__pos));
return 1;
l49:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "block", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_filler(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "filler")); yyText(yy, yy->__begin, yy->__end); {
#define yytext yy->__text
#define yyleng yy->__textlen
if (!(YY_BEGIN)) goto l50;
#undef yytext
#undef yyleng
}
{ int yypos53= yy->__pos, yythunkpos53= yy->__thunkpos; if (!yy_end_of_line(yy)) goto l53; if (!yymatchString(yy, "```")) goto l53; goto l50;
l53:; yy->__pos= yypos53; yy->__thunkpos= yythunkpos53;
} if (!yymatchDot(yy)) goto l50;
l51:;
{ int yypos52= yy->__pos, yythunkpos52= yy->__thunkpos;
{ int yypos54= yy->__pos, yythunkpos54= yy->__thunkpos; if (!yy_end_of_line(yy)) goto l54; if (!yymatchString(yy, "```")) goto l54; goto l52;
l54:; yy->__pos= yypos54; yy->__thunkpos= yythunkpos54;
} if (!yymatchDot(yy)) goto l52; goto l51;
l52:; yy->__pos= yypos52; yy->__thunkpos= yythunkpos52;
} yyText(yy, yy->__begin, yy->__end); {
#define yytext yy->__text
#define yyleng yy->__textlen
if (!(YY_END)) goto l50;
#undef yytext
#undef yyleng
} yyDo(yy, yy_1_filler, yy->__begin, yy->__end);
yyprintf((stderr, " ok %s @ %s\n", "filler", yy->__buf+yy->__pos));
return 1;
l50:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "filler", yy->__buf+yy->__pos));
return 0;
}
YY_RULE(int) yy_document(yycontext *yy)
{ int yypos0= yy->__pos, yythunkpos0= yy->__thunkpos;
yyprintf((stderr, "%s\n", "document"));
{ int yypos58= yy->__pos, yythunkpos58= yy->__thunkpos; if (!yy_filler(yy)) goto l59; goto l58;
l59:; yy->__pos= yypos58; yy->__thunkpos= yythunkpos58; if (!yy_block(yy)) goto l55;
}
l58:;
l56:;
{ int yypos57= yy->__pos, yythunkpos57= yy->__thunkpos;
{ int yypos60= yy->__pos, yythunkpos60= yy->__thunkpos; if (!yy_filler(yy)) goto l61; goto l60;
l61:; yy->__pos= yypos60; yy->__thunkpos= yythunkpos60; if (!yy_block(yy)) goto l57;
}
l60:; goto l56;
l57:; yy->__pos= yypos57; yy->__thunkpos= yythunkpos57;
} if (!yy_end_of_file(yy)) goto l55;
yyprintf((stderr, " ok %s @ %s\n", "document", yy->__buf+yy->__pos));
return 1;
l55:; yy->__pos= yypos0; yy->__thunkpos= yythunkpos0;
yyprintf((stderr, " fail %s @ %s\n", "document", yy->__buf+yy->__pos));
return 0;
}
#ifndef YY_PART
typedef int (*yyrule)(yycontext *yy);
YY_PARSE(int) YYPARSEFROM(YY_CTX_PARAM_ yyrule yystart)
{
int yyok;
if (!yyctx->__buflen)
{
yyctx->__buflen= YY_BUFFER_SIZE;
yyctx->__buf= (char *)YY_MALLOC(yyctx, yyctx->__buflen);
yyctx->__textlen= YY_BUFFER_SIZE;
yyctx->__text= (char *)YY_MALLOC(yyctx, yyctx->__textlen);
yyctx->__thunkslen= YY_STACK_SIZE;
yyctx->__thunks= (yythunk *)YY_MALLOC(yyctx, sizeof(yythunk) * yyctx->__thunkslen);
yyctx->__valslen= YY_STACK_SIZE;
yyctx->__vals= (YYSTYPE *)YY_MALLOC(yyctx, sizeof(YYSTYPE) * yyctx->__valslen);
yyctx->__begin= yyctx->__end= yyctx->__pos= yyctx->__limit= yyctx->__thunkpos= 0;
}
yyctx->__begin= yyctx->__end= yyctx->__pos;
yyctx->__thunkpos= 0;
yyctx->__val= yyctx->__vals;
yyok= yystart(yyctx);
if (yyok) yyDone(yyctx);
yyCommit(yyctx);
return yyok;
}
YY_PARSE(int) YYPARSE(YY_CTX_PARAM)
{
return YYPARSEFROM(YY_CTX_ARG_ yy_document);
}
YY_PARSE(yycontext *) YYRELEASE(yycontext *yyctx)
{
if (yyctx->__buflen)
{
yyctx->__buflen= 0;
YY_FREE(yyctx, yyctx->__buf);
YY_FREE(yyctx, yyctx->__text);
YY_FREE(yyctx, yyctx->__thunks);
YY_FREE(yyctx, yyctx->__vals);
}
return yyctx;
}
#endif
<file_sep>ifeq ($(PREFIX),)
PREFIX := /usr/local
endif
all: mds
build: mds
install: mds
install -d $(PREFIX)/bin
install -m 777 mds $(PREFIX)/bin
mds: mds.c markdown.h
gcc -g mds.c -o mds
markdown.h: markdown.peg
peg -v markdown.peg > markdown.h
clean:
rm markdown.h
rm mds
<file_sep># Markdown shell v 0.1.0
## Exsample
```ls
exsample
makefile
README.md
README.mds
src
test.md
tests
t.md
```
## Issues and features needed for 1.0.0
- [ ] escape commands (\")
- [ ] non block commands somthing like "version { cat version }"
- [ ] Remove need to supply block label
- [ ] Better error handeling
- [ ] .md file should be identical if parsing failes
- [ ] Add some kind of copyleft license
<file_sep>This is a c program
```asm "gcc -xc -S -o - -"
int main(void)
{
printf("hello world!");
}
```
This is in betwene
```c
int main(void)
{
printf("hello world!");
}
```
<file_sep>EXSAMPLE_MDS := $(wildcard *.mds)
EXSAMPLE_MD := $(patsubst %.mds,%.md, $(EXSAMPLE_MDS))
all: $(EXSAMPLE_MD)
%.md: %.mds ../src/mds
../src/mds < $< >$@
clean:
rm EXSAMPLE_MD
| 1596ce581ebcc8159cda343bfb4b9abc101a3ef2 | [
"Markdown",
"C",
"Makefile"
]
| 7 | C | Miniwoffer/mds | 65e90c76994bf7d90df094313d0cadae5ab2550d | c8b3abbb1e42e6dbd48b8ae2363e289f18cbdf84 |
refs/heads/master | <repo_name>mohammedfarhan442/cpgms<file_sep>/geometrical_areas.c
#include <stdio.h>
#include<math.h>
int main()
{
int Select;
float side, base, length, breadth, height, area, radius;
printf("-------------------------\n");
printf(" 1 --> Area of Circle\n");
printf(" 2 --> Area of Rectangle\n");
printf(" 3 --> Area of Triangle\n");
printf(" 4 --> Area of Square\n");
printf(" 5 --> Area of Cube\n");
printf(" 6 --> Area of cuboid\n");
printf("-------------------------\n");
printf("Select the number to find area\n");
scanf("%d", &Select);
switch(Select)
{
case 1: // to find area of ciecle.
printf("Enter the radius\n");
scanf("%f", &radius);
area = 3.142 * radius * radius;
printf("Area of a circle = %f cm\n", area);
break;
case 2: // to find area of rectangle.
printf("Enter the breadth and length\n");
scanf("%f %f", &breadth, &length);
area = breadth * length;
printf("Area of a Reactangle = %f cm\n", area);
break;
case 3: //to find area of triangle.
printf("Enter the base and height\n");
scanf("%f %f", &base, &height);
area = 0.5 * base * height;
printf("Area of a Triangle = %f cm\n", area);
break;
case 4: //to find area of Square.
printf("Enter the side\n");
scanf("%f", &side);
area = side * side;
printf("Area of a Square=%f cm\n", area);
break;
case 5: //to find area of cube.
printf("Enter the sides of Cube:\n");
scanf("%f", &side);
area= 6*side*side;
printf("Area of Cube:%f cm \n", area);
break;
case 6: // to area of cuboid.
printf("Enter the Length, Breadth and Height of Cuboid: \n");
scanf("%f%f%f", &length, &breadth, &height);
area= length*breadth*height;
printf("Area of Cuboid: %f cm \n", area);
break;
default:
printf("Chosice not found!!\n");
break;
}
}
<file_sep>/A1. Write a program to find Area and Circumference of Circle. - Copy.cpp
#include<stdio.h>
int main()
{
int rad;
float PI = 3.14, area, ci;
printf("\nEnter radius of circle: ");
scanf("%d", &rad);
area = PI * rad * rad;
printf("\nArea of circle : %f cm", area);
ci = 2 * PI * rad;
printf("\nCircumference : %f cm ", ci);
return (0);
}
<file_sep>/Self Project of moudel 1.cpp
#include <stdio.h>
#include<math.h>
int main()
{
int Select;
float side, base, length, breadth, height, area, radius;
printf("---------Gemetrical Calculator----------------\n");
printf(" 1 --> Area of Circle\n");
printf(" 2 --> Area of Rectangle\n");
printf(" 3 --> Area of Triangle\n");
printf(" 4 --> Area of Square\n");
printf(" 5 --> Area of Cube\n");
printf(" 6 --> Area of cuboid\n");
printf("-------------------------\n");
printf("Select the number to find area\n");
scanf("%d", &Select);
switch(Select)
{
case 1: // to find area of circle.
printf("Enter the radius\n");
scanf("%f", &radius);
area = 3.142 * radius * radius;
printf("Area of a circle = %f cm\n", area);
break;
case 2: // to find area of rectangle.
printf("Enter the breadth and length\n");
scanf("%f %f", &breadth, &length);
area = breadth * length;
printf("Area of a Rectangle = %f cm\n", area);
break;
case 3: //to find area of triangle.
printf("Enter the base and height\n");
scanf("%f %f", &base, &height);
area = 0.5 * base * height;
printf("Area of a Triangle = %f cm\n", area);
break;
case 4: //to find area of Square.
printf("Enter the side\n");
scanf("%f", &side);
area = side * side;
printf("Area of a Square=%f cm\n", area);
break;
case 5: //to find area of cube.
printf("Enter the sides of Cube:\n");
scanf("%f", &side);
area= 6*side*side;
printf("Area of Cube:%f cm \n", area);
break;
case 6: // to area of cuboid.
printf("Enter the Length, Breadth and Height of Cuboid: \n");
scanf("%f%f%f", &length, &breadth, &height);
area= length*breadth*height;
printf("Area of Cuboid: %f cm \n", area);
break;
default:
printf("Chosice not found!!\n");
break;
}
}
<file_sep>/E2. Write a program to check whether the triangle is valid or not when 3 sides given. - Copy.cpp
#include <stdio.h>
int main()
{
int side1, side2, side3;
printf("Enter three sides of triangle: \n");
scanf("%d%d%d", &side1, &side2, &side3);
if((side1 + side2) > side3)
{
if((side2 + side3) > side1)
{
if((side1 + side3) > side2)
{
/*
* If side1 + side2 > side3 and
* side2 + side3 > side1 and
* side1 + side3 > side2 then
* the triangle is valid.
*/
printf("Triangle is valid. \n");
}
else
{
printf("Triangle is not valid. \n");
}
}
else
{
printf("Triangle is not valid. \n");
}
}
else
{
printf("Triangle is not valid. \n");
}
return 0;
}
<file_sep>/P1. EMI calculator - Copy.cpp
#include <stdio.h>
#include <math.h>
int main()
{
float principal, rate, time, emi;
printf("Enter principal: \n");
scanf("%f",&principal);
printf("Enter the rate:\n");
scanf("%f", &rate);
printf("Enter the Time duration: \n");
scanf("%f", &time);
rate=rate/(12*100); /*one month interest*/
time=time*12; /*one month period*/
emi= (principal*rate*pow(1+rate,time))/(pow(1+rate,time)-1);
printf("Monthly EMI is= %f\n",emi);
return 0;
}
<file_sep>/L2. Write a program to add first seven terms of the following series using a for loop 1 1! + 2 2! + 3 3! + ….. .cpp
#include<stdio.h>
main()
{
float result, temp_calc, num, temp, factorial;
result=0;
for (num=1; num<=7; num++)
{
for (temp=1, factorial=1; temp<=num; temp++)
{
factorial = factorial*temp;
temp_calc = (num/factorial);
}
result=result+temp_calc;
}
printf("(1/1!) + (2/2!) + (3/3!) + (4/4!) + (5/5!) + (6/6!) + (7/7!) = %f", result);
}
<file_sep>/N2. pyramid pattern Asterisk.cpp
#include<stdio.h>
int main()
{
int line, row, col, b;
printf("Enter number of lines:\n");
scanf("%d", &line);
printf("The Pattern is:\n");
for (row=0; row<=line; row++)
{
for(b=1; b<=line-row+1; b++)
printf(" ");
for (col=1; col<=row; col++)
printf(" *");
printf(" \n ");
}
}
<file_sep>/J2. Write a program to find the given number is Armstrong number or not. - Copy.cpp
#include <math.h>
#include <stdio.h>
int main()
{
int num, originalNum, remainder, n = 0, result = 0, power;
printf("Enter an integer: ");
scanf("%d", &num);
originalNum = num;
while (originalNum != 0)
{
originalNum /= 10;
++n;
}
originalNum = num;
while (originalNum != 0)
{
remainder = originalNum % 10;
// pow() returns a double value
// round() return the equivalent int
power = round(pow(remainder, n));
result += power;
originalNum /= 10;
}
if (result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
return 0;
}
<file_sep>/C1. Write a program to perform all Arithmetic operations - Copy.cpp
#include <stdio.h>
#include<math.h>
int main()
{
int Select;
int a,b,c;
int sum, sub, multi, mode;
float div;
printf("X-X-X-X-X-X-X-X-X-X-X-X-X-X-X-X-X-X-X-X \n");
printf("Select the Arithmetic Operations for Calculations: \n");
printf(" 1.------> Addition \n");
printf(" 2------> Subtraction \n");
printf(" 3------> Division \n");
printf(" 4------> Multiplication \n");
printf(" 5------> Modules \n");
printf("X-X-X-X-X-X-X-X-X-X-X-X-X-X-X-X-X-X-X-X \n");
scanf("%d", &Select);
switch(Select)
{
case 1:
printf("Enter three numbers for Addition \n");
scanf("%d%d%d", &a,&b,&c);
sum= a+b+c;
printf("Addition for three numbers are equls to: %d \n", sum);
break;
case 2:
printf("Enter three numbers for Subtraction \n");
scanf("%d%d%d", &a,&b,&c);
sub= a-b-c;
printf("Subtraction of three numbers are equals to: %d \n", sub);
break;
case 3:
printf("Enter three numbers for Division \n");
scanf("%d%d%d", &a,&b,&c);
div= a/b/c;
printf("Division of three numbers are equals to: %d \n", div);
break;
case 4:
printf("Enter three numbers for Multiplication \n");
scanf("%d%d%d", &a,&b,&c);
multi=a*b*c;
printf("Multiplication of three numbers are equals to:%d \n", multi);
break;
case 5:
printf("Enter three numbers for Modules \n");
scanf("%d%d%d", &a,&b,&c);
mode= a%b%c;
printf("Modules for three numbers are equals to: %d \n", mode);
break;
default:
printf("Selection not found!!\n");
break;
}
}
<file_sep>/O1. If a five-digit number is input through the keyboard, write a program to print a new number by adding one to each of its digits. For example if the number that is input is 12391 then the output should - Copy.cpp
#include<stdio.h>
int main()
{
int num, sum, i, number, count=0, n=1;
printf("Enter Digits: \n");
scanf("%d", &num);
number = num;
//get the counter till then we have to run the loop
while(number!=0)
{
number = number/10;
count = count + 1;
}
for(i=1;i<count;i++)
{
n = n * 10; //n = 10
n = n + 1; //n = 11
}
sum = num + n;
printf("Output: %d", sum);
return 0;
}
<file_sep>/C2. Write a program to find the Greatest of 3 number. - Copy.cpp
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter the three numbers\n");
scanf("%d %d %d", &a, &b, &c);
printf("a = %d\tb = %d\tc = %d\n", a, b, c);
if (a > b)
{
if (a > c)
{
printf("a is the greatest among three \n");
}
else
{
printf("c is the greatest among three \n");
}
}
else if (b > c)
printf("b is the greatest among three \n");
else
printf("c is the greatest among three \n");
}
<file_sep>/D1. Write a program to perform all Relation operations. - Copy.cpp
#include <stdio.h>
int main()
{
int a = 10, b = 4;
if (a > b)
printf("a is greater than b\n");
else
printf("a is less than or equal to b\n");
if (a >= b)
printf("a is greater than or equal to b\n");
else
printf("a is lesser than b\n");
if (a < b)
printf("a is less than b\n");
else
printf("a is greater than or equal to b\n");
if (a <= b)
printf("a is lesser than or equal to b\n");
else
printf("a is greater than b\n");
if (a == b)
printf("a is equal to b\n");
else
printf("a and b are not equal\n");
if (a != b)
printf("a is not equal to b\n");
else
printf("a is equal b\n");
return 0;
}
<file_sep>/Resturant food odering list.cpp
#include <stdio.h>
#include<math.h>
int main()
{
int Select;
int Steam_Momos, Chowmein, Grilled_Sandwich, Fresh_Juice, Cold_coffe;
printf("-------------------------\n");
printf("Welcome to Foodland \n");
printf(" 1 --> Steam Momos \n");
printf(" 2 --> Chowmein \n");
printf(" 3 --> Grilled Sandwich \n");
printf(" 4 --> Fresh Juice \n");
printf(" 5 --> Cold Coffee \n");
printf("-------------------------\n");
printf("Select the food which you like to order \n");
scanf("%d", &Select);
switch(Select)
{
case 1:
printf("Select Steam Momos \n");
printf("1. Chicken Steam Momos\n");
printf("2. Veg Steam momos \n");
printf("3. Paneer Momos \n");
break;
case 2:
printf("Select Chowmein \n");
printf("1. Chicken Chowmein \n");
printf("2. Veg Chowmein \n");
break;
case 3:
printf("Select Grilled Sandwich \n");
printf(" 1. Veg Cheese Sandwich \n");
printf(" 2. Cheese Sandwich \n");
printf(" 3. Paneer Sandwich \n");
break;
case 4:
printf("Select Fresh Juices\n");
printf(" 1. Watermelon Juice. \n");
printf(" 2. Apple Juice \n");
printf(" 3. Orange Juice \n");
printf(" 4. Grapes Juice \n");
break;
case 5:
printf("Select Coffee \n");
printf(" 1. Cappuccino \n");
printf(" 2. Espresso \n");
printf(" 3. cold coffee \n");
printf(" 4. Chocolate coffee \n");
break;
default:
printf("Selection not found!!\n");
break;
}
}
<file_sep>/F2. A company insures its driver 1) if the driver is married 2) unmarried, male and age above 30 3) unmarried, female and age above 25 - Copy.cpp
#include<stdio.h>
int main( )
{
char sex, ms ; int age ;
printf ( "Enter age, sex, marital status " ) ;
scanf ( "%d %c %c",&age, &sex, &ms ) ;
if ( ( ms == 'M') || ( ms == 'U' && sex == 'M' && age > 30 ) ||
( ms == 'U' && sex == 'F' && age > 25 ) )
printf ( "Driver is insured" ) ;
else printf ( "Driver is not insured" ) ;
}
<file_sep>/G1. Write a program to convert fahrenheit to celsius . - Copy.cpp
#include<stdio.h>
int main()
{
float fahrenheit, celsius;
printf("Enter Fahrenheit: \n");
scanf("%f",&fahrenheit);
celsius = (fahrenheit - 32)*5/9;
printf("Celsius: %f \n", celsius);
return 0;
}
<file_sep>/README.md
#include<stdio.h>
#include<string.h>
int main()
{
char str[]={'W','E','L','C','O','M', 'E','\0'};
printf("%s",str);
return 0;
}
<file_sep>/H2. Write a program to print numbers from 5 to 15. - Copy.cpp
#include<stdio.h>
int main()
{
int i=1;
for(i=1;i<=15;i++)
{
/* This statement is executed till the condition in above 'for loop' is true.
The space after %d is used for separating the numbers.*/
printf("%d ",i);
}
return 0;
}
<file_sep>/B1. Write a program to find Area and Perimeter of Triangle. - Copy.cpp
#include <stdio.h>
#include <math.h>
int main()
{
float l, b, h, p, a, area, sp;
printf("Enter the side of trinagle: \n");
scanf("%f%f%f", &l,&b,&h);
p= (l+b+h);
sp= p/2.0;
a= sqrt(sp*(sp-l)*(sp-b)*(sp-h));
printf("Permimerter of triangle: %4f unit\n",p);
printf("Area of Triangle: %4f unit \n", a);
return 0;
}
<file_sep>/B2. Write a program to find whether given year is Leap year. - Copy.cpp
#include<stdio.h>
int main()
{
int year;
printf("Enter a year \n");
scanf("%d", &year);
if ((year % 400) == 0)
printf("%d is a leap year \n", year);
else if ((year % 100) == 0)
printf("%d is a not leap year \n", year);
else if ((year % 4) == 0)
printf("%d is a leap year \n", year);
else
printf("%d is not a leap year \n", year);
return 0;
}
<file_sep>/A2. Write a program to find given number is Odd or even. - Copy.cpp
#include<stdio.h>
int main()
{
int n;
printf("Enter the number \n");
scanf("%d", &n);
if (n % 2 ==0)
{
printf("%d number is even \n", n);
}
else
{
printf("number is odd %d \n", n);
}
return 0;
}
<file_sep>/L1. Write a program to find the area of triangle when three sides are given. - Copy.cpp
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, s, area;
printf("Enter sides of a triangle\n");
scanf("%lf%lf%lf", &a, &b, &c);
s = (a+b+c)/2; // Semiperimeter
area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area of the triangle = %.2lf cm\n", area);
return 0;
}
<file_sep>/M1. If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits. (Hint Use the modulus operator ‘%’ and ‘’) - Copy.cpp
#include<stdio.h>
int main()
{
int a, b, c, d, e, n, sum=0;
printf("Enter the five digits: \n");
scanf("%d", &n);
a= (n/10000);
b=(n%10000)/1000;
c=(n%1000)/100;
d=(n%100)/10;
e=n%10;
sum=a+b+c+d+e;
printf("Sum of digits: %d \n", sum);
}
<file_sep>/F1. Write a program to find the grass salary of the person. (Basic salary as input and 20% of basic salary for HA and 40% of basic salary as DA). - Copy.cpp
#include <stdio.h>
int main()
{
float basic, gross, da, hra;
printf("Enter basic salary of an employee: ");
scanf("%f", &basic);
if(basic <= 10000)
{
da = basic * 0.4;
hra = basic * 0.2;
}
else if(basic <= 20000)
{
da = basic * 0.5;
hra = basic * 0.25;
}
else
{
da = basic * 0.55;
hra = basic * 0.3;
}
gross = basic + hra + da;
printf("GROSS SALARY OF EMPLOYEE = %.2f", gross);
return 0;
}
| f09da94d9e107c8ca183ac3c2c48a0bcc01252f6 | [
"Markdown",
"C",
"C++"
]
| 23 | C | mohammedfarhan442/cpgms | 71059bdcbf48df54747b290708dbf0b478895cc2 | b96703c4b65502c22fa93f68187b740b74e167b7 |
refs/heads/master | <repo_name>pradhumnsingh10/pradhumnportfolio<file_sep>/src/pages/skills/skills.component.jsx
import React from "react";
import Card from "react-bootstrap/Card";
import CardDeck from "react-bootstrap/CardDeck";
import Col from "react-bootstrap/Col";
import "./skills.styles.css";
const Skills = () => {
return ( <
div className = "pt-3 pb-3"
id = "skills" >
<
h1 className = "text-center font-details-b pb-4" > TECH SKILLS < /h1> <
CardDeck > <
Col md = { 5 } >
<
Card className = "focus mt-2 mb-2" >
<
Card.Body > <
Card.Title className = "text-center card-title" > Frontend < /Card.Title> <
hr / >
<
Card.Text className = "card-text d-flex justify-content-start flex-column" > < ul > < li > HTML < /li> <
li > CSS < /
li > < li > JavaScript < /li>< li > HTML < /li > < /ul > < /
Card.Text > < /
Card.Body > <
/Card> < /
Col > <
Col md = { 5 } >
<
Card className = "focus mt-2 mb-2" >
<
Card.Body > <
Card.Title className = "text-center card-title" > Backend < /Card.Title> <
hr / >
<
Card.Text className = "card-text d-flex justify-content-start flex-column" > < ul > < li > Nodejs < /li><li>Expressjs</
li > < li > Database - MYSQL, MongoDB < /li> <li>API</li > < /ul > < /
Card.Text > < /
Card.Body > <
/Card> < /
Col >
<
Col md = { 5 } >
<
Card className = "focus mt-2 mb-2" >
<
Card.Body > <
Card.Title className = "text-center card-title" > Languages < /Card.Title> <
hr / >
<
Card.Text className = "card-text d-flex justify-content-start flex-column" > < ul > < li > C < /li> <
li > C++ < /
li > < li > Python < /li>< /ul > < /
Card.Text > < /
Card.Body > <
/Card> < /
Col >
<
Col md = { 5 } >
<
Card className = "focus mt-2 mb-2" >
<
Card.Body > <
Card.Title className = "text-center card-title" > Other < /Card.Title> <
hr / >
<
Card.Text className = "card-text d-flex justify-content-start flex-column" > < ul > < li > Data Structure & Algorithm < /li> < li > Machine Learning < /li > < li > Deep Learning < /
li > < /ul > < /
Card.Text > < /
Card.Body > <
/Card> < /
Col > <
/
CardDeck > < /
div >
);
};
export default Skills;<file_sep>/src/pages/about/about.component.jsx
import React from "react";
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import "./about.styles.css";
import Profile from "../../assets/img/profile/profile.webp";
import Image from "react-bootstrap/Image";
import Button from "react-bootstrap/Button";
const About = () => {
return ( <
div id = "about" >
<
div className = "about" >
<
h1 className = "pt-3 text-center font-details pb-3" > ABOUT ME < /h1> <
Container >
<
Row className = "pt-3 pb-5 align-items-center" >
<
Col xs = { 12 }
md = { 6 } >
<
Row className = "justify-content-center mb-2 mr-2 " >
<
Image className = "profile justify-content-end"
alt = "profile"
src = { Profile }
thumbnail fluid / >
<
/Row> < /
Col > <
Col xs = { 12 }
md = { 6 } >
<
Row className = " align-items-start p-2 my-details rounded" >
<
strong > Hey!!! < /strong> I am a tech enthusiast, born and brought up in India.I am a Full Stack Web Developer with React.js, Express.js, Node.js, and MYSQL as my tech stack. <
br / >
I am pursuing B.tech from jamia millia islamia '.<
br / > I love learning about new technologies, what problems are they solving and How can I use them to build better and scalable products. <
br / > < br / >
<
Col className = "d-flex justify-content-center flex-wrap" >
<
div >
<
a href = "#contact" >
<
Button className = "m-2"
variant = "outline-primary" >
Let 's talk < /
Button > <
/a> < /
div > <
div >
<
a href = "https://drive.google.com"
target = "_blank"
rel = "noopener noreferrer" >
<
Button className = "m-2"
variant = "outline-success" >
My Resume <
/Button> < /
a > <
/div> <
div >
<
a href = "https://github.com/pradhumnsingh45"
target = "_blank"
rel = "noopener noreferrer" >
<
Button className = "m-2"
variant = "outline-dark" >
GitHub <
/Button> < /
a > <
/div> <
div >
<
a href = "https://www.linkedin.com/in/pradhumn-singh-505a25b7/"
target = "_blank"
rel = "noopener noreferrer" >
<
Button className = "m-2"
variant = "outline-info" >
LinkedIn <
/Button> < /
a > <
/div> < /
Col > <
/Row> < /
Col > <
/Row> < /
Container > <
/div> < /
div >
);
};
export default About;<file_sep>/src/components/projects-timeline/projects-timeline.component.jsx
import React from "react";
import Card from "react-bootstrap/Card";
import CardDeck from "react-bootstrap/CardDeck";
import Row from "react-bootstrap/Col";
import "./projects-timeline.styles.css";
const Projects = () => {
return ( <
div className = "pt-3 pb-3"
id = "projects" >
<
h1 className = "text-center font-details-b pb-4" > PROJECTS < /h1> <
CardDeck > <
Row md = { 12 } >
<
Card className = "focus mt-2 mb-2" >
<
Card.Body > <
Card.Title className = "text-center card-title" > < /Card.Title> <
hr / >
<
Card.Text className = "card-text d-flex justify-content-start flex-column" >
<
ul id = "menu" >
<
li > < a href = "https://drive.google.com/drive/folders/1e7OTDSkF1i_JSP0fBzzN6tmk77Y6NgN3?usp=sharing" > < strong > Shopping Cart < /strong>: users can buy clothings and accesories from here.< /a > < /li > <
li > < a href = "https://drive.google.com/drive/folders/1e7OTDSkF1i_JSP0fBzzN6tmk77Y6NgN3?usp=sharing" > < strong > Plasma Donation < /strong>: users can register themselves,find people in any area they need blood.< /a > < /li > <
li > < a href = "https://drive.google.com/drive/folders/1e7OTDSkF1i_JSP0fBzzN6tmk77Y6NgN3?usp=sharing" > < strong > Github Finder < / strong>:users can find any profile by searching their username.< /a > < /li > <
li > < a href = "#" > < strong > Movie Review Detector < / strong>:Ml model that tells Review is postitve or negative < /a > < /li > < /
ul > < /
Card.Text > < /
Card.Body > <
/Card> < /
Row > < /CardDeck > < /
div > )
};
export default Projects;<file_sep>/src/components/my-navbar/my-navbar.component.jsx
import React from "react";
import Navbar from "react-bootstrap/Navbar";
import Nav from "react-bootstrap/Nav";
import "./my-navbar.styles.css";
const MyNavbar = () => {
return ( <
div >
<
Navbar fixed = "top"
variant = "dark"
expand = "md"
className = "animate-navbar nav-theme justify-content-between" >
<
div >
<
Navbar.Brand href = "#home" >
<
/Navbar.Brand> < /
div > <
div >
<
Navbar.Collapse id = "basic-navbar-nav" >
<
Nav className = "mr-auto " >
<
Nav.Link href = "#home" > Home < /Nav.Link> <
Nav.Link href = "#about" > About < /Nav.Link> <
Nav.Link href = "#skills" > Skills < /Nav.Link><
Nav.Link href = "#projects" > Projects < /Nav.Link> <
Nav.Link href = "#contact" > Contact < /Nav.Link> < /
Nav > <
/Navbar.Collapse> < /
div > <
/Navbar> < /
div >
);
};
export default MyNavbar; | 61bbe7a06904614cdc6e7e20fe91409c77361aed | [
"JavaScript"
]
| 4 | JavaScript | pradhumnsingh10/pradhumnportfolio | d0c5a01c239b2c54908f604a1bf30eeef5a1afbb | 70548ddc212b0442af4dde8777f7bbb65b9cbd85 |
refs/heads/main | <repo_name>runingcoder/DBMSPROJECT<file_sep>/employee1.sql
-- phpMyAdmin SQL Dump
-- version 5.1.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 23, 2021 at 06:55 AM
-- Server version: 10.4.19-MariaDB
-- PHP Version: 7.3.28
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `employee`
--
-- --------------------------------------------------------
--
-- Table structure for table `auth_group`
--
CREATE TABLE `auth_group` (
`id` int(11) NOT NULL,
`name` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `auth_group_permissions`
--
CREATE TABLE `auth_group_permissions` (
`id` int(11) NOT NULL,
`group_id` int(11) NOT NULL,
`permission_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `auth_permission`
--
CREATE TABLE `auth_permission` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`content_type_id` int(11) NOT NULL,
`codename` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `auth_permission`
--
INSERT INTO `auth_permission` (`id`, `name`, `content_type_id`, `codename`) VALUES
(1, 'Can add log entry', 1, 'add_logentry'),
(2, 'Can change log entry', 1, 'change_logentry'),
(3, 'Can delete log entry', 1, 'delete_logentry'),
(4, 'Can view log entry', 1, 'view_logentry'),
(5, 'Can add permission', 2, 'add_permission'),
(6, 'Can change permission', 2, 'change_permission'),
(7, 'Can delete permission', 2, 'delete_permission'),
(8, 'Can view permission', 2, 'view_permission'),
(9, 'Can add group', 3, 'add_group'),
(10, 'Can change group', 3, 'change_group'),
(11, 'Can delete group', 3, 'delete_group'),
(12, 'Can view group', 3, 'view_group'),
(13, 'Can add user', 4, 'add_user'),
(14, 'Can change user', 4, 'change_user'),
(15, 'Can delete user', 4, 'delete_user'),
(16, 'Can view user', 4, 'view_user'),
(17, 'Can add content type', 5, 'add_contenttype'),
(18, 'Can change content type', 5, 'change_contenttype'),
(19, 'Can delete content type', 5, 'delete_contenttype'),
(20, 'Can view content type', 5, 'view_contenttype'),
(21, 'Can add session', 6, 'add_session'),
(22, 'Can change session', 6, 'change_session'),
(23, 'Can delete session', 6, 'delete_session'),
(24, 'Can view session', 6, 'view_session'),
(25, 'Can add Department', 7, 'add_department'),
(26, 'Can change Department', 7, 'change_department'),
(27, 'Can delete Department', 7, 'delete_department'),
(28, 'Can view Department', 7, 'view_department'),
(29, 'Can add Role', 8, 'add_role'),
(30, 'Can change Role', 8, 'change_role'),
(31, 'Can delete Role', 8, 'delete_role'),
(32, 'Can view Role', 8, 'view_role'),
(33, 'Can add Employee', 9, 'add_employee'),
(34, 'Can change Employee', 9, 'change_employee'),
(35, 'Can delete Employee', 9, 'delete_employee'),
(36, 'Can view Employee', 9, 'view_employee'),
(37, 'Can add Leave', 10, 'add_leave'),
(38, 'Can change Leave', 10, 'change_leave'),
(39, 'Can delete Leave', 10, 'delete_leave'),
(40, 'Can view Leave', 10, 'view_leave'),
(41, 'Can add features', 11, 'add_features'),
(42, 'Can change features', 11, 'change_features'),
(43, 'Can delete features', 11, 'delete_features'),
(44, 'Can view features', 11, 'view_features');
-- --------------------------------------------------------
--
-- Table structure for table `auth_user`
--
CREATE TABLE `auth_user` (
`id` int(11) NOT NULL,
`password` varchar(128) NOT NULL,
`last_login` datetime(6) DEFAULT NULL,
`is_superuser` tinyint(1) NOT NULL,
`username` varchar(150) NOT NULL,
`first_name` varchar(150) NOT NULL,
`last_name` varchar(150) NOT NULL,
`email` varchar(254) NOT NULL,
`is_staff` tinyint(1) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`date_joined` datetime(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `auth_user`
--
INSERT INTO `auth_user` (`id`, `password`, `last_login`, `is_superuser`, `username`, `first_name`, `last_name`, `email`, `is_staff`, `is_active`, `date_joined`) VALUES
(1, 'pbkdf2_sha256$120000$a68DaVngx24E$4isZaGyJ29b/wsJTOss/ZN/AFneiH2y0dYnRGErV6pU=', '2021-08-23 03:31:47.818211', 1, 'admin98', '', '', '', 1, 1, '2021-07-20 05:13:47.270560'),
(2, 'pbkdf2_sha256$120000$Naf0YIWoA2BK$8e5SUJdeRPUyKJAW5xoXNcE09fXAzk2TTK5n4DqotOM=', '2021-08-23 03:29:30.681215', 0, 'Kakeru', '', '', '', 0, 1, '2021-07-20 06:01:50.299388'),
(3, 'pbkdf2_sha256$260000$hL09ben0iufXG8ZEnpO1MM$4lNkuYsL4PqHM1AR4m4o5Hxf2P7C0UdLcauXfcDUWcQ=', '2021-07-20 12:20:35.065137', 0, 'Shoyo', '', '', '', 0, 1, '2021-07-20 06:03:05.108235'),
(4, 'pbkdf2_sha256$120000$1alGDFMfrjBn$Eocf4EGXxl2A8X5L5/ylMn1bw5VFenxgZX/ca2q1+ts=', '2021-08-23 03:30:52.773447', 0, 'Pravesh', '', '', '<EMAIL>', 0, 1, '2021-08-23 03:30:22.478864');
-- --------------------------------------------------------
--
-- Table structure for table `auth_user_groups`
--
CREATE TABLE `auth_user_groups` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`group_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `auth_user_user_permissions`
--
CREATE TABLE `auth_user_user_permissions` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`permission_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `django_admin_log`
--
CREATE TABLE `django_admin_log` (
`id` int(11) NOT NULL,
`action_time` datetime(6) NOT NULL,
`object_id` longtext DEFAULT NULL,
`object_repr` varchar(200) NOT NULL,
`action_flag` smallint(5) UNSIGNED NOT NULL CHECK (`action_flag` >= 0),
`change_message` longtext NOT NULL,
`content_type_id` int(11) DEFAULT NULL,
`user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `django_admin_log`
--
INSERT INTO `django_admin_log` (`id`, `action_time`, `object_id`, `object_repr`, `action_flag`, `change_message`, `content_type_id`, `user_id`) VALUES
(1, '2021-07-20 05:59:06.468183', '1', 'Finance', 1, '[{\"added\": {}}]', 7, 1),
(2, '2021-07-20 05:59:24.979348', '2', 'HR', 1, '[{\"added\": {}}]', 7, 1),
(3, '2021-07-20 05:59:46.815977', '3', 'Managing Director', 1, '[{\"added\": {}}]', 7, 1),
(4, '2021-07-20 06:00:10.942343', '3', 'Managing Director', 3, '', 7, 1),
(5, '2021-07-20 06:00:26.097344', '4', 'Engineering', 1, '[{\"added\": {}}]', 7, 1),
(6, '2021-07-20 06:00:46.639396', '1', 'Accountant', 1, '[{\"added\": {}}]', 8, 1),
(7, '2021-07-20 06:01:08.352283', '2', 'Peon', 1, '[{\"added\": {}}]', 8, 1),
(8, '2021-07-20 06:01:50.594206', '2', 'Kakeru', 1, '[{\"added\": {}}]', 4, 1),
(9, '2021-07-20 06:02:35.744267', '1', 'Itadori Yuji', 1, '[{\"added\": {}}]', 9, 1),
(10, '2021-07-20 06:03:05.629912', '3', 'Shoyo', 1, '[{\"added\": {}}]', 4, 1),
(11, '2021-07-20 06:03:40.251339', '2', '<NAME>', 1, '[{\"added\": {}}]', 9, 1),
(12, '2021-07-20 06:06:57.840330', '2', '<NAME>', 2, '[{\"changed\": {\"fields\": [\"Profile Image\"]}}]', 9, 1),
(13, '2021-07-20 12:17:28.878295', '3', 'Itadori Yuji', 2, '[]', 9, 1);
-- --------------------------------------------------------
--
-- Table structure for table `django_content_type`
--
CREATE TABLE `django_content_type` (
`id` int(11) NOT NULL,
`app_label` varchar(100) NOT NULL,
`model` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `django_content_type`
--
INSERT INTO `django_content_type` (`id`, `app_label`, `model`) VALUES
(1, 'admin', 'logentry'),
(3, 'auth', 'group'),
(2, 'auth', 'permission'),
(4, 'auth', 'user'),
(5, 'contenttypes', 'contenttype'),
(7, 'employee', 'department'),
(9, 'employee', 'employee'),
(8, 'employee', 'role'),
(10, 'leave', 'leave'),
(11, 'myapp', 'features'),
(6, 'sessions', 'session');
-- --------------------------------------------------------
--
-- Table structure for table `django_migrations`
--
CREATE TABLE `django_migrations` (
`id` int(11) NOT NULL,
`app` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`applied` datetime(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `django_migrations`
--
INSERT INTO `django_migrations` (`id`, `app`, `name`, `applied`) VALUES
(1, 'contenttypes', '0001_initial', '2021-07-20 05:06:42.467483'),
(2, 'auth', '0001_initial', '2021-07-20 05:06:43.193031'),
(3, 'admin', '0001_initial', '2021-07-20 05:06:43.358534'),
(4, 'admin', '0002_logentry_remove_auto_add', '2021-07-20 05:06:43.372526'),
(5, 'admin', '0003_logentry_add_action_flag_choices', '2021-07-20 05:06:43.384894'),
(6, 'contenttypes', '0002_remove_content_type_name', '2021-07-20 05:06:43.463863'),
(7, 'auth', '0002_alter_permission_name_max_length', '2021-07-20 05:06:43.508856'),
(8, 'auth', '0003_alter_user_email_max_length', '2021-07-20 05:06:43.532842'),
(9, 'auth', '0004_alter_user_username_opts', '2021-07-20 05:06:43.543835'),
(10, 'auth', '0005_alter_user_last_login_null', '2021-07-20 05:06:43.594523'),
(11, 'auth', '0006_require_contenttypes_0002', '2021-07-20 05:06:43.598520'),
(12, 'auth', '0007_alter_validators_add_error_messages', '2021-07-20 05:06:43.609516'),
(13, 'auth', '0008_alter_user_username_max_length', '2021-07-20 05:06:43.634500'),
(14, 'auth', '0009_alter_user_last_name_max_length', '2021-07-20 05:06:43.656486'),
(15, 'auth', '0010_alter_group_name_max_length', '2021-07-20 05:06:43.678473'),
(16, 'auth', '0011_update_proxy_permissions', '2021-07-20 05:06:43.690467'),
(17, 'auth', '0012_alter_user_first_name_max_length', '2021-07-20 05:06:43.711451'),
(18, 'employee', '0001_initial', '2021-07-20 05:06:43.959174'),
(19, 'employee', '0002_auto_20200904_1545', '2021-07-20 05:06:44.032827'),
(20, 'leave', '0001_initial', '2021-07-20 05:06:44.129748'),
(21, 'leave', '0002_alter_leave_leavetype', '2021-07-20 05:06:44.143737'),
(22, 'sessions', '0001_initial', '2021-07-20 05:06:44.197706'),
(23, 'employee', '0003_auto_20210720_1722', '2021-07-20 11:37:34.024760'),
(24, 'leave', '0003_alter_leave_id', '2021-07-20 11:37:34.096714'),
(25, 'myapp', '0001_initial', '2021-07-20 11:37:34.152678');
-- --------------------------------------------------------
--
-- Table structure for table `django_session`
--
CREATE TABLE `django_session` (
`session_key` varchar(40) NOT NULL,
`session_data` longtext NOT NULL,
`expire_date` datetime(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `django_session`
--
INSERT INTO `django_session` (`session_key`, `session_data`, `expire_date`) VALUES
('3j189utq2b4cv49q54ji11q5wrq41ett', 'e30:1m5oXq:l9acCXehUWHY4m0lz138gdDRzyBB1pxT44-_iat0wRI', '2021-08-03 12:08:18.890165'),
('<KEY>', <KEY>', '2021-08-03 06:52:20.752919'),
('<KEY>', <KEY>', '2021-08-03 06:06:50.300140'),
('toxigw2t5sftovvzy8338wrqhi6envjt', 'e30:1m5oRA:f8E7RCfkP5-LCXKkpE-1btdL9Dr-_q-Wq-dNQSqDmEc', '2021-08-03 12:01:24.642170'),
('<KEY>', '<KEY> '2021-09-06 03:31:47.833200'),
('<KEY>', '.<KEY>2N5Xnb376BgL9_<KEY>Y<KEY>APFkOCY:1m5own:VmSMvxtN_7syUKJnuGFVz7YIGhRThA0PYlQFHlsWNDA', '2021-08-03 12:34:05.088032');
-- --------------------------------------------------------
--
-- Table structure for table `employee_department`
--
CREATE TABLE `employee_department` (
`id` bigint(20) NOT NULL,
`name` varchar(125) NOT NULL,
`description` varchar(125) DEFAULT NULL,
`created` datetime(6) NOT NULL,
`updated` datetime(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `employee_department`
--
INSERT INTO `employee_department` (`id`, `name`, `description`, `created`, `updated`) VALUES
(1, 'Finance', 'To take care of all the financial works', '2021-07-20 05:59:06.466185', '2021-07-20 05:59:06.466185'),
(2, 'HR', 'To take care of the new employees and to give them salary', '2021-07-20 05:59:24.977347', '2021-07-20 05:59:24.977347'),
(4, 'Engineering', 'To learn how to analyze and deisgn', '2021-07-20 06:00:26.095349', '2021-07-20 06:00:26.095349'),
(5, 'Doctor', 'To take care of the patients in the world.', '2021-07-07 11:54:27.000000', '2021-07-21 11:54:27.000000');
-- --------------------------------------------------------
--
-- Table structure for table `employee_employee`
--
CREATE TABLE `employee_employee` (
`id` bigint(20) NOT NULL,
`image` varchar(100) DEFAULT NULL,
`firstname` varchar(125) NOT NULL,
`lastname` varchar(125) NOT NULL,
`othername` varchar(125) DEFAULT NULL,
`birthday` date NOT NULL,
`startdate` date DEFAULT NULL,
`employeetype` varchar(15) DEFAULT NULL,
`employeeid` varchar(10) DEFAULT NULL,
`dateissued` date DEFAULT NULL,
`created` datetime(6) DEFAULT NULL,
`updated` datetime(6) DEFAULT NULL,
`department_id` bigint(20) DEFAULT NULL,
`role_id` bigint(20) DEFAULT NULL,
`user_id` int(11) NOT NULL,
`is_blocked` tinyint(1) NOT NULL,
`is_deleted` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `employee_employee`
--
INSERT INTO `employee_employee` (`id`, `image`, `firstname`, `lastname`, `othername`, `birthday`, `startdate`, `employeetype`, `employeeid`, `dateissued`, `created`, `updated`, `department_id`, `role_id`, `user_id`, `is_blocked`, `is_deleted`) VALUES
(1, 'profiles/sidebar.jpg', 'Itadori', 'Yuji', NULL, '2000-02-12', '2021-06-09', 'Full-Time', NULL, '2021-06-30', '2021-07-20 06:02:35.742271', '2021-07-20 06:02:35.742271', 4, 1, 2, 0, 0),
(2, 'profiles/new_logo.png', 'Shoyo', 'Kun', NULL, '2000-05-01', '2021-06-07', 'Part-Time', NULL, '2021-06-28', '2021-07-20 06:03:40.249339', '2021-07-20 06:06:57.837333', 1, 2, 3, 0, 0),
(3, 'profiles/sidebar.jpg', 'Itadori', 'Yuji', 'Hero', '2000-02-12', '2021-06-09', 'Full-Time', 'RGL/12/345', '2021-06-30', '2021-07-20 12:14:51.398059', '2021-07-20 12:17:28.876296', 4, 1, 2, 0, 0),
(4, 'profiles/pravesh.jpeg', 'Pravesh', 'Khanal', 'richkid', '2018-12-04', '2021-08-22', 'Part-Time', NULL, '2021-08-23', '2021-08-23 03:54:22.675565', '2021-08-23 03:54:22.675565', 4, 3, 4, 0, 0);
-- --------------------------------------------------------
--
-- Table structure for table `employee_role`
--
CREATE TABLE `employee_role` (
`id` bigint(20) NOT NULL,
`name` varchar(125) NOT NULL,
`description` varchar(125) DEFAULT NULL,
`created` datetime(6) NOT NULL,
`updated` datetime(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `employee_role`
--
INSERT INTO `employee_role` (`id`, `name`, `description`, `created`, `updated`) VALUES
(1, 'Accountant', 'To account for all the financial transactions in the company', '2021-07-20 06:00:46.637399', '2021-07-20 06:00:46.637399'),
(2, 'Peon', 'To wash every corner of the office so that spark is default', '2021-07-20 06:01:08.351286', '2021-07-20 06:01:08.351286'),
(3, 'Technical Officer', 'The one who analyses and supervises all the technical stuff that happens in the organization.', '2021-08-23 09:19:30.297000', '2021-08-23 09:21:30.000000');
-- --------------------------------------------------------
--
-- Table structure for table `leave_leave`
--
CREATE TABLE `leave_leave` (
`id` bigint(20) NOT NULL,
`startdate` date DEFAULT NULL,
`enddate` date DEFAULT NULL,
`leavetype` varchar(25) DEFAULT NULL,
`reason` varchar(255) DEFAULT NULL,
`defaultdays` int(10) UNSIGNED DEFAULT NULL CHECK (`defaultdays` >= 0),
`status` varchar(12) NOT NULL,
`is_approved` tinyint(1) NOT NULL,
`updated` datetime(6) NOT NULL,
`created` datetime(6) NOT NULL,
`user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `leave_leave`
--
INSERT INTO `leave_leave` (`id`, `startdate`, `enddate`, `leavetype`, `reason`, `defaultdays`, `status`, `is_approved`, `updated`, `created`, `user_id`) VALUES
(1, '2021-07-21', '2021-07-23', 'emergency', 'I maa be a daddy now.', 30, 'approved', 1, '2021-07-20 06:06:23.179341', '2021-07-20 06:05:56.873290', 3),
(2, '2021-07-21', '2021-07-26', 'maternity', 'I have to kill some Gooses and reinstate the white energy.', 30, 'rejected', 0, '2021-07-20 12:23:56.941317', '2021-07-20 12:22:53.146349', 2),
(3, '2021-08-23', '2021-08-25', 'sick', 'please admin sensei. I will buy you a chocolate.', 30, 'approved', 1, '2021-08-22 17:27:22.805428', '2021-08-22 17:26:54.548494', 2),
(4, '2021-08-23', '2021-08-25', 'sick', 'GAijatra aayo, so , bhaktapur ghumauna laanu paryo saathi ahru lai.', 30, 'pending', 0, '2021-08-23 03:31:32.756417', '2021-08-23 03:31:32.756417', 4);
-- --------------------------------------------------------
--
-- Table structure for table `myapp_features`
--
CREATE TABLE `myapp_features` (
`id` bigint(20) NOT NULL,
`name` varchar(100) NOT NULL,
`details` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `auth_group`
--
ALTER TABLE `auth_group`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `name` (`name`);
--
-- Indexes for table `auth_group_permissions`
--
ALTER TABLE `auth_group_permissions`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `auth_group_permissions_group_id_permission_id_0cd325b0_uniq` (`group_id`,`permission_id`),
ADD KEY `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` (`permission_id`);
--
-- Indexes for table `auth_permission`
--
ALTER TABLE `auth_permission`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `auth_permission_content_type_id_codename_01ab375a_uniq` (`content_type_id`,`codename`);
--
-- Indexes for table `auth_user`
--
ALTER TABLE `auth_user`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `username` (`username`);
--
-- Indexes for table `auth_user_groups`
--
ALTER TABLE `auth_user_groups`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `auth_user_groups_user_id_group_id_94350c0c_uniq` (`user_id`,`group_id`),
ADD KEY `auth_user_groups_group_id_97559544_fk_auth_group_id` (`group_id`);
--
-- Indexes for table `auth_user_user_permissions`
--
ALTER TABLE `auth_user_user_permissions`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `auth_user_user_permissions_user_id_permission_id_14a6b632_uniq` (`user_id`,`permission_id`),
ADD KEY `auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm` (`permission_id`);
--
-- Indexes for table `django_admin_log`
--
ALTER TABLE `django_admin_log`
ADD PRIMARY KEY (`id`),
ADD KEY `django_admin_log_content_type_id_c4bce8eb_fk_django_co` (`content_type_id`),
ADD KEY `django_admin_log_user_id_c564eba6_fk_auth_user_id` (`user_id`);
--
-- Indexes for table `django_content_type`
--
ALTER TABLE `django_content_type`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `django_content_type_app_label_model_76bd3d3b_uniq` (`app_label`,`model`);
--
-- Indexes for table `django_migrations`
--
ALTER TABLE `django_migrations`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `django_session`
--
ALTER TABLE `django_session`
ADD PRIMARY KEY (`session_key`),
ADD KEY `django_session_expire_date_a5c62663` (`expire_date`);
--
-- Indexes for table `employee_department`
--
ALTER TABLE `employee_department`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `employee_employee`
--
ALTER TABLE `employee_employee`
ADD PRIMARY KEY (`id`),
ADD KEY `employee_employee_user_id_2dd26fdc_fk_auth_user_id` (`user_id`),
ADD KEY `employee_employee_department_id_8fce1a05_fk` (`department_id`),
ADD KEY `employee_employee_role_id_a4c099f1_fk` (`role_id`);
--
-- Indexes for table `employee_role`
--
ALTER TABLE `employee_role`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `leave_leave`
--
ALTER TABLE `leave_leave`
ADD PRIMARY KEY (`id`),
ADD KEY `leave_leave_user_id_b4b01ea9_fk_auth_user_id` (`user_id`);
--
-- Indexes for table `myapp_features`
--
ALTER TABLE `myapp_features`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `auth_group`
--
ALTER TABLE `auth_group`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `auth_group_permissions`
--
ALTER TABLE `auth_group_permissions`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `auth_permission`
--
ALTER TABLE `auth_permission`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=45;
--
-- AUTO_INCREMENT for table `auth_user`
--
ALTER TABLE `auth_user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `auth_user_groups`
--
ALTER TABLE `auth_user_groups`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `auth_user_user_permissions`
--
ALTER TABLE `auth_user_user_permissions`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `django_admin_log`
--
ALTER TABLE `django_admin_log`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- AUTO_INCREMENT for table `django_content_type`
--
ALTER TABLE `django_content_type`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- AUTO_INCREMENT for table `django_migrations`
--
ALTER TABLE `django_migrations`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26;
--
-- AUTO_INCREMENT for table `employee_department`
--
ALTER TABLE `employee_department`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `employee_employee`
--
ALTER TABLE `employee_employee`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `employee_role`
--
ALTER TABLE `employee_role`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `leave_leave`
--
ALTER TABLE `leave_leave`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `myapp_features`
--
ALTER TABLE `myapp_features`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `auth_group_permissions`
--
ALTER TABLE `auth_group_permissions`
ADD CONSTRAINT `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`),
ADD CONSTRAINT `auth_group_permissions_group_id_b120cbf9_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`);
--
-- Constraints for table `auth_permission`
--
ALTER TABLE `auth_permission`
ADD CONSTRAINT `auth_permission_content_type_id_2f476e4b_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`);
--
-- Constraints for table `auth_user_groups`
--
ALTER TABLE `auth_user_groups`
ADD CONSTRAINT `auth_user_groups_group_id_97559544_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`),
ADD CONSTRAINT `auth_user_groups_user_id_6a12ed8b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
--
-- Constraints for table `auth_user_user_permissions`
--
ALTER TABLE `auth_user_user_permissions`
ADD CONSTRAINT `auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`),
ADD CONSTRAINT `auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
--
-- Constraints for table `django_admin_log`
--
ALTER TABLE `django_admin_log`
ADD CONSTRAINT `django_admin_log_content_type_id_c4bce8eb_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`),
ADD CONSTRAINT `django_admin_log_user_id_c564eba6_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
--
-- Constraints for table `employee_employee`
--
ALTER TABLE `employee_employee`
ADD CONSTRAINT `employee_employee_department_id_8fce1a05_fk` FOREIGN KEY (`department_id`) REFERENCES `employee_department` (`id`),
ADD CONSTRAINT `employee_employee_role_id_a4c099f1_fk` FOREIGN KEY (`role_id`) REFERENCES `employee_role` (`id`),
ADD CONSTRAINT `employee_employee_user_id_2dd26fdc_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
--
-- Constraints for table `leave_leave`
--
ALTER TABLE `leave_leave`
ADD CONSTRAINT `leave_leave_user_id_b4b01ea9_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/newrequirements.txt
args==0.1.0
arrow==0.13.1
asgiref==2.3.2
asn1crypto==0.24.0
async-timeout==2.0.1
attrs==18.2.0
autobahn==19.2.1
Automat==0.7.0
Babel==2.6.0
backports.entry-points-selectable==1.1.0
beautifulsoup4==4.7.1
cairocffi==1.0.2
CairoSVG==2.5.2
certifi==2018.11.29
cffi==1.14.5
chardet==3.0.4
charset-normalizer==2.0.3
clint==0.5.1
constantly==15.1.0
cryptography==3.4.7
cssselect2==0.2.1
defusedxml==0.5.0
distlib==0.3.2
dj-database-url==0.5.0
Django==2.1.7
django-admin-honeypot==1.1.0
django-allauth==0.38.0
django-appconf==1.0.2
django-channels==0.7.0
django-ckeditor==5.6.1
django-compressor==2.4.1
django-crispy-forms==1.7.2
django-debug-toolbar==1.11
django-encrypted-model-fields==0.5.8
django-filter==2.1.0
django-haystack==2.8.1
django-hosts==3.0
django-js-asset==1.2.1
django-markdown==0.8.4
django-phonenumber-field==2.2.0
django-redis==4.10.0
django-request==1.5.4
django-softdelete==0.9.0
django-tables2==2.0.4
django-taggit==0.23.0
django-urlcrypt==0.1.6
django-weasyprint==0.5.4
django-widget-tweaks==1.4.3
djangorestframework==3.9.1
easy-thumbnails==2.6
elasticsearch==6.3.1
filelock==3.0.12
googledrivedownloader==0.3
holidays==0.9.9
html5lib==1.0.1
hurry.filesize==0.9
hyperlink==18.0.0
idna==2.8
image==1.5.33
incremental==17.5.0
install==1.3.4
Jinja2==2.10
Markdown==3.0.1
MarkupSafe==1.1.0
mysql-connector-python==8.0.26
mysqlclient==2.0.3
numpy==1.21.1
oauthlib==3.0.1
pandas==1.3.0
phonenumbers==8.10.5
phonenumberslite==8.8.8
Pillow==8.3.1
pipenv==2018.11.26
platformdirs==2.0.2
protobuf==3.17.3
pycparser==2.19
PyHamcrest==1.9.0
PyJWT==1.7.1
PyMySQL==1.0.2
Pyphen==0.9.5
PySocks==1.6.8
pysolr==3.8.1
python-dateutil==2.7.5
python-decouple==3.1
python3-openid==3.1.0
pytube==9.4.0
pytz==2018.9
rcssmin==1.0.6
redis==3.1.0
reportlab==3.5.68
requests==2.21.0
requests-oauthlib==1.2.0
rjsmin==1.1.0
serious-django-permissions==0.6
six==1.12.0
soupsieve==1.7.3
South==1.0.2
sqlparse==0.2.4
tinycss2==1.0.1
tweepy==3.7.0
twilio==6.63.0
txaio==18.8.1
urllib3==1.24.1
virtualenv==16.0.0
virtualenv-clone==0.5.1
WeasyPrint==45
webencodings==0.5.1
wget==3.2
Whoosh==2.7.4
zope.interface==5.0.0
<file_sep>/myapp/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Features
from django.contrib.auth.models import User, auth
from django.contrib import messages
from django.shortcuts import redirect
# Create your views here.
def index(request):
# call an object for the class
feture =Features.objects.all()
# turns into a list of all object of the model , that we edited from the website itself.
return render(request, 'index.html', {"features": feture})
def register(request):
if request.method == 'POST':
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
password2 = request.POST['<PASSWORD>2']
if password ==password2:
if User.objects.filter(email=email).exists():
messages.info(request, 'Email ALready Used')
return redirect('register')
elif User.objects.filter(username=username).exists():
messages.info(request, "Username already used.")
return redirect('/new/register')
else:
user = User.objects.create_user(username=username, email =email, password =<PASSWORD>)
user. save();
return redirect('/new/login')
else:
messages.info(request, "The passwords don't match at all.")
return redirect('/new/register')
return render(request, 'register.html')
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['<PASSWORD>']
user = auth.authenticate(username =username, password =<PASSWORD>)
if user is not None:
auth.login(request, user)
return redirect('/new')
else:
messages.info(request, "invalid credentials")
return redirect('/new/login')
else:
return render(request, 'login.html')
def logout(request):
auth.logout(request)
# this single line will log out the user
return redirect('/new')
def counter(request):
posts = [1, 3, 7,3 ,777, 2,3 , 'asdfa', 'asdsd', 'Hello']
return render(request, 'counter.html', {'posts': posts})
def post(request, pk):
return render(request, 'post.html', {'pk': pk})
def about(request):
# call an object for the class
feture =Features.objects.all()
# turns into a list of all object of the model , that we edited from the website itself.
return render(request, 'about.html', {"features": feture})
def services(request):
# call an object for the class
feture =Features.objects.all()
# turns into a list of all object of the model , that we edited from the website itself.
return render(request, 'services.html', {"features": feture})
def contact(request):
# call an object for the class
feture =Features.objects.all()
# turns into a list of all object of the model , that we edited from the website itself.
return render(request, 'contact.html', {"features": feture})<file_sep>/employee/models.py
import datetime
from employee.utility import code_format
from django.db import models
from employee.managers import EmployeeManager
from phonenumber_field.modelfields import PhoneNumberField
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from leave.models import Leave
# Create your models here.
class Role(models.Model):
name = models.CharField(max_length=125)
description = models.CharField(max_length=125,null=True,blank=True)
created = models.DateTimeField(verbose_name=_('Created'),auto_now_add=True)
updated = models.DateTimeField(verbose_name=_('Updated'),auto_now=True)
class Meta:
verbose_name = _('Role')
verbose_name_plural = _('Roles')
ordering = ['name','created']
def __str__(self):
return self.name
class Department(models.Model):
name = models.CharField(max_length=125)
description = models.CharField(max_length=125,null=True,blank=True)
created = models.DateTimeField(verbose_name=_('Created'),auto_now_add=True)
updated = models.DateTimeField(verbose_name=_('Updated'),auto_now=True)
class Meta:
verbose_name = _('Department')
verbose_name_plural = _('Departments')
ordering = ['name','created']
def __str__(self):
return self.name
class Employee(models.Model):
MALE = 'male'
FEMALE = 'female'
OTHER = 'other'
NOT_KNOWN = 'Not Known'
GENDER = (
(MALE,'Male'),
(FEMALE,'Female'),
(OTHER,'Other'),
(NOT_KNOWN,'Not Known'),
)
MR = 'Mr'
MRS = 'Mrs'
MSS = 'Mss'
DR = 'Dr'
SIR = 'Sir'
MADAM = 'Madam'
TITLE = (
(MR,'Mr'),
(MRS,'Mrs'),
(MSS,'Mss'),
(DR,'Dr'),
(SIR,'Sir'),
(MADAM,'Madam'),
)
FULL_TIME = 'Full-Time'
PART_TIME = 'Part-Time'
CONTRACT = 'Contract'
INTERN = 'Intern'
EMPLOYEETYPE = (
(FULL_TIME,'Full-Time'),
(PART_TIME,'Part-Time'),
(CONTRACT,'Contract'),
(INTERN,'Intern'),
)
# PERSONAL DATA
user = models.ForeignKey(User,on_delete=models.CASCADE,default=1)
image = models.FileField(_('Profile Image'),upload_to='profiles',default='default.png',blank=True,null=True,help_text='upload image size less than 2.0MB')#work on path username-date/image
firstname = models.CharField(_('Firstname'),max_length=125,null=False,blank=False)
lastname = models.CharField(_('Lastname'),max_length=125,null=False,blank=False)
othername = models.CharField(_('Othername (optional)'),max_length=125,null=True,blank=True)
birthday = models.DateField(_('Birthday'),blank=False,null=False)
department = models.ForeignKey(Department,verbose_name =_('Department'),on_delete=models.SET_NULL,null=True,default=None)
role = models.ForeignKey(Role,verbose_name =_('Role'),on_delete=models.SET_NULL,null=True,default=None)
startdate = models.DateField(_('Employement Date'),help_text='date of employement',blank=False,null=True)
employeetype = models.CharField(_('Employee Type'),max_length=15,default=FULL_TIME,choices=EMPLOYEETYPE,blank=False,null=True)
employeeid = models.CharField(_('Employee ID Number'),max_length=10,null=True,blank=True)
dateissued = models.DateField(_('Date Issued'),help_text='date staff id was issued',blank=False,null=True)
# app related
is_blocked = models.BooleanField(_('Is Blocked'),help_text='button to toggle employee block and unblock',default=False)
is_deleted = models.BooleanField(_('Is Deleted'),help_text='button to toggle employee deleted and undelete',default=False)
created = models.DateTimeField(verbose_name=_('Created'),auto_now_add=True,null=True)
updated = models.DateTimeField(verbose_name=_('Updated'),auto_now=True,null=True)
#PLUG MANAGERS
objects = EmployeeManager()
class Meta:
verbose_name = _('Employee')
verbose_name_plural = _('Employees')
ordering = ['-created']
def __str__(self):
return self.get_full_name
@property
def get_full_name(self):
fullname = ''
firstname = self.firstname
lastname = self.lastname
othername = self.othername
if (firstname and lastname) or othername is None:
fullname = firstname +' '+ lastname
return fullname
elif othername:
fullname = firstname + ' '+ lastname +' '+othername
return fullname
return
@property
def get_age(self):
current_year = datetime.date.today().year
dateofbirth_year = self.birthday.year
if dateofbirth_year:
return current_year - dateofbirth_year
return
@property
def can_apply_leave(self):
pass
def save(self,*args,**kwargs):
'''
overriding the save method - for every instance that calls the save method
perform this action on its employee_id
added : March, 03 2019 - 11:08 PM
'''
get_id = self.employeeid #grab employee_id number from submitted form field
data = code_format(get_id)
self.employeeid = data #pass the new code to the employee_id as its orifinal or actual code
super().save(*args,**kwargs) # call the parent save method
# print(self.employeeid)
<file_sep>/NEWproject/settings.py
"""
Django settings for NEWproject project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-4)+f)*k13s$i3b#tor_g%+zs!#)9xl0ma&(n2ns8)r&62)$et7'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = ['myapp',
'Newwebtry',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.humanize',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# INSTALLED APPS
'crispy_forms',
'phonenumber_field',
'widget_tweaks',
# PROJECT APPS
'dashboard',
'accounts',
'employee',
'leave',
'debug_toolbar',
]
MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'NEWproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR, 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'NEWproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'employee',
'USER': 'root',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '3306',
"OPTIONS": {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES', innodb_strict_mode=1",
'charset': 'utf8mb4',
"autocommit": True,
}
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# STATIC FILES WILL BE SERVED FROM newsatic WHEN WE ARE LIVE - OUT SIDE OF PROJECT
STATIC_ROOT = os.path.join(BASE_DIR, 'newstatic')
#THIS KEEPS THE PROJECT FILES - CSS/JS/IMAGES/FONTS (this gets transferred to newstatic)
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static_in_proj','our_static'),
os.path.join(BASE_DIR, 'static_cdn', 'static_root'),
os.path.join(BASE_DIR, 'static'),
]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),'static_cdn','media_root')
INTERNAL_IPS = [
'127.0.0.1',
]<file_sep>/myapp/models.py
from django.db import models
# Create your models here.
class Features(models.Model):
# models.model turn whatever is in the class as model
name = models.CharField(max_length = 100)
details = models.CharField(max_length = 500)
# migrate these datas into the database
# python manage.py makemigrations
# python manage.py migrate
# python manage.py createsuperuser .. to create
# the admin logic credentials for serverside access
# for the developers<file_sep>/myapp/admin.py
from django.contrib import admin
# Register your models here.
from .models import Features
admin.site.register(Features)<file_sep>/accounts/sms.py
import os
from twilio.rest import Client
# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
message = client.messages.create(
body='Hi there, this is what I am talking about, part 2',
from_='+18622256163',
to='+977 984-3812816'
)
print(message.sid)<file_sep>/myapp/urls.py
from django.urls import path
from . import views
urlpatterns =[
path('', views.index, name='index'),
path('about/', views.about, name='about'),
path('services/', views.services, name='services'),
path('contact/', views.contact, name='contact'),
path('counter/', views.counter, name='counter'),
path('register/', views.register, name='register'),
path('login/', views.login, name='login'),
path('logout/', views.logout, name='logout'),
path('post/<str:pk>', views.post, name='post'),
]<file_sep>/Newwebtry/urls.py
from django.urls import path, include
from . import views
urlpatterns =[
path('', views.index1, name='index1'),
path('login/', views.login, name='login'),
path('logout/', views.logout, name='logout'),
path('register', views.register, name='register'),
path('accounts/', include('accounts.urls', namespace='accounts')),
path('dashboard/', include('dashboard.urls', namespace='dashboard')),
]
<file_sep>/leave/migrations/0002_alter_leave_leavetype.py
# Generated by Django 3.2.5 on 2021-07-20 04:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('leave', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='leave',
name='leavetype',
field=models.CharField(choices=[('sick', 'Sick Leave'), ('casual', 'Casual Leave'), ('emergency', 'Emergency Leave'), ('study', 'Study Leave'), ('maternity', 'Maternity Leave'), ('bereavement', 'Bereavement Leave'), ('quarantine', 'Self Quarantine'), ('compensatory', 'Compensatory Leave'), ('sabbatical', 'Sabbatical Leave')], default='sick', max_length=25, null=True),
),
]
<file_sep>/leave/migrations/0004_auto_20210822_2041.py
# Generated by Django 2.1.7 on 2021-08-22 14:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('leave', '0003_alter_leave_id'),
]
operations = [
migrations.AlterField(
model_name='leave',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
]
<file_sep>/employee/admin.py
from django.contrib import admin
from employee.models import Role,Department,Employee
admin.site.register(Role)
admin.site.register(Department)
admin.site.register(Employee)
| 60aa9635cd6d8870adf1a412e4fd3633a75c8a4b | [
"SQL",
"Python",
"Text"
]
| 13 | SQL | runingcoder/DBMSPROJECT | 37cae54eb357d267dbb526cb5edf6ba3f8f071e8 | e008063b180434fb2ff56190f8b9ee99799f47f0 |
refs/heads/master | <file_sep>import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { TpKhSharedModule } from 'app/shared/shared.module';
import { SingerComponent } from './singer.component';
import { SingerDetailComponent } from './singer-detail.component';
import { SingerUpdateComponent } from './singer-update.component';
import { SingerDeleteDialogComponent } from './singer-delete-dialog.component';
import { singerRoute } from './singer.route';
@NgModule({
imports: [TpKhSharedModule, RouterModule.forChild(singerRoute)],
declarations: [SingerComponent, SingerDetailComponent, SingerUpdateComponent, SingerDeleteDialogComponent],
entryComponents: [SingerDeleteDialogComponent],
})
export class TpKhSingerModule {}
<file_sep>package com.tp.soa.service.mapper;
import com.tp.soa.domain.*;
import com.tp.soa.service.dto.AlbumsDTO;
import org.mapstruct.*;
/**
* Mapper for the entity {@link Albums} and its DTO {@link AlbumsDTO}.
*/
@Mapper(componentModel = "spring", uses = {SingerMapper.class})
public interface AlbumsMapper extends EntityMapper<AlbumsDTO, Albums> {
@Mapping(source = "singerr.id", target = "singerrId")
@Mapping(source = "singerr.fname", target = "singerrFname")
AlbumsDTO toDto(Albums albums);
@Mapping(source = "singerrId", target = "singerr")
Albums toEntity(AlbumsDTO albumsDTO);
default Albums fromId(Long id) {
if (id == null) {
return null;
}
Albums albums = new Albums();
albums.setId(id);
return albums;
}
}
<file_sep>import { Component } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager } from 'ng-jhipster';
import { IAlbums } from 'app/shared/model/albums.model';
import { AlbumsService } from './albums.service';
@Component({
templateUrl: './albums-delete-dialog.component.html',
})
export class AlbumsDeleteDialogComponent {
albums?: IAlbums;
constructor(protected albumsService: AlbumsService, public activeModal: NgbActiveModal, protected eventManager: JhiEventManager) {}
cancel(): void {
this.activeModal.dismiss();
}
confirmDelete(id: number): void {
this.albumsService.delete(id).subscribe(() => {
this.eventManager.broadcast('albumsListModification');
this.activeModal.close();
});
}
}
<file_sep>package com.tp.soa.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.io.Serializable;
/**
* A Albums.
*/
@Entity
@Table(name = "albums")
public class Albums implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "title")
private String title;
@Column(name = "type")
private String type;
@ManyToOne
@JsonIgnoreProperties(value = "albums", allowSetters = true)
private Singer singerr;
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public Albums title(String title) {
this.title = title;
return this;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public Albums type(String type) {
this.type = type;
return this;
}
public void setType(String type) {
this.type = type;
}
public Singer getSingerr() {
return singerr;
}
public Albums singerr(Singer singer) {
this.singerr = singer;
return this;
}
public void setSingerr(Singer singer) {
this.singerr = singer;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Albums)) {
return false;
}
return id != null && id.equals(((Albums) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "Albums{" +
"id=" + getId() +
", title='" + getTitle() + "'" +
", type='" + getType() + "'" +
"}";
}
}
<file_sep>package com.tp.soa.service;
import com.tp.soa.service.dto.AlbumsDTO;
import java.util.List;
import java.util.Optional;
/**
* Service Interface for managing {@link com.tp.soa.domain.Albums}.
*/
public interface AlbumsService {
/**
* Save a albums.
*
* @param albumsDTO the entity to save.
* @return the persisted entity.
*/
AlbumsDTO save(AlbumsDTO albumsDTO);
/**
* Get all the albums.
*
* @return the list of entities.
*/
List<AlbumsDTO> findAll();
/**
* Get the "id" albums.
*
* @param id the id of the entity.
* @return the entity.
*/
Optional<AlbumsDTO> findOne(Long id);
/**
* Delete the "id" albums.
*
* @param id the id of the entity.
*/
void delete(Long id);
}
<file_sep>package com.tp.soa.web.rest;
import com.tp.soa.TpKhApp;
import com.tp.soa.domain.Albums;
import com.tp.soa.repository.AlbumsRepository;
import com.tp.soa.service.AlbumsService;
import com.tp.soa.service.dto.AlbumsDTO;
import com.tp.soa.service.mapper.AlbumsMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@link AlbumsResource} REST controller.
*/
@SpringBootTest(classes = TpKhApp.class)
@AutoConfigureMockMvc
@WithMockUser
public class AlbumsResourceIT {
private static final String DEFAULT_TITLE = "AAAAAAAAAA";
private static final String UPDATED_TITLE = "BBBBBBBBBB";
private static final String DEFAULT_TYPE = "AAAAAAAAAA";
private static final String UPDATED_TYPE = "BBBBBBBBBB";
@Autowired
private AlbumsRepository albumsRepository;
@Autowired
private AlbumsMapper albumsMapper;
@Autowired
private AlbumsService albumsService;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restAlbumsMockMvc;
private Albums albums;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Albums createEntity(EntityManager em) {
Albums albums = new Albums()
.title(DEFAULT_TITLE)
.type(DEFAULT_TYPE);
return albums;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Albums createUpdatedEntity(EntityManager em) {
Albums albums = new Albums()
.title(UPDATED_TITLE)
.type(UPDATED_TYPE);
return albums;
}
@BeforeEach
public void initTest() {
albums = createEntity(em);
}
@Test
@Transactional
public void createAlbums() throws Exception {
int databaseSizeBeforeCreate = albumsRepository.findAll().size();
// Create the Albums
AlbumsDTO albumsDTO = albumsMapper.toDto(albums);
restAlbumsMockMvc.perform(post("/api/albums")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(albumsDTO)))
.andExpect(status().isCreated());
// Validate the Albums in the database
List<Albums> albumsList = albumsRepository.findAll();
assertThat(albumsList).hasSize(databaseSizeBeforeCreate + 1);
Albums testAlbums = albumsList.get(albumsList.size() - 1);
assertThat(testAlbums.getTitle()).isEqualTo(DEFAULT_TITLE);
assertThat(testAlbums.getType()).isEqualTo(DEFAULT_TYPE);
}
@Test
@Transactional
public void createAlbumsWithExistingId() throws Exception {
int databaseSizeBeforeCreate = albumsRepository.findAll().size();
// Create the Albums with an existing ID
albums.setId(1L);
AlbumsDTO albumsDTO = albumsMapper.toDto(albums);
// An entity with an existing ID cannot be created, so this API call must fail
restAlbumsMockMvc.perform(post("/api/albums")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(albumsDTO)))
.andExpect(status().isBadRequest());
// Validate the Albums in the database
List<Albums> albumsList = albumsRepository.findAll();
assertThat(albumsList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllAlbums() throws Exception {
// Initialize the database
albumsRepository.saveAndFlush(albums);
// Get all the albumsList
restAlbumsMockMvc.perform(get("/api/albums?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(albums.getId().intValue())))
.andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE)))
.andExpect(jsonPath("$.[*].type").value(hasItem(DEFAULT_TYPE)));
}
@Test
@Transactional
public void getAlbums() throws Exception {
// Initialize the database
albumsRepository.saveAndFlush(albums);
// Get the albums
restAlbumsMockMvc.perform(get("/api/albums/{id}", albums.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(albums.getId().intValue()))
.andExpect(jsonPath("$.title").value(DEFAULT_TITLE))
.andExpect(jsonPath("$.type").value(DEFAULT_TYPE));
}
@Test
@Transactional
public void getNonExistingAlbums() throws Exception {
// Get the albums
restAlbumsMockMvc.perform(get("/api/albums/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateAlbums() throws Exception {
// Initialize the database
albumsRepository.saveAndFlush(albums);
int databaseSizeBeforeUpdate = albumsRepository.findAll().size();
// Update the albums
Albums updatedAlbums = albumsRepository.findById(albums.getId()).get();
// Disconnect from session so that the updates on updatedAlbums are not directly saved in db
em.detach(updatedAlbums);
updatedAlbums
.title(UPDATED_TITLE)
.type(UPDATED_TYPE);
AlbumsDTO albumsDTO = albumsMapper.toDto(updatedAlbums);
restAlbumsMockMvc.perform(put("/api/albums")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(albumsDTO)))
.andExpect(status().isOk());
// Validate the Albums in the database
List<Albums> albumsList = albumsRepository.findAll();
assertThat(albumsList).hasSize(databaseSizeBeforeUpdate);
Albums testAlbums = albumsList.get(albumsList.size() - 1);
assertThat(testAlbums.getTitle()).isEqualTo(UPDATED_TITLE);
assertThat(testAlbums.getType()).isEqualTo(UPDATED_TYPE);
}
@Test
@Transactional
public void updateNonExistingAlbums() throws Exception {
int databaseSizeBeforeUpdate = albumsRepository.findAll().size();
// Create the Albums
AlbumsDTO albumsDTO = albumsMapper.toDto(albums);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restAlbumsMockMvc.perform(put("/api/albums")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(albumsDTO)))
.andExpect(status().isBadRequest());
// Validate the Albums in the database
List<Albums> albumsList = albumsRepository.findAll();
assertThat(albumsList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteAlbums() throws Exception {
// Initialize the database
albumsRepository.saveAndFlush(albums);
int databaseSizeBeforeDelete = albumsRepository.findAll().size();
// Delete the albums
restAlbumsMockMvc.perform(delete("/api/albums/{id}", albums.getId())
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<Albums> albumsList = albumsRepository.findAll();
assertThat(albumsList).hasSize(databaseSizeBeforeDelete - 1);
}
}
<file_sep>/**
* Spring MVC REST controllers.
*/
package com.tp.soa.web.rest;
<file_sep>package com.tp.soa.service.dto;
import java.io.Serializable;
/**
* A DTO for the {@link com.tp.soa.domain.Albums} entity.
*/
public class AlbumsDTO implements Serializable {
private Long id;
private String title;
private String type;
private Long singerrId;
private String singerrFname;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getSingerrId() {
return singerrId;
}
public void setSingerrId(Long singerId) {
this.singerrId = singerId;
}
public String getSingerrFname() {
return singerrFname;
}
public void setSingerrFname(String singerFname) {
this.singerrFname = singerFname;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AlbumsDTO)) {
return false;
}
return id != null && id.equals(((AlbumsDTO) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "AlbumsDTO{" +
"id=" + getId() +
", title='" + getTitle() + "'" +
", type='" + getType() + "'" +
", singerrId=" + getSingerrId() +
", singerrFname='" + getSingerrFname() + "'" +
"}";
}
}
<file_sep>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { HttpHeaders, HttpResponse } from '@angular/common/http';
import { TpKhTestModule } from '../../../test.module';
import { SingerComponent } from 'app/entities/singer/singer.component';
import { SingerService } from 'app/entities/singer/singer.service';
import { Singer } from 'app/shared/model/singer.model';
describe('Component Tests', () => {
describe('Singer Management Component', () => {
let comp: SingerComponent;
let fixture: ComponentFixture<SingerComponent>;
let service: SingerService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TpKhTestModule],
declarations: [SingerComponent],
})
.overrideTemplate(SingerComponent, '')
.compileComponents();
fixture = TestBed.createComponent(SingerComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(SingerService);
});
it('Should call load all on init', () => {
// GIVEN
const headers = new HttpHeaders().append('link', 'link;link');
spyOn(service, 'query').and.returnValue(
of(
new HttpResponse({
body: [new Singer(123)],
headers,
})
)
);
// WHEN
comp.ngOnInit();
// THEN
expect(service.query).toHaveBeenCalled();
expect(comp.singers && comp.singers[0]).toEqual(jasmine.objectContaining({ id: 123 }));
});
});
});
<file_sep>import { Component } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager } from 'ng-jhipster';
import { ISinger } from 'app/shared/model/singer.model';
import { SingerService } from './singer.service';
@Component({
templateUrl: './singer-delete-dialog.component.html',
})
export class SingerDeleteDialogComponent {
singer?: ISinger;
constructor(protected singerService: SingerService, public activeModal: NgbActiveModal, protected eventManager: JhiEventManager) {}
cancel(): void {
this.activeModal.dismiss();
}
confirmDelete(id: number): void {
this.singerService.delete(id).subscribe(() => {
this.eventManager.broadcast('singerListModification');
this.activeModal.close();
});
}
}
<file_sep>import { IAlbums } from 'app/shared/model/albums.model';
export interface ISinger {
id?: number;
fname?: string;
lname?: string;
adress?: string;
avoir_albums?: IAlbums[];
}
export class Singer implements ISinger {
constructor(public id?: number, public fname?: string, public lname?: string, public adress?: string, public avoir_albums?: IAlbums[]) {}
}
<file_sep>import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { TpKhSharedModule } from 'app/shared/shared.module';
import { AlbumsComponent } from './albums.component';
import { AlbumsDetailComponent } from './albums-detail.component';
import { AlbumsUpdateComponent } from './albums-update.component';
import { AlbumsDeleteDialogComponent } from './albums-delete-dialog.component';
import { albumsRoute } from './albums.route';
@NgModule({
imports: [TpKhSharedModule, RouterModule.forChild(albumsRoute)],
declarations: [AlbumsComponent, AlbumsDetailComponent, AlbumsUpdateComponent, AlbumsDeleteDialogComponent],
entryComponents: [AlbumsDeleteDialogComponent],
})
export class TpKhAlbumsModule {}
<file_sep>package com.tp.soa.service.impl;
import com.tp.soa.service.SingerService;
import com.tp.soa.domain.Singer;
import com.tp.soa.repository.SingerRepository;
import com.tp.soa.service.dto.SingerDTO;
import com.tp.soa.service.mapper.SingerMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Service Implementation for managing {@link Singer}.
*/
@Service
@Transactional
public class SingerServiceImpl implements SingerService {
private final Logger log = LoggerFactory.getLogger(SingerServiceImpl.class);
private final SingerRepository singerRepository;
private final SingerMapper singerMapper;
public SingerServiceImpl(SingerRepository singerRepository, SingerMapper singerMapper) {
this.singerRepository = singerRepository;
this.singerMapper = singerMapper;
}
@Override
public SingerDTO save(SingerDTO singerDTO) {
log.debug("Request to save Singer : {}", singerDTO);
Singer singer = singerMapper.toEntity(singerDTO);
singer = singerRepository.save(singer);
return singerMapper.toDto(singer);
}
@Override
@Transactional(readOnly = true)
public List<SingerDTO> findAll() {
log.debug("Request to get all Singers");
return singerRepository.findAll().stream()
.map(singerMapper::toDto)
.collect(Collectors.toCollection(LinkedList::new));
}
@Override
@Transactional(readOnly = true)
public Optional<SingerDTO> findOne(Long id) {
log.debug("Request to get Singer : {}", id);
return singerRepository.findById(id)
.map(singerMapper::toDto);
}
@Override
public void delete(Long id) {
log.debug("Request to delete Singer : {}", id);
singerRepository.deleteById(id);
}
}
<file_sep>/**
* Audit specific code.
*/
package com.tp.soa.config.audit;
<file_sep>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { HttpHeaders, HttpResponse } from '@angular/common/http';
import { TpKhTestModule } from '../../../test.module';
import { AlbumsComponent } from 'app/entities/albums/albums.component';
import { AlbumsService } from 'app/entities/albums/albums.service';
import { Albums } from 'app/shared/model/albums.model';
describe('Component Tests', () => {
describe('Albums Management Component', () => {
let comp: AlbumsComponent;
let fixture: ComponentFixture<AlbumsComponent>;
let service: AlbumsService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TpKhTestModule],
declarations: [AlbumsComponent],
})
.overrideTemplate(AlbumsComponent, '')
.compileComponents();
fixture = TestBed.createComponent(AlbumsComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(AlbumsService);
});
it('Should call load all on init', () => {
// GIVEN
const headers = new HttpHeaders().append('link', 'link;link');
spyOn(service, 'query').and.returnValue(
of(
new HttpResponse({
body: [new Albums(123)],
headers,
})
)
);
// WHEN
comp.ngOnInit();
// THEN
expect(service.query).toHaveBeenCalled();
expect(comp.albums && comp.albums[0]).toEqual(jasmine.objectContaining({ id: 123 }));
});
});
});
<file_sep>/**
* Spring Framework configuration files.
*/
package com.tp.soa.config;
<file_sep>package com.tp.soa.repository;
import com.tp.soa.domain.Albums;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the Albums entity.
*/
@SuppressWarnings("unused")
@Repository
public interface AlbumsRepository extends JpaRepository<Albums, Long> {
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ISinger } from 'app/shared/model/singer.model';
@Component({
selector: 'jhi-singer-detail',
templateUrl: './singer-detail.component.html',
})
export class SingerDetailComponent implements OnInit {
singer: ISinger | null = null;
constructor(protected activatedRoute: ActivatedRoute) {}
ngOnInit(): void {
this.activatedRoute.data.subscribe(({ singer }) => (this.singer = singer));
}
previousState(): void {
window.history.back();
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { Resolve, ActivatedRouteSnapshot, Routes, Router } from '@angular/router';
import { Observable, of, EMPTY } from 'rxjs';
import { flatMap } from 'rxjs/operators';
import { Authority } from 'app/shared/constants/authority.constants';
import { UserRouteAccessService } from 'app/core/auth/user-route-access-service';
import { IAlbums, Albums } from 'app/shared/model/albums.model';
import { AlbumsService } from './albums.service';
import { AlbumsComponent } from './albums.component';
import { AlbumsDetailComponent } from './albums-detail.component';
import { AlbumsUpdateComponent } from './albums-update.component';
@Injectable({ providedIn: 'root' })
export class AlbumsResolve implements Resolve<IAlbums> {
constructor(private service: AlbumsService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot): Observable<IAlbums> | Observable<never> {
const id = route.params['id'];
if (id) {
return this.service.find(id).pipe(
flatMap((albums: HttpResponse<Albums>) => {
if (albums.body) {
return of(albums.body);
} else {
this.router.navigate(['404']);
return EMPTY;
}
})
);
}
return of(new Albums());
}
}
export const albumsRoute: Routes = [
{
path: '',
component: AlbumsComponent,
data: {
authorities: [Authority.USER],
pageTitle: 'Albums',
},
canActivate: [UserRouteAccessService],
},
{
path: ':id/view',
component: AlbumsDetailComponent,
resolve: {
albums: AlbumsResolve,
},
data: {
authorities: [Authority.USER],
pageTitle: 'Albums',
},
canActivate: [UserRouteAccessService],
},
{
path: 'new',
component: AlbumsUpdateComponent,
resolve: {
albums: AlbumsResolve,
},
data: {
authorities: [Authority.USER],
pageTitle: 'Albums',
},
canActivate: [UserRouteAccessService],
},
{
path: ':id/edit',
component: AlbumsUpdateComponent,
resolve: {
albums: AlbumsResolve,
},
data: {
authorities: [Authority.USER],
pageTitle: 'Albums',
},
canActivate: [UserRouteAccessService],
},
];
<file_sep>import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { IAlbums, Albums } from 'app/shared/model/albums.model';
import { AlbumsService } from './albums.service';
import { ISinger } from 'app/shared/model/singer.model';
import { SingerService } from 'app/entities/singer/singer.service';
@Component({
selector: 'jhi-albums-update',
templateUrl: './albums-update.component.html',
})
export class AlbumsUpdateComponent implements OnInit {
isSaving = false;
singers: ISinger[] = [];
editForm = this.fb.group({
id: [],
title: [],
type: [],
singerrId: [],
});
constructor(
protected albumsService: AlbumsService,
protected singerService: SingerService,
protected activatedRoute: ActivatedRoute,
private fb: FormBuilder
) {}
ngOnInit(): void {
this.activatedRoute.data.subscribe(({ albums }) => {
this.updateForm(albums);
this.singerService.query().subscribe((res: HttpResponse<ISinger[]>) => (this.singers = res.body || []));
});
}
updateForm(albums: IAlbums): void {
this.editForm.patchValue({
id: albums.id,
title: albums.title,
type: albums.type,
singerrId: albums.singerrId,
});
}
previousState(): void {
window.history.back();
}
save(): void {
this.isSaving = true;
const albums = this.createFromForm();
if (albums.id !== undefined) {
this.subscribeToSaveResponse(this.albumsService.update(albums));
} else {
this.subscribeToSaveResponse(this.albumsService.create(albums));
}
}
private createFromForm(): IAlbums {
return {
...new Albums(),
id: this.editForm.get(['id'])!.value,
title: this.editForm.get(['title'])!.value,
type: this.editForm.get(['type'])!.value,
singerrId: this.editForm.get(['singerrId'])!.value,
};
}
protected subscribeToSaveResponse(result: Observable<HttpResponse<IAlbums>>): void {
result.subscribe(
() => this.onSaveSuccess(),
() => this.onSaveError()
);
}
protected onSaveSuccess(): void {
this.isSaving = false;
this.previousState();
}
protected onSaveError(): void {
this.isSaving = false;
}
trackById(index: number, item: ISinger): any {
return item.id;
}
}
<file_sep>package com.tp.soa.domain;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import com.tp.soa.web.rest.TestUtil;
public class AlbumsTest {
@Test
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Albums.class);
Albums albums1 = new Albums();
albums1.setId(1L);
Albums albums2 = new Albums();
albums2.setId(albums1.getId());
assertThat(albums1).isEqualTo(albums2);
albums2.setId(2L);
assertThat(albums1).isNotEqualTo(albums2);
albums1.setId(null);
assertThat(albums1).isNotEqualTo(albums2);
}
}
<file_sep>package com.tp.soa.service.mapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class AlbumsMapperTest {
private AlbumsMapper albumsMapper;
@BeforeEach
public void setUp() {
albumsMapper = new AlbumsMapperImpl();
}
@Test
public void testEntityFromId() {
Long id = 1L;
assertThat(albumsMapper.fromId(id).getId()).isEqualTo(id);
assertThat(albumsMapper.fromId(null)).isNull();
}
}
<file_sep>package com.tp.soa.service.impl;
import com.tp.soa.service.AlbumsService;
import com.tp.soa.domain.Albums;
import com.tp.soa.repository.AlbumsRepository;
import com.tp.soa.service.dto.AlbumsDTO;
import com.tp.soa.service.mapper.AlbumsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Service Implementation for managing {@link Albums}.
*/
@Service
@Transactional
public class AlbumsServiceImpl implements AlbumsService {
private final Logger log = LoggerFactory.getLogger(AlbumsServiceImpl.class);
private final AlbumsRepository albumsRepository;
private final AlbumsMapper albumsMapper;
public AlbumsServiceImpl(AlbumsRepository albumsRepository, AlbumsMapper albumsMapper) {
this.albumsRepository = albumsRepository;
this.albumsMapper = albumsMapper;
}
@Override
public AlbumsDTO save(AlbumsDTO albumsDTO) {
log.debug("Request to save Albums : {}", albumsDTO);
Albums albums = albumsMapper.toEntity(albumsDTO);
albums = albumsRepository.save(albums);
return albumsMapper.toDto(albums);
}
@Override
@Transactional(readOnly = true)
public List<AlbumsDTO> findAll() {
log.debug("Request to get all Albums");
return albumsRepository.findAll().stream()
.map(albumsMapper::toDto)
.collect(Collectors.toCollection(LinkedList::new));
}
@Override
@Transactional(readOnly = true)
public Optional<AlbumsDTO> findOne(Long id) {
log.debug("Request to get Albums : {}", id);
return albumsRepository.findById(id)
.map(albumsMapper::toDto);
}
@Override
public void delete(Long id) {
log.debug("Request to delete Albums : {}", id);
albumsRepository.deleteById(id);
}
}
<file_sep>export interface IAlbums {
id?: number;
title?: string;
type?: string;
singerrFname?: string;
singerrId?: number;
}
export class Albums implements IAlbums {
constructor(public id?: number, public title?: string, public type?: string, public singerrFname?: string, public singerrId?: number) {}
}
<file_sep>package com.tp.soa.web.rest;
import com.tp.soa.TpKhApp;
import com.tp.soa.domain.Singer;
import com.tp.soa.repository.SingerRepository;
import com.tp.soa.service.SingerService;
import com.tp.soa.service.dto.SingerDTO;
import com.tp.soa.service.mapper.SingerMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@link SingerResource} REST controller.
*/
@SpringBootTest(classes = TpKhApp.class)
@AutoConfigureMockMvc
@WithMockUser
public class SingerResourceIT {
private static final String DEFAULT_FNAME = "AAAAAAAAAA";
private static final String UPDATED_FNAME = "BBBBBBBBBB";
private static final String DEFAULT_LNAME = "AAAAAAAAAA";
private static final String UPDATED_LNAME = "BBBBBBBBBB";
private static final String DEFAULT_ADRESS = "AAAAAAAAAA";
private static final String UPDATED_ADRESS = "BBBBBBBBBB";
@Autowired
private SingerRepository singerRepository;
@Autowired
private SingerMapper singerMapper;
@Autowired
private SingerService singerService;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restSingerMockMvc;
private Singer singer;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Singer createEntity(EntityManager em) {
Singer singer = new Singer()
.fname(DEFAULT_FNAME)
.lname(DEFAULT_LNAME)
.adress(DEFAULT_ADRESS);
return singer;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Singer createUpdatedEntity(EntityManager em) {
Singer singer = new Singer()
.fname(UPDATED_FNAME)
.lname(UPDATED_LNAME)
.adress(UPDATED_ADRESS);
return singer;
}
@BeforeEach
public void initTest() {
singer = createEntity(em);
}
@Test
@Transactional
public void createSinger() throws Exception {
int databaseSizeBeforeCreate = singerRepository.findAll().size();
// Create the Singer
SingerDTO singerDTO = singerMapper.toDto(singer);
restSingerMockMvc.perform(post("/api/singers")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(singerDTO)))
.andExpect(status().isCreated());
// Validate the Singer in the database
List<Singer> singerList = singerRepository.findAll();
assertThat(singerList).hasSize(databaseSizeBeforeCreate + 1);
Singer testSinger = singerList.get(singerList.size() - 1);
assertThat(testSinger.getFname()).isEqualTo(DEFAULT_FNAME);
assertThat(testSinger.getLname()).isEqualTo(DEFAULT_LNAME);
assertThat(testSinger.getAdress()).isEqualTo(DEFAULT_ADRESS);
}
@Test
@Transactional
public void createSingerWithExistingId() throws Exception {
int databaseSizeBeforeCreate = singerRepository.findAll().size();
// Create the Singer with an existing ID
singer.setId(1L);
SingerDTO singerDTO = singerMapper.toDto(singer);
// An entity with an existing ID cannot be created, so this API call must fail
restSingerMockMvc.perform(post("/api/singers")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(singerDTO)))
.andExpect(status().isBadRequest());
// Validate the Singer in the database
List<Singer> singerList = singerRepository.findAll();
assertThat(singerList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllSingers() throws Exception {
// Initialize the database
singerRepository.saveAndFlush(singer);
// Get all the singerList
restSingerMockMvc.perform(get("/api/singers?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(singer.getId().intValue())))
.andExpect(jsonPath("$.[*].fname").value(hasItem(DEFAULT_FNAME)))
.andExpect(jsonPath("$.[*].lname").value(hasItem(DEFAULT_LNAME)))
.andExpect(jsonPath("$.[*].adress").value(hasItem(DEFAULT_ADRESS)));
}
@Test
@Transactional
public void getSinger() throws Exception {
// Initialize the database
singerRepository.saveAndFlush(singer);
// Get the singer
restSingerMockMvc.perform(get("/api/singers/{id}", singer.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(singer.getId().intValue()))
.andExpect(jsonPath("$.fname").value(DEFAULT_FNAME))
.andExpect(jsonPath("$.lname").value(DEFAULT_LNAME))
.andExpect(jsonPath("$.adress").value(DEFAULT_ADRESS));
}
@Test
@Transactional
public void getNonExistingSinger() throws Exception {
// Get the singer
restSingerMockMvc.perform(get("/api/singers/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateSinger() throws Exception {
// Initialize the database
singerRepository.saveAndFlush(singer);
int databaseSizeBeforeUpdate = singerRepository.findAll().size();
// Update the singer
Singer updatedSinger = singerRepository.findById(singer.getId()).get();
// Disconnect from session so that the updates on updatedSinger are not directly saved in db
em.detach(updatedSinger);
updatedSinger
.fname(UPDATED_FNAME)
.lname(UPDATED_LNAME)
.adress(UPDATED_ADRESS);
SingerDTO singerDTO = singerMapper.toDto(updatedSinger);
restSingerMockMvc.perform(put("/api/singers")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(singerDTO)))
.andExpect(status().isOk());
// Validate the Singer in the database
List<Singer> singerList = singerRepository.findAll();
assertThat(singerList).hasSize(databaseSizeBeforeUpdate);
Singer testSinger = singerList.get(singerList.size() - 1);
assertThat(testSinger.getFname()).isEqualTo(UPDATED_FNAME);
assertThat(testSinger.getLname()).isEqualTo(UPDATED_LNAME);
assertThat(testSinger.getAdress()).isEqualTo(UPDATED_ADRESS);
}
@Test
@Transactional
public void updateNonExistingSinger() throws Exception {
int databaseSizeBeforeUpdate = singerRepository.findAll().size();
// Create the Singer
SingerDTO singerDTO = singerMapper.toDto(singer);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restSingerMockMvc.perform(put("/api/singers")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(singerDTO)))
.andExpect(status().isBadRequest());
// Validate the Singer in the database
List<Singer> singerList = singerRepository.findAll();
assertThat(singerList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteSinger() throws Exception {
// Initialize the database
singerRepository.saveAndFlush(singer);
int databaseSizeBeforeDelete = singerRepository.findAll().size();
// Delete the singer
restSingerMockMvc.perform(delete("/api/singers/{id}", singer.getId())
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<Singer> singerList = singerRepository.findAll();
assertThat(singerList).hasSize(databaseSizeBeforeDelete - 1);
}
}
| 43b86fe6013d38a7c193ea775423ee89fd873d4a | [
"Java",
"TypeScript"
]
| 25 | TypeScript | khawlaakermi/jhipster_crud | 514a5b406de99784a1795d016b53de124f527ebd | e622bb9817c9c05427aa38e2785bf30efff56af1 |
refs/heads/master | <file_sep>package main
import (
"fmt"
"os"
"github.com/rg-devel/lumo"
"github.com/urfave/cli"
log "github.com/Sirupsen/logrus"
)
func init() {
log.SetFormatter(&log.TextFormatter{
TimestampFormat: "2006-01-02T15:04:05.000",
FullTimestamp: true,
})
}
func main() {
log.SetOutput(os.Stdout)
log.WithFields(log.Fields{
"string field": "string value",
"number": 1,
}).Info("starting lumo")
log.Warn("warning message without fields")
app := cli.NewApp()
app.Name = "lumo"
app.Version = "0.0.1"
app.Usage = "Log parser in Go"
app.Commands = []cli.Command{
{
Name: "list",
Aliases: []string{"l"},
Usage: "list jobs",
Description: "List jobs filtered by the arguments",
Subcommands: []cli.Command{
{
Name: "all",
Aliases: []string{"a"},
Usage: "list all jobs",
Description: "List all jobs in the log(s)",
Flags: []cli.Flag{
cli.StringFlag{
Name: "name",
Value: "Bob",
Usage: "Name of the person to greet",
},
},
Action: func(c *cli.Context) error {
fmt.Println("Hello,", c.String("name"))
return nil
},
},
},
},{
Name: "show",
Usage: "show details",
Description: "Show details of the arguments",
Subcommands: []cli.Command{
{
Name: "job",
Aliases: []string{"a"},
Usage: "show all entries of a given job",
Description: "List all entries related to a given job",
Flags: []cli.Flag{
cli.IntFlag{
Name: "id",
Value: 0,
Usage: "Job ID",
},
},
Action: func(c *cli.Context) error {
fmt.Printf("This is where all the entries for job ID %d is displayed", c.Int("id"))
return nil
},
},
},
Action: func(c *cli.Context) error {
fmt.Printf("the next example")
return nil
},
},
}
app.Action = func(c *cli.Context) error {
fmt.Printf("Hello %q\n", c.Args().Get(0))
err := lumo.Foo()
if err != nil {
return err
}
fmt.Println("done")
return nil
}
_ = app.Run(os.Args)
}
<file_sep>package lumo
import (
"fmt"
"time"
)
// Foo is my foo function
func Foo() error {
fmt.Println("in Foo")
time.Sleep(2 * time.Second)
return nil
}
<file_sep># Lumo
Lumo is an lumo app.
This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code.
We appreciate your contribution. Please refer to our [contributing guidelines](CONTRIBUTING.md).
[](https://github.com/rg-devel/lumo/releases/latest)
[](LICENSE.md)
[](https://travis-ci.org/rg-devel/lumo)
[](https://codecov.io/gh/rg-devel/lumo)
[](http://godoc.org/github.com/rg-devel/lumo)
[](https://goreportcard.com/report/github.com/rg-devel/lumo)
[](https://saythanks.io/to/caarlos0)
[](https://github.com/goreleaser)
| fd6f85fd2418bd13ea325a63d981f7aa21d30db7 | [
"Markdown",
"Go"
]
| 3 | Go | rg-devel/lumo | 06ad23b2ba41071652919e71f59b0704796d609a | cd91228b19b70f9a21a87e5c64f28ae42ebe7a29 |
refs/heads/master | <file_sep>==============
girder_jupyter
==============
|build-status| |pypi-version| |pypi-status|
The Jupyter Notebook web application provides a graphical interface for creating, opening, renaming, and deleting files in a virtual filesystem. `girder_jupyter <https://github.com/girder/girder_jupyter>`__ is a python package that implements a `contents manager <http://jupyter-notebook.readthedocs.io/en/latest/extending/contents.html>`_
to allow Girder to become a backend for this virtual filesystem. This allows notebooks and files to be stored
in a Girder server from within Jupyter.
Getting Started
===============
Install the package in the Python environment you are running your Jupyter server in:
.. code-block:: bash
pip install girder-jupyter
Add the following options to your :code:`jupyter_notebook_config.py`
.. code-block:: python
c.NotebookApp.contents_manager_class = 'girder_jupyter.contents.manager.GirderContentsManager'
c.GirderContentsManager.api_key = '<api key>'
c.GirderContentsManager.api_url = '<api url>'
Where :code:`<api key>` is replaced with a `Girder API key <https://girder.readthedocs.io/en/latest/user-guide.html?highlight=API%20Key#api-keys>`__ for the Girder server and :code:`<api url>` is the URL to Girder instance you want
to use for example http://localhost:8080/api/v1.
Configuration Parameters
========================
- :code:`api_url` - An API URL for the Girder server. Defaults to 'http://localhost:8080/api/v1'
- :code:`api_key` -A `Girder API key <https://girder.readthedocs.io/en/latest/user-guide.html?highlight=API%20Key#api-keys>`__ key for the Girder server at :code:`api_url`. The key should have read and write permission scope.
- :code:`token` - A Girder token for the Girder server at :code:`api_url`. This parameter is particularly useful when running instances from JupyterHub.
- :code:`root` - The root in the Girder hierarchy to use as the content managers root. This path can include :code:`{login}` which will be replace with the current users login. Defaults to :code:`'user/{login}'`
Note that either :code:`api_key` or :code:`token` must be provided for the contents manager to be able to
authenticate with the Girder server.
.. |build-status| image:: https://circleci.com/gh/girder/girder_jupyter.png?style=shield
:target: https://circleci.com/gh/girder/girder_jupyter
:alt: Build Status
.. |pypi-version| image:: https://img.shields.io/pypi/v/girder-jupyter.svg
:target: https://pypi.python.org/pypi/girder-jupyter/
:alt: PyPI version
.. |pypi-status| image:: https://img.shields.io/pypi/status/girder-jupyter.svg
:target: https://pypi.python.org/pypi/girder-jupyter/
:alt: PyPI status
<file_sep>from notebook.services.contents.tests.test_contents_api import APITest, Config
import girder_client
from six import BytesIO
import os
import json
from .constants import GIRDER_API_URL
class GirderContentsTest(APITest):
gc = girder_client.GirderClient(apiUrl=GIRDER_API_URL)
def _get_girder_path(self, path):
return ('/user/%s/Private/%s' % (self.user['login'],
path.lstrip('/'))).rstrip('/')
@classmethod
def setup_class(cls):
cls.config = Config()
cls.config.NotebookApp.ip = '127.0.0.1'
cls.config.NotebookApp.contents_manager_class =\
'girder_jupyter.contents.manager.GirderContentsManager'
if 'GIRDER_API_KEY' in os.environ:
api_key = os.environ['GIRDER_API_KEY']
cls.config.GirderContentsManager.api_key = api_key
cls.gc.authenticate(apiKey=api_key)
elif 'GIRDER_USER' in os.environ and 'GIRDER_PASSWORD' in os.environ:
user = os.environ['GIRDER_USER']
password = <PASSWORD>['<PASSWORD>']
cls.gc.authenticate(user, password)
cls.config.GirderContentsManager.token = cls.gc.token
else:
raise Exception('No Girder credentials configured.')
cls.config.GirderContentsManager.root = 'user/{login}/Private'
cls.user = cls.gc.get('user/me')
super(APITest, cls).setup_class()
def delete_dir(self, path):
path = self._get_girder_path(path)
resource = self._resource(path)
if resource is not None:
self.gc.delete('folder/{}'.format(resource['_id']))
def delete_file(self, path):
path = self._get_girder_path(path)
resource = self._resource(path)
if resource is not None:
self.gc.delete('item/{}'.format(resource['_id']))
def isdir(self, path):
path = self._get_girder_path(path)
resource = self._resource(path)
return self._is_type(resource, model_type=['folder', 'item'])
def isfile(self, path):
path = self._get_girder_path(path)
resource = self._resource(path)
if self._is_type(resource, model_type=['item']):
resource = self._resource(os.path.join(path, os.path.basename(path)))
return self._is_type(resource, model_type=['file'])
return False
def _is_type(self, resource, model_type):
if resource is None:
return False
if not isinstance(model_type, list):
model_type = list(model_type)
return resource['_modelType'] in model_type
def _resource(self, path):
try:
return self.gc.resourceLookup(path)
except girder_client.HttpError:
return None
def make_root_dir(self, name):
return self.gc.createFolder(self.user['_id'], name, parentType='user')
def _get_or_create_folder_parent(self, path):
"""
Get the parent directory of a specific path.
If needed, create all the required intermediate folders.
"""
parent_path = os.path.dirname(path.lstrip('/').rstrip('/'))
parent = self._resource(self._get_girder_path(parent_path))
if parent is None:
grandpa = self._get_or_create_folder_parent(parent_path)
parent = self.gc.createFolder(grandpa['_id'],
os.path.basename(parent_path),
parentType=grandpa['_modelType'])
elif parent['_modelType'] not in ['user', 'folder']:
self.fail('Permission denied: %s' % parent_path)
return parent
def _get_or_create_file_parent(self, path):
# an item is an acceptable parent type only for a file
# and only at the first iteration
parent_path, name = os.path.split(path.lstrip('/').rstrip('/'))
resource = self._resource(self._get_girder_path(path))
if resource is None:
grandpa = self._get_or_create_dir(parent_path)
parent = self.gc.createItem(grandpa['_id'], name)
return parent
elif resource['_modelType'] == 'item':
return resource
elif resource['_modelType'] == 'file':
self.fail('Only an item can contain a file')
elif resource['_modelType'] == 'folder':
self.fail('Only an item can contain a file')
def make_dir(self, path):
"""
Create all necessary folder for a given path.
"""
parent = self._get_or_create_folder_parent(path)
folder = self.gc.createFolder(parent['_id'], os.path.basename(path),
parentType=parent['_modelType'])
return folder
def _get_or_create_dir(self, path):
resource = self._resource(self._get_girder_path(path))
if resource is None:
return self.make_dir(path)
elif resource['_modelType'] != 'folder':
self.fail('The requested resource is not a folder %s' % path)
else:
return resource
def make_txt(self, path, content):
parent = self._get_or_create_file_parent(path)
content = content.encode('utf8')
size = len(content)
stream = BytesIO(content)
self.gc.uploadFile(parent['_id'], stream, os.path.basename(path), size)
def make_blob(self, path, content):
parent = self._get_or_create_file_parent(path)
# content = content.encode('utf8')
size = len(content)
stream = BytesIO(content)
self.gc.uploadFile(parent['_id'], stream, os.path.basename(path), size)
def make_nb(self, path, nb):
"""Make a notebook file at a given api_path"""
content = json.dumps(nb, indent=2)
self.make_txt(path, content)
<file_sep>GIRDER_API_URL = 'http://localhost:8080/api/v1'
<file_sep>import os
from six import BytesIO
import dateutil
import base64
import nbformat
from notebook.services.contents.manager import ContentsManager
from notebook.services.contents.filecheckpoints import GenericFileCheckpoints
from traitlets import default, Unicode, Instance
from tornado import web
import girder_client
class GirderContentsManager(ContentsManager):
api_url = Unicode(
allow_none=True,
config=True,
help='A Girder API url.',
default_value='http://localhost:8080/api/v1'
)
api_key = Unicode(
allow_none=True,
config=True,
help='A Girder API key.',
default_value=None
)
token = Unicode(
allow_none=True,
config=True,
help='A Girder token.'
)
gc = Instance(girder_client.GirderClient)
root = Unicode(
allow_none=True,
config=True,
help='The root in the Girder hierarchy, defaults to user/<login>.'
'This path can include {login} which will be replace with the current users login.',
default_value='user/{login}'
)
@default('gc')
def _gc(self):
gc = girder_client.GirderClient(apiUrl=self.api_url)
if self.api_key is not None:
gc = girder_client.GirderClient(apiUrl=self.api_url)
gc.authenticate(apiKey=self.api_key)
elif self.token is not None:
gc.token = self.token
return gc
@default('checkpoints_class')
def _checkpoints_class(self):
return GenericFileCheckpoints
@default('checkpoints_kwargs')
def _checkpoints_kwargs(self):
home = os.path.expanduser('~')
return {
'root_dir': os.path.join(home, '.ipynb_checkpoints')
}
def _render_login(self, root):
if '{login}' in self.root:
me = self.gc.get('user/me')
# Replace {login} with users login.
try:
root = root.format(login=me['login'])
except KeyError:
pass
return root
def __init__(self, *args, **kwargs):
super(GirderContentsManager, self).__init__(*args, **kwargs)
# Render {login}
self.root = self._render_login(self.root)
def _resource(self, path):
try:
return self.gc.resourceLookup(path)
except girder_client.HttpError:
return None
def _resource_exists(self, path, model_type):
resource = self._resource(path)
return self._is_type(resource, model_type)
def _is_type(self, resource, model_types):
if resource is None:
return False
if not isinstance(model_types, list):
model_types = [model_types]
return resource['_modelType'] in model_types
def _is_folder(self, resource):
return self._is_type(resource, 'folder')
def _is_item(self, resource):
return self._is_type(resource, 'item')
def _is_user(self, resource):
return self._is_type(resource, 'user')
def _is_file(self, resource):
return self._is_type(resource, 'file')
def _file(self, path):
resource = self._resource(path)
name = path.split('/')[-1]
if self._is_item(resource):
return self._file_by_name(resource['_id'], name)
return None
def _file_by_name(self, item_id, name):
for file in self.gc.listFile(item_id):
if file['name'] == name:
return file
return None
def _list_resource(self, resource):
listing = []
if self._is_folder(resource):
params = {
'folderId': resource['_id']
}
listing += self.gc.get('item', params)
params = {
'parentId': resource['_id'],
'parentType': resource['_modelType']
}
listing += self.gc.get('folder', params)
return listing
def _get_girder_path(self, path):
return ('%s/%s' % (self.root, path)).rstrip('/')
def dir_exists(self, path):
"""Does a directory exist at the given path?
Like os.path.isdir
Parameters
----------
path : string
The path to check
Returns
-------
exists : bool
Whether the path does indeed exist.
"""
path = path.strip('/')
girder_path = self._get_girder_path(path)
return self._resource_exists(girder_path, ['folder', 'item', 'user'])
def is_hidden(self, path):
"""Is path a hidden directory or file?
Parameters
----------
path : string
The path to check. This is an API path (`/` separated,
relative to root dir).
Returns
-------
hidden : bool
Whether the path is hidden.
"""
return False
def file_exists(self, path=''):
"""Does a file exist at the given path?
Like os.path.isfile
Parameters
----------
path : string
The API path of a file to check for.
Returns
-------
exists : bool
Whether the file exists.
"""
path = path.strip('/')
girder_path = self._get_girder_path(path)
return self._file(girder_path) is not None
def _has_write_access(self, resource):
if self._is_folder(resource) or self._is_user(resource):
return resource['_accessLevel'] > 0
elif self._is_item(resource):
# Get the containing folder to check access
folder = self.gc.getFolder(resource['folderId'])
return self._has_write_access(folder)
elif self._is_file(resource):
# Get the containing item to check access
folder = self.gc.getItem(resource['itemId'])
return self._has_write_access(folder)
else:
# TODO Need to work out error reporting
raise Exception('Unexpected resource type: %s' % resource['_modelType'])
def _base_model(self, path, resource):
"""Build the common base of a contents model
Parameters
----------
path : string
The path to the resource
resource : dict
The Girder file or folder model
"""
created = resource['created']
updated = resource.get('updated', created)
# Create the base model.
model = {}
model['name'] = resource.get('name', resource.get('login'))
model['path'] = path
model['last_modified'] = dateutil.parser.parse(updated)
model['created'] = dateutil.parser.parse(created)
model['content'] = None
model['format'] = None
model['mimetype'] = None
model['writable'] = self._has_write_access(resource)
return model
def _dir_model(self, path, resource, content=True, format=None):
"""Build a model for a directory
if content is requested, will include a listing of the directory
"""
model = self._base_model(path, resource)
model['type'] = 'directory'
if content:
model['content'] = contents = []
for resource in self._list_resource(resource):
name = resource['name']
if self.should_list(name) and not name.startswith('.'):
contents.append(self._get(
'%s/%s' % (path, name), resource,
content=False, format=format)
)
model['format'] = 'json'
return model
def _file_model(self, path, file, content=True, format=None):
"""Build a model for a file
if content is requested, include the file contents.
format:
If 'text', the contents will be decoded as UTF-8.
If 'base64', the raw bytes contents will be encoded as base64.
If not specified, try to decode as UTF-8, and fall back to base64
"""
girder_path = self._get_girder_path(path)
model = self._base_model(path, file)
model['type'] = 'file'
model['mimetype'] = file['mimeType']
if content:
stream = BytesIO()
self.gc.downloadFile(file['_id'], stream)
if format == 'text':
try:
content = stream.getvalue().decode('utf8')
except UnicodeError:
if format == 'text':
raise web.HTTPError(
400, '%s is not UTF-8 encoded' % girder_path,
reason='bad format')
elif format == 'base64':
content = base64.b64encode(stream.getvalue()).decode('ascii')
# If not specified, try to decode as UTF-8, and fall back to base64
else:
try:
content = stream.getvalue().decode('utf8')
format = 'text'
except UnicodeError:
content = base64.b64encode(stream.getvalue()).decode('ascii')
format = 'base64'
model.update(
content=content,
format=format
)
return model
def _item_model(self, path, item, content=True, format=None):
name = path.split('/')[-1]
files = list(self.gc.listFile(item['_id']))
# We short cut an item just create to contain a file
item_is_container = False
for file in files:
if file['name'] == name:
item_is_container = len(files) == 1
item_file = file
if item_is_container:
return self._file_model(path, item_file, content, format)
# Other treat item as read-only directories
model = self._base_model(path, item)
model['writable'] = False
model['type'] = 'directory'
if content:
model['content'] = contents = []
for file in files:
contents.append(self._get(
'%s/%s' % (path, file['name']), file,
content=False, format=format)
)
model['format'] = 'json'
return model
def _notebook_model(self, path, resource, content=True):
name = path.split('/')[-1]
# Shortcut item
if self._is_item(resource):
resource = self._file_by_name(resource['_id'], name)
model = self._base_model(path, resource)
model['type'] = 'notebook'
if content:
stream = BytesIO()
self.gc.downloadFile(resource['_id'], stream)
nb = nbformat.reads(stream.getvalue().decode('utf8'), as_version=4)
self.mark_trusted_cells(nb, path)
model['content'] = nb
model['format'] = 'json'
self.validate_notebook_model(model)
return model
def _get(self, path, resource, content=True, type=None, format=None):
"""Get a file or directory model."""
girder_path = self._get_girder_path(path)
if not self._is_type(resource, ['file', 'item', 'folder', 'user']):
raise web.HTTPError(404, 'No such file or directory: %s' % girder_path)
if type == 'notebook' or (type is None and path.endswith('.ipynb')):
model = self._notebook_model(path, resource, content)
elif self._is_folder(resource) or self._is_user(resource):
if type not in (None, 'directory'):
raise web.HTTPError(
400, '%s is a directory, not a %s' % (girder_path, type), reason='bad type')
model = self._dir_model(path, resource, content, format)
elif self._is_item(resource):
if type not in (None, 'file', 'notebook'):
raise web.HTTPError(
400, '%s is a file, not a %s' % (girder_path, type), reason='bad type')
model = self._item_model(path, resource, content, format)
else:
if type == 'directory':
raise web.HTTPError(
400, '%s is not a directory' % girder_path, reason='bad type')
model = self._file_model(path, resource, content=content, format=format)
return model
def get(self, path, content=True, type=None, format=None):
"""Get a file or directory model."""
path = path.strip('/')
girder_path = self._get_girder_path(path)
resource = self._resource(girder_path)
return self._get(path, resource, content, type, format)
def _upload_to_path(self, content, mime_type, format, path):
parts = path.split('/')
name = parts[-1]
folder_path = parts[:-1]
parent = self._create_folders('/'.join(folder_path))
if self._is_user(parent):
msg = "The Girder user's home location may only contain " \
'folders. Create or navigate to another folder before ' \
'creating or uploading a file.'
raise web.HTTPError(400, msg, reason=msg)
elif self._is_item(parent):
item = parent
else:
item = self.gc.loadOrCreateItem(name, parent['_id'], reuseExisting=True)
file = self._file_by_name(item['_id'], name)
# Get content in right format
if format == 'text':
content = content.encode('utf8')
else:
b64_content = content.encode('ascii')
content = base64.b64decode(b64_content)
size = len(content)
stream = BytesIO(content)
if file is None:
self.gc.uploadFile(item['_id'], stream, name, size, mimeType=mime_type)
else:
self.gc.uploadFileContents(file['_id'], stream, size)
def _create_folders(self, path):
"""
Create all necessary folder for a given path.
"""
parts = path.split('/')
root = '/'.join(parts[:2])
path = parts[2:]
current_resource = self._resource(root)
if current_resource is None:
raise web.HTTPError(404, 'No such file or directory: %s' % path)
for resource_name in path:
# Can't create folder under an item so return permission denied
if self._is_item(current_resource):
raise web.HTTPError(403, 'Permission denied: %s' % resource_name)
next_resource = next(
self.gc.listFolder(current_resource['_id'],
name=resource_name,
parentFolderType=current_resource['_modelType']), None)
# Check for items
if next_resource is None:
next_resource = next(self.gc.listItem(current_resource['_id'],
name=resource_name), None)
if next_resource is None:
# Can't create folder under an item so return permission denied
if self._is_item(current_resource):
raise web.HTTPError(403, 'Permission denied: %s' % resource_name)
current_resource = self.gc.createFolder(current_resource['_id'],
resource_name,
parentType=current_resource['_modelType'])
else:
current_resource = next_resource
return current_resource
def save(self, model, path):
"""
Save a file or directory model to path.
Should return the saved model with no content. Save implementations
should call self.run_pre_save_hook(model=model, path=path) prior to
writing any data.
"""
path = path.strip('/')
girder_path = self._get_girder_path(path)
if 'type' not in model:
raise web.HTTPError(400, 'No file type provided')
if 'content' not in model and model['type'] != 'directory':
raise web.HTTPError(400, 'No file content provided')
for segment in path.split('/'):
if segment.startswith('.'):
raise web.HTTPError(400, 'Hidden files and folders are not allowed.')
try:
if model['type'] == 'notebook':
nb = nbformat.from_dict(model['content'])
self.check_and_sign(nb, path)
nb = nbformat.writes(nb, version=nbformat.NO_CONVERT)
self._upload_to_path(nb, 'application/json', 'text', girder_path)
elif model['type'] == 'file':
self._upload_to_path(model.get('content'), model.get('mimetype'),
model.get('format'), girder_path)
elif model['type'] == 'directory':
self._create_folders(girder_path)
else:
raise web.HTTPError(400, 'Unhandled contents type: %s' % model['type'])
except web.HTTPError:
raise
except Exception as e:
self.log.error('Error while saving file: %s %s', path, e, exc_info=True)
raise web.HTTPError(500, 'Unexpected error while saving file: %s %s' % (path, e))
validation_message = None
if model['type'] == 'notebook':
self.validate_notebook_model(model)
validation_message = model.get('message', None)
model = self.get(path, content=False)
model['message'] = validation_message
return model
def delete_file(self, path, allow_non_empty=False):
"""Delete the file or directory at path."""
path = path.strip('/')
girder_path = self._get_girder_path(path)
resource = self._resource(girder_path)
if resource is None:
raise web.HTTPError(404, 'Path does not exist: %s' % girder_path)
if self._is_folder(resource):
# Don't delete non-empty directories.
# TODO A directory containing only leftover checkpoints is
# considered empty.
resources = self._list_resource(resource)
if not allow_non_empty and resources:
raise web.HTTPError(400, 'Directory %s not empty' % girder_path)
self.gc.delete('folder/%s' % resource['_id'])
else:
name = path.split('/')[-1]
files = list(self.gc.listFile(resource['_id']))
deleted = False
for file in files:
if file['name'] == name:
self.gc.delete('file/%s' % file['_id'])
deleted = True
if not deleted:
raise web.HTTPError(404, 'File does not exist: %s' % girder_path)
# If the item only contained that file clean it up?
# TODO: What about item metadata?
if len(files):
self.gc.delete('item/%s' % resource['_id'])
def rename_file(self, old_path, new_path):
"""
Rename a file or directory.
N.B. Note currently we only support renaming, not moving to another folder.
Its not clear that this operation can be performed using rename, it doesn't
seem to be exposed through jlab.
"""
girder_path = self._get_girder_path(old_path)
resource = self._resource(girder_path)
if resource is None:
raise web.HTTPError(404, 'Path does not exist: %s' % girder_path)
# Check if new_path already exists
new_girder_path = self._get_girder_path(new_path)
existing_resource = self._resource(new_girder_path)
if existing_resource is not None:
raise web.HTTPError(409, u'File already exists: %s' % new_path)
def _update_name(type, resource, name):
params = {
'name': name
}
self.gc.put('%s/%s' % (type, resource['_id']), params)
name = os.path.basename(new_path)
if self._is_folder(resource):
_update_name('folder', resource, name)
elif self._is_file(resource):
_update_name('file', resource, name)
elif self._is_item(resource):
item_id = resource['_id']
item = self.gc.getItem(item_id)
files = list(self.gc.listFile(item_id))
_update_name('item', resource, name)
# If we have one file and the names match then rename both.
# This may or may not be the right behavior.
if len(files) == 1 and item['name'] == resource['name']:
_update_name('file', files[0], name)
def delete(self, path):
"""Delete a file/directory and any associated checkpoints."""
self.delete_file(path, allow_non_empty=True)
def rename(self, old_path, new_path):
"""Rename a file and any checkpoints associated with that file."""
self.rename_file(old_path, new_path)
<file_sep>=============
Release Notes
=============
This is the summary list of changes to girder_jupyter between each release. For full
details, see the commit logs at https://github.com/girder/girder_jupyter
Unreleased
==========
Added Features
--------------
Bug fixes
---------
Changes
-------
Deprecations
------------
DevOps
------
Removals
--------
Security Fixes
--------------
girder_jupyter 0.2.0
====================
Bug fixes
---------
* Guard against file creation under a user.
Changes
-------
* The contents manager class has been renamed to girder_jupyter.contents.manager.GirderContentsManager
to better fit with established naming conventions.
girder_jupyter 0.2.1
====================
Bug fixes
---------
* Improve error message when user tries to create a file under a Girder user.
<file_sep>from setuptools import setup, find_packages
from codecs import open
import os
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
with open('requirements.in') as f:
install_reqs = f.readlines()
def prerelease_local_scheme(version):
"""Return local scheme version unless building on master in CircleCI.
This function returns the local scheme version number
(e.g. 0.0.0.dev<N>+g<HASH>) unless building on CircleCI for a
pre-release in which case it ignores the hash and produces a
PEP440 compliant pre-release version number (e.g. 0.0.0.dev<N>).
"""
from setuptools_scm.version import get_local_node_and_date
if 'CIRCLE_BRANCH' in os.environ and \
os.environ.get('CIRCLE_BRANCH') == 'master':
return ''
else:
return get_local_node_and_date(version)
setup(
name='girder-jupyter',
use_scm_version={'local_scheme': prerelease_local_scheme},
setup_requires=['setuptools_scm'],
description='A jupyter content manager for Girder',
long_description=long_description,
url='https://github.com/girder/girder_jupyter',
author='Kitware Inc',
author_email='<EMAIL>',
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Jupyter',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
],
keywords='jupyter girder data management',
packages=find_packages(),
install_requires=install_reqs,
extras_require={
}
)
| 546d463395f71e8ae338c08931c232042ef6fc9c | [
"Python",
"reStructuredText"
]
| 6 | reStructuredText | girder/girder_jupyter | 09a1cbbca3c3c6e8d0b0a37c18a23c3e6e80938d | 99fb7223da94bfdf9b85bff09982833dc7b5b622 |
refs/heads/master | <file_sep>require 'geo-distance/class_methods'
class GeoDistance
include Comparable
include Conversion
attr_accessor :distance, :unit
def initialize distance, unit = :radians
@distance = distance
@unit = GeoUnits.key(unit)
end
alias_method :units, :unit
def <=> other
in_meters <=> other.in_meters
end
def number
distance.round(precision[unit])
end
private
def precision
{
:feet => 0,
:meters => 2,
:km => 4,
:miles => 4
}
end
end
| f174a4680564b46d646ee2379a990c4b355f3a41 | [
"Ruby"
]
| 1 | Ruby | tangopium/geo-distance | e9b45eaf2ec06c431c533db5bce6f2d82dbcbf6d | 3fd222fa3ae03412e84b92744e5b9cd396b148f8 |
refs/heads/master | <repo_name>denhub/vue-date-pick<file_sep>/docs/assets/js/16.b23c54ac.js
(window.webpackJsonp=window.webpackJsonp||[]).push([[16],{186:function(n,w,o){}}]); | 093edcd0f11ceea776a085ee93070e8e4c85d68c | [
"JavaScript"
]
| 1 | JavaScript | denhub/vue-date-pick | 2edc6f2c6fe732dea3fff05178dac0a1dcd86b59 | b39bb3edf0888c6c96fd1d08e768b763fb6687f9 |
refs/heads/master | <repo_name>newton073026/AndroidTestBoofCV<file_sep>/app/src/boofcv/benchmark/android/BinaryOpsBenchmark.java
package boofcv.benchmark.android;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import boofcv.alg.filter.binary.BinaryImageOps;
import boofcv.alg.filter.binary.GThresholdImageOps;
import boofcv.alg.misc.GPixelMath;
import boofcv.android.ConvertBitmap;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageSInt32;
import boofcv.struct.image.ImageSingleBand;
import boofcv.struct.image.ImageUInt8;
public class BinaryOpsBenchmark extends BenchmarkThread {
public static final String NAME = "BinaryOps";
private static final long serialVersionUID = 1L;
Bitmap bitmap;
public BinaryOpsBenchmark() {
super(NAME);
}
@Override
public void configure( Resources resources ) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
bitmap = BitmapFactory.decodeResource(resources,R.drawable.simple_objects,options);
}
@Override
public void run() {
if( bitmap == null ) {
finished();
return;
}
publishText(" Input size = "+bitmap.getWidth()+" x "+bitmap.getHeight()+"\n");
publishText("\n");
ImageUInt8 binary = new ImageUInt8(bitmap.getWidth(),bitmap.getHeight());
benchmarkThreshold(ImageUInt8.class,"U8",binary);
benchmarkThreshold(ImageFloat32.class,"F32",binary);
benchmark(binary);
finished();
}
private <T extends ImageSingleBand> void benchmarkThreshold( Class<T> imageType , String imageName ,
final ImageUInt8 binary ) {
final T image = ConvertBitmap.bitmapToGray(bitmap, null, imageType, null);
// the mean pixel value is often a reasonable threshold when creating a binary image
final double mean = GPixelMath.sum(image)/(image.width*image.height);
benchmark("Threshold "+imageName,new EvalPA() {
public void _process() {GThresholdImageOps.threshold(image,binary,mean,true);}});
}
private <T extends ImageSingleBand> void benchmark( final ImageUInt8 binary ) {
final ImageUInt8 output = new ImageUInt8(binary.width,binary.height);
benchmark("Erode4",new EvalPA() {
public void _process() {BinaryImageOps.erode4(binary,output);}});
benchmark("Erode8",new EvalPA() {
public void _process() {BinaryImageOps.erode8(binary,output);}});
benchmark("Dilate4",new EvalPA() {
public void _process() {BinaryImageOps.dilate4(binary,output);}});
benchmark("Dilate8",new EvalPA() {
public void _process() {BinaryImageOps.dilate8(binary,output);}});
benchmark("Edge4",new EvalPA() {
public void _process() {BinaryImageOps.edge4(binary,output);}});
benchmark("Edge8",new EvalPA() {
public void _process() {BinaryImageOps.edge8(binary,output);}});
benchmark("Logic And",new EvalPA() {
public void _process() {BinaryImageOps.logicAnd(binary,binary,output);}});
benchmark("Logic Or",new EvalPA() {
public void _process() {BinaryImageOps.logicOr(binary,binary,output);}});
benchmark("Logic Xor",new EvalPA() {
public void _process() {BinaryImageOps.logicXor(binary,binary,output);}});
final ImageSInt32 labeled = new ImageSInt32(binary.width,binary.height);
benchmark("Label Blobs4",new EvalPA() {
public void _process() {BinaryImageOps.labelBlobs4(binary,labeled);}});
benchmark("Label Blobs8",new EvalPA() {
public void _process() {BinaryImageOps.labelBlobs8(binary,labeled);}});
}
@Override
public String getDescription() {
return "Computes a binary image by thresholding. Binary operators are then applied " +
"to the resulting image. The number next to an operation refers to the connectivity rule used.\n"+
"\n"+
"BoofCV Image Type\n"+
" U8 = ImageUInt8\n"+
" F32 = ImageFloat32\n"+
" MU8 = MultSpectral<ImageUInt8>\n"+
" MF32 = MultiSpectral<ImageFloat32>";
}
}
<file_sep>/app/src/boofcv/benchmark/android/EvalPA.java
package boofcv.benchmark.android;
public abstract class EvalPA implements EvaluationProcess {
@Override
public void process(long numTrials) {
for( long i = 0; i < numTrials; i++ ) {
_process();
}
}
public abstract void _process();
}
<file_sep>/app/src/boofcv/benchmark/android/AboutActivity.java
package boofcv.benchmark.android;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.widget.TextView;
public class AboutActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
TextView textView = (TextView) findViewById(R.id.textViewAbout);
String text =
"BoofCV: http://boofcv.org\n"+
"Benchmark Version: "+CentralMemory.APP_VERSION_NAME+"\n"+
"\n"+
"- Higher scores are better.\n"+
"- All times are in milliseconds.\n"+
"\n"+
"BoofCV is an open source computer vision library written entirely in Java and "+
"released under an Apache 2.0 license. "+
"This application performs a series of diagnostic tests and "+
"benchmarks to evaluate BoofCV's performance on different Android "+
"platforms. Please help improve BoofCV on Android by "+
"running all the benchmarks, then submitting the results. To submit "+
"results click on the options menu.\n"+
"\n"+
"- <NAME>\n";
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(text);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_about, menu);
return true;
}
}
<file_sep>/app/src/boofcv/benchmark/android/BenchmarkThread.java
package boofcv.benchmark.android;
import java.io.Serializable;
import android.content.res.Resources;
public abstract class BenchmarkThread extends Thread implements Serializable {
long targetTime = 1000;
boolean interrupted = false;
BenchmarkResults resultsStorage = new BenchmarkResults();
public BenchmarkThread( String benchmarkName ) {
setPriority(MAX_PRIORITY);
resultsStorage.name = benchmarkName;
}
public abstract void configure( Resources resources);
public abstract String getDescription();
public void publishText( final String text ) {
CentralMemory.appendText(text);
}
public void benchmark( String name , EvaluationProcess process ) {
// lets the thread be killed by an interrupt
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
interrupted = true;
return;
}
long N = 1;
long found = evaluate(N,process);
while( found < targetTime/5 ) {
N = 2+N*N;
found = evaluate(N,process);
}
int sanity = 0;
while( found < targetTime && sanity++ < 1000 ) {
// linearly estimate how long many trials it should take, plus a fudge factor
long testN = (long)Math.ceil((1.1*N*targetTime)/found);
if( testN < 0 )
System.out.println();
if( testN <= N )
testN = N+1;
found = evaluate(testN,process);
N = testN;
}
publishResults(name,(double)found/(double)N );
}
private long evaluate( long trials , EvaluationProcess target ) {
long before = System.currentTimeMillis();
target.process(trials);
long after = System.currentTimeMillis();
return after-before;
}
public void publishResults( final String benchmarkName , final double results ) {
CentralMemory.appendText(String.format("%22.22s | %6.1f\n",benchmarkName,results));
resultsStorage.addResult(benchmarkName, results);
}
public void finished() {
CentralMemory.markFinished();
if( !interrupted ) {
resultsStorage.setText(CentralMemory.text);
CentralMemory.storageResults.put(resultsStorage.name, resultsStorage);
CentralMemory.storageUpdated = true;
}
}
public boolean isInterrupted() {
return interrupted;
}
public interface Listener {
public void updateText();
public void benchmarkFinished();
}
}
<file_sep>/app/src/boofcv/benchmark/android/RunAllBenchmark.java
package boofcv.benchmark.android;
import android.content.res.Resources;
/**
* Benchmark which runs all the other benchmarks
*
* @author <NAME>
*
*/
public class RunAllBenchmark extends BenchmarkThread {
Resources resources;
public RunAllBenchmark() {
super(null);
}
@Override
public void configure(Resources resources) {
this.resources = resources;
}
@Override
public void run() {
if( runBencmark(new Binary() ) ) return;
if( runBencmark(new Feature() ) ) return;
if( runBencmark(new Convert() ) ) return;
if( runBencmark(new LowLevel() ) ) return;
finished();
}
private boolean runBencmark( BenchmarkThread thread ) {
thread.configure(resources);
thread.run();
if( checkInterrupted() )
return true;
return false;
}
private boolean checkInterrupted() {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
interrupted = true;
finished();
return true;
}
return false;
}
@Override
public String getDescription() {
return "Runs every benchmarks one after another. Can take a bit to finish.";
}
@Override
public void finished() {
CentralMemory.markFinished();
}
private class Binary extends BinaryOpsBenchmark {
@Override
public void finished() {
if( !interrupted ) {
resultsStorage.setText(CentralMemory.text);
CentralMemory.storageResults.put(resultsStorage.name, resultsStorage);
CentralMemory.storageUpdated = true;
}
}
}
private class Feature extends FeatureBenchmark {
@Override
public void finished() {
if( !interrupted ) {
resultsStorage.setText(CentralMemory.text);
CentralMemory.storageResults.put(resultsStorage.name, resultsStorage);
CentralMemory.storageUpdated = true;
}
}
}
private class Convert extends ImageConvertBenchmark {
@Override
public void finished() {
if( !interrupted ) {
resultsStorage.setText(CentralMemory.text);
CentralMemory.storageResults.put(resultsStorage.name, resultsStorage);
CentralMemory.storageUpdated = true;
}
}
}
private class LowLevel extends LowLevelBenchmark {
@Override
public void finished() {
if( !interrupted ) {
resultsStorage.setText(CentralMemory.text);
CentralMemory.storageResults.put(resultsStorage.name, resultsStorage);
CentralMemory.storageUpdated = true;
}
}
}
}
<file_sep>/app/src/boofcv/benchmark/android/BenchmarkResultsCodec.java
package boofcv.benchmark.android;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.media.MediaScannerConnection;
/**
* For reading and writing to results log file
* @author <NAME>
*
*/
public class BenchmarkResultsCodec {
Activity activity;
public BenchmarkResultsCodec( Activity activity ) {
this.activity = activity;
}
public String resultsToString( Collection<BenchmarkResults> results ) {
StringBuffer buffer = new StringBuffer();
// start by adding information about the device
buffer.append("DeviceInfo 9\n");
buffer.append("AppVersionCode "+CentralMemory.APP_VERSION_CODE+"\n");
buffer.append("MODEL "+android.os.Build.MODEL+"\n");
buffer.append("BRAND "+android.os.Build.BRAND+"\n");
buffer.append("CPU_ABI "+android.os.Build.CPU_ABI+"\n");
buffer.append("DISPLAY "+android.os.Build.DISPLAY+"\n");
buffer.append("HARDWARE "+android.os.Build.HARDWARE+"\n");
buffer.append("MANUFACTURER "+android.os.Build.MANUFACTURER+"\n");
buffer.append("MODEL "+android.os.Build.MODEL+"\n");
buffer.append("VERSION.SDK_INT "+android.os.Build.VERSION.SDK_INT+"\n");
// add the results
for( BenchmarkResults r : results ) {
buffer.append(String.format("%s %d\n",r.name,r.results.size()));
for( BenchmarkResults.Pair p : r.results ) {
buffer.append(String.format("%f %s\n",p.result,p.testName));
}
}
return buffer.toString();
}
public boolean copyToExternal( String fileName ) {
try {
FileInputStream in = activity.openFileInput(fileName);
File file = new File(activity.getExternalFilesDir(""), fileName);
if( file.exists() )
file.delete();
FileOutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while( (bytesRead = in.read(buffer)) > 0){
out.write(buffer,0,bytesRead);
}
out.close();
in.close();
// Hack so that it will be visible to users when mounted on the computer
MediaScannerConnection.scanFile(activity, new String[] {file.getAbsolutePath()}, null, null);
return true;
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
}
public void write( String fileName , List<BenchmarkResults> results ){
try {
FileOutputStream fos = activity.openFileOutput(fileName, Context.MODE_PRIVATE);
PrintStream out = new PrintStream(fos);
out.print(resultsToString(results));
out.flush();
out.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public Map<String,BenchmarkResults> read( String fileName , boolean rawResource ) {
try {
BufferedReader fis;
if( rawResource ) {
fis = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(R.raw.galaxys3)));
} else {
fis = new BufferedReader(new InputStreamReader(activity.openFileInput(fileName)));
}
Map<String,BenchmarkResults> map = new HashMap<String,BenchmarkResults>();
while( true ) {
String s = fis.readLine();
if( s == null )
break;
String[] line = splitLine(s);
BenchmarkResults r = new BenchmarkResults();
r.name = line[0];
int N = Integer.parseInt(line[1]);
if (r.name.compareTo("DeviceInfo") == 0) {
// skip over device info since it follows a slightly different format and will cause a crash
for (int i = 0; i < N; i++) {
fis.readLine();
}
} else {
for (int i = 0; i < N; i++) {
line = splitLine(fis.readLine());
double value = Double.parseDouble(line[0]);
r.results.add(new BenchmarkResults.Pair(line[1], value));
}
map.put(r.name, r);
}
}
fis.close();
return map;
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String[] splitLine( String text ) {
String[] ret = new String[2];
int w = 0;
for( ; w < text.length(); w++ ) {
if( text.charAt(w) == ' ') {
break;
}
}
ret[0] = text.substring(0,w);
ret[1] = text.substring(w+1);
return ret;
}
}
<file_sep>/readme.txt
Application for evaluating and testing BoofCV's performance on an Android device. Once launched a user and select a series of benchmarks to run and check to see if image conversion between Android and BoofCV data types is done correctly.
All code is released under an Apache 2 software license.
- <NAME>
<file_sep>/app/src/boofcv/benchmark/android/CentralMemory.java
package boofcv.benchmark.android;
import java.util.HashMap;
import java.util.Map;
import android.content.res.Resources;
import android.os.Handler;
import boofcv.benchmark.android.BenchmarkThread.Listener;
public class CentralMemory {
public static int APP_VERSION_CODE;
public static String APP_VERSION_NAME;
public static Class<BenchmarkThread> benchmarkType;
public static volatile BenchmarkThread thread;
public static volatile String text;
public static volatile boolean isRunning = false;
public static volatile boolean hasResults = false;
public static volatile Handler handler;
public static volatile Listener listener;
public static Map<String,BenchmarkResults> storageResults = new HashMap<String,BenchmarkResults>();
public static Map<String,BenchmarkResults> storageBaseLine = new HashMap<String,BenchmarkResults>();
public static boolean storageUpdated = false;
public static void setBenchmark( Class type ) {
benchmarkType = type;
declareThread();
}
public static void startThread( Resources resources, Listener listener ) {
if( isRunning )
throw new RuntimeException("Thread has not finished yet");
isRunning = true;
hasResults = true;
CentralMemory.handler = new Handler();
CentralMemory.listener = listener;
declareThread();
text = "";
thread.configure( resources );
thread.start();
}
public static boolean isThreadRunning() {
return isRunning;
}
public static boolean hasResults() {
return hasResults;
}
public static void reset() {
hasResults = false;
handler = null;
listener = null;
}
public static void markFinished() {
appendText("\nFinished");
isRunning = false;
if (handler != null) {
handler.post(new Runnable() {
public void run() {
if( listener != null )
listener.benchmarkFinished();
}
});
}
}
public static void updateActivity( Listener listener ) {
synchronized (thread) {
CentralMemory.handler = new Handler();
CentralMemory.listener = listener;
}
}
public static void appendText( final String text ) {
synchronized( thread ) {
CentralMemory.text += text;
if (handler != null) {
handler.post(new Runnable() {
public void run() {
if( listener != null )
listener.updateText();
}
});
}
}
}
private static void declareThread() {
try {
thread = benchmarkType.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
<file_sep>/app/src/boofcv/benchmark/android/FeatureBenchmark.java
package boofcv.benchmark.android;
import georegression.struct.point.Point2D_F64;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import boofcv.abst.feature.describe.DescribeRegionPoint;
import boofcv.abst.feature.detect.edge.DetectEdgeContour;
import boofcv.abst.feature.detect.extract.GeneralFeatureDetector;
import boofcv.abst.feature.detect.interest.InterestPointDetector;
import boofcv.abst.feature.detect.line.DetectLineHoughPolar;
import boofcv.alg.filter.derivative.GImageDerivativeOps;
import boofcv.android.ConvertBitmap;
import boofcv.factory.feature.describe.FactoryDescribeRegionPoint;
import boofcv.factory.feature.detect.edge.FactoryDetectEdgeContour;
import boofcv.factory.feature.detect.interest.FactoryDetectPoint;
import boofcv.factory.feature.detect.interest.FactoryInterestPoint;
import boofcv.factory.feature.detect.line.FactoryDetectLineAlgs;
import boofcv.struct.feature.TupleDesc_F64;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageSingleBand;
import boofcv.struct.image.ImageUInt8;
public class FeatureBenchmark extends BenchmarkThread {
private static final long serialVersionUID = 1L;
private static final int NUM_DESCRIBE = 300;
public static final String NAME = "Feature";
Bitmap bitmap;
Bitmap bitmapLines;
InterestPointDetector detector;
DetectLineHoughPolar detectorLine;
DescribeRegionPoint describe;
public FeatureBenchmark() {
super(NAME);
}
@Override
public void configure( Resources resources ) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
bitmap = BitmapFactory.decodeResource(resources,R.drawable.sundial01_left,options);
bitmapLines = BitmapFactory.decodeResource(resources,R.drawable.lines_indoors,options);
}
@Override
public void run() {
if( bitmap == null ) {
finished();
return;
}
// TODO smaller image 320x240
publishText(" Point input size = "+bitmap.getWidth()+" x "+bitmap.getHeight()+"\n");
publishText(" Line input size = "+bitmapLines.getWidth()+" x "+bitmapLines.getHeight()+"\n");
publishText(" Describe "+NUM_DESCRIBE+" features\n");
publishText("\n");
benchmark(ImageUInt8.class,"U8");
benchmark(ImageFloat32.class,"F32");
finished();
}
private <T extends ImageSingleBand> void benchmark( Class<T> imageType , String imageName ) {
T imagePoint = ConvertBitmap.bitmapToGray(bitmap, null, imageType, null);
benchmarkPoints(imagePoint,imageName);
imagePoint = null;
T imageLine = ConvertBitmap.bitmapToGray(bitmapLines, null, imageType, null);
benchmarkLines(imageLine,imageName);
benchmarkContour(imageLine,imageName);
benchmarkDescribe(imageLine,imageName);
}
private <T extends ImageSingleBand> void benchmarkPoints( final T image , String imageName ) {
Class<T> imageType = (Class)image.getClass();
Class derivType = GImageDerivativeOps.getDerivativeType(imageType);
int maxFeatures = 300;
int r = 2;
GeneralFeatureDetector corner = FactoryDetectPoint.createFast(r,45,maxFeatures,imageType);
detector = FactoryInterestPoint.wrapCorner(corner, imageType, derivType);
benchmark("Fast Corner "+imageName,new EvalPA() {
public void _process() {detector.detect(image);}});
corner = FactoryDetectPoint.createHarris(r,false,1,maxFeatures,derivType);
detector = FactoryInterestPoint.wrapCorner(corner, imageType, derivType);
benchmark("Harris "+imageName,new EvalPA() {
public void _process() {detector.detect(image);}});
corner = FactoryDetectPoint.createShiTomasi(r,false,1,maxFeatures,derivType);
detector = FactoryInterestPoint.wrapCorner(corner, imageType, derivType);
benchmark("Shi-Tomasi "+imageName,new EvalPA() {
public void _process() {detector.detect(image);}});
detector = FactoryInterestPoint.fastHessian(10, 2, 120, 2, 9, 4, 4);
benchmark("Fast Hessian "+imageName,new EvalPA() {
public void _process() {detector.detect(image);}});
detector = null;
}
private <T extends ImageSingleBand> void benchmarkLines( final T image , String imageName ) {
Class<T> imageType = (Class)image.getClass();
Class derivType = GImageDerivativeOps.getDerivativeType(imageType);
int maxLines = 10;
float edgeThreshold = 25;
detectorLine = FactoryDetectLineAlgs.houghPolar(3, 30, 2, Math.PI / 180,
edgeThreshold, maxLines, imageType, derivType);
benchmark("Hough Polar "+imageName,new EvalPA() {
public void _process() {detectorLine.detect(image);}});
detectorLine = null;
// The line segement detector currently only supports floating point images
// Once the algorithm is better create an integer version.
// final DetectLineSegmentsGridRansac detectorLS =
// FactoryDetectLineAlgs.lineRansac(40, 30, 2.36, true, imageType, derivType);
//
// benchmark("Line Seg. Grid "+imageName,new EvalPA() {
// public void _process() {detectorLS.detect(image);}});
}
private <T extends ImageSingleBand> void benchmarkContour( final T image , String imageName ) {
Class<T> imageType = (Class)image.getClass();
Class derivType = GImageDerivativeOps.getDerivativeType(imageType);
final DetectEdgeContour<T> canny =
FactoryDetectEdgeContour.canny(30,200,false,imageType,derivType);
benchmark("Canny Edge "+imageName,new EvalPA() {
public void _process() {canny.process(image);}});
}
private <T extends ImageSingleBand> void benchmarkDescribe( final T image , String imageName ) {
Class<T> imageType = (Class)image.getClass();
// randomly create interest points to describe
Random rand = new Random(234);
final List<Point2D_F64> locs = new ArrayList<Point2D_F64>();
final double scales[] = new double[NUM_DESCRIBE];
for( int i = 0; i < NUM_DESCRIBE; i++ ) {
double x = rand.nextDouble()*image.width;
double y = rand.nextDouble()*image.height;
locs.add( new Point2D_F64(x,y) );
scales[i] = rand.nextDouble()*5+0.9;
}
describe = FactoryDescribeRegionPoint.surf(true, imageType);
benchmark("Desc SURF "+imageName,new EvalPA() {
public void _process() {computeDescription(image,locs,scales);}});
describe = FactoryDescribeRegionPoint.surfm(true, imageType);
benchmark("Desc SURFM "+imageName,new EvalPA() {
public void _process() {computeDescription(image,locs,scales);}});
describe = FactoryDescribeRegionPoint.pixel(7,7,imageType);
benchmark("Desc Pixel "+imageName,new EvalPA() {
public void _process() {computeDescription(image,locs,scales);}});
}
private void computeDescription(ImageSingleBand image, List<Point2D_F64> locs, double scales[]) {
TupleDesc_F64 desc = new TupleDesc_F64(describe.getDescriptionLength());
describe.setImage(image);
for( int i = 0; i < NUM_DESCRIBE; i++ ) {
Point2D_F64 p = locs.get(i);
describe.process(p.x, p.y , 0, scales[i], desc);
}
}
@Override
public String getDescription() {
return "Runs different types of feature detectors (e.g. point, line, edge) and descriptors on an image. " +
"Some of these operations can be slow depending on your hardware.\n"+
"\n"+
"BoofCV Image Type\n"+
" U8 = ImageUInt8\n"+
" F32 = ImageFloat32\n"+
" MU8 = MultSpectral<ImageUInt8>\n"+
" MF32 = MultiSpectral<ImageFloat32>";
}
}
<file_sep>/app/src/boofcv/benchmark/android/VisualDebugActivity.java
package boofcv.benchmark.android;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import boofcv.android.ConvertBitmap;
import boofcv.struct.image.ImageBase;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageSingleBand;
import boofcv.struct.image.ImageUInt8;
import boofcv.struct.image.MultiSpectral;
public class VisualDebugActivity extends Activity implements OnItemSelectedListener {
Spinner spinnerAndroid;
Spinner spinnerBoof;
Bitmap.Config selectedAndroid = Bitmap.Config.ARGB_8888;
int selectedBoofcv = 0;
boolean isInitialized = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visual_debug);
spinnerAndroid = (Spinner) findViewById(R.id.spinnerAndroidTypes);
spinnerBoof = (Spinner) findViewById(R.id.spinnerBoofcvTypes);
setupSpinner(R.id.spinnerAndroidTypes,R.array.AndroidTypes);
setupSpinner(R.id.spinnerBoofcvTypes,R.array.BoofcvTypes);
render();
isInitialized = true;
}
private void setupSpinner( int spinnerID, int textArrayID ) {
Spinner spinner = (Spinner) findViewById(spinnerID);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, textArrayID,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_visual_debug, menu);
return true;
}
private void render() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap input = BitmapFactory.decodeResource(getResources(),R.drawable.sundial01_left,options);
// convert the input image into the desired image type
if( input.getConfig() != selectedAndroid ) {
input = input.copy(selectedAndroid, true);
}
// Declare the appropriate BoofCV Type
ImageBase middle = null;
switch( selectedBoofcv ) {
case 0:
middle = new ImageUInt8(input.getWidth(),input.getHeight());
break;
case 1:
middle = new ImageFloat32(input.getWidth(),input.getHeight());
break;
case 2:
middle = new MultiSpectral<ImageUInt8>(ImageUInt8.class,input.getWidth(),input.getHeight(),4);
break;
case 3:
middle = new MultiSpectral<ImageFloat32>(ImageFloat32.class,input.getWidth(),input.getHeight(),4);
break;
}
// convert into the correct boofcv type
if( selectedBoofcv <= 1 ) {
ConvertBitmap.bitmapToGray(input, (ImageSingleBand)middle, (Class)middle.getClass(), null);
} else {
MultiSpectral ms = (MultiSpectral)middle;
ConvertBitmap.bitmapToMS(input, ms, ms.getType(), null);
}
// convert it back into the android type
if( selectedBoofcv <= 1 ) {
ConvertBitmap.grayToBitmap((ImageSingleBand)middle, input,null);
} else {
MultiSpectral ms = (MultiSpectral)middle;
ConvertBitmap.multiToBitmap(ms,input, null);
}
// update the view
ImageView view = (ImageView) findViewById(R.id.imageViewTest);
view.setImageBitmap(input);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if( parent == spinnerAndroid ) {
switch( pos ) {
case 0:
this.selectedAndroid = Bitmap.Config.ARGB_8888;
break;
case 1:
this.selectedAndroid = Bitmap.Config.RGB_565;
break;
default:
throw new RuntimeException("Unknown android selection");
}
} else if( parent == spinnerBoof ){
this.selectedBoofcv = pos;
}
if( isInitialized )
render();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
<file_sep>/app/src/boofcv/benchmark/android/BenchmarkActivity.java
package boofcv.benchmark.android;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class BenchmarkActivity extends Activity implements BenchmarkThread.Listener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_benchmark);
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
TextView textView = (TextView) findViewById(R.id.textViewResults);
textView.setMovementMethod(new ScrollingMovementMethod());
// prevents the screen from going to sleep and slowing down the CPU
// Unlike the power manager approach no extra permission is required and I can't
// accidentially leave it on
textView.setKeepScreenOn(true);
if( CentralMemory.hasResults() ) {
CentralMemory.updateActivity(this);
textView.setText(CentralMemory.text);
} else{
textView.setText(CentralMemory.thread.getDescription());
}
}
@Override
protected void onResume() {
super.onResume();
// make sure it has full control over the CPU
if( CentralMemory.hasResults() ) {
CentralMemory.updateActivity(this);
TextView textView = (TextView) findViewById(R.id.textViewResults);
textView.setText(CentralMemory.text);
}
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
Button button = (Button) findViewById(R.id.buttonStart);
if( CentralMemory.isThreadRunning() ) {
pb.setVisibility(View.VISIBLE);
button.setText("Stop");
button.setTextColor(0xFFFF0000);
} else {
pb.setVisibility(View.INVISIBLE);
button.setText("Start");
button.setTextColor(0xFF000000);
}
}
@Override
protected void onStop() {
super.onStop();
CentralMemory.updateActivity( null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_low_level, menu);
return true;
}
public void onStartButton( View view ) {
TextView textView = (TextView) findViewById(R.id.textViewResults);
Button button = (Button) findViewById(R.id.buttonStart);
if( !CentralMemory.isThreadRunning() ) {
CentralMemory.startThread(getResources(),this);
textView.setText(CentralMemory.text);
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.VISIBLE);
button.setText("Stop");
button.setTextColor(0xFFFF0000);
} else {
new KillBenchmarkThread(this).start();
}
}
@Override
public void benchmarkFinished() {
Button button = (Button) findViewById(R.id.buttonStart);
button.setText("Start");
button.setTextColor(0xFF000000);
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
}
@Override
public void updateText() {
TextView textView = (TextView) findViewById(R.id.textViewResults);
textView.setText(CentralMemory.text);
}
}
<file_sep>/app/src/boofcv/benchmark/android/BenchmarkResults.java
package boofcv.benchmark.android;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Contains results of benchmark test
*
* @author <NAME>
*
*/
public class BenchmarkResults implements Serializable {
private static final long serialVersionUID = 1838240192L;
public String name;
public String text;
public List<Pair> results = new ArrayList<Pair>();
public void setText( String text ) {
this.text = text;
}
public void addResult( String testName , double result ) {
results.add( new Pair(testName,result));
}
public double computeScore() {
double total = 0;
for( Pair p : results ) {
total += p.result;
}
return total;
}
public static class Pair implements Serializable
{
private static final long serialVersionUID = 93384L;
public String testName;
public double result;
public Pair( String testName , double result ) {
this.testName = testName;
this.result = result;
}
public String getTestName() {
return testName;
}
public double getResult() {
return result;
}
}
}
| 18154970d7a15fb08989f437d8e7bd93f7f28c15 | [
"Java",
"Text"
]
| 12 | Java | newton073026/AndroidTestBoofCV | 4d810fae0875e1b429b1f9b0f580a290c49d31fc | 46afc75437d243ebae9f6a7704de503240e68a56 |
refs/heads/main | <repo_name>Gasu16/Race-Conditions<file_sep>/README.md
# Race-Conditions
Set of race conditions based attacks (TOCTTOU)
file_1 => bait file (the file we are deceiving the system with)
file_2 => target file (the file we actually want to open)
To compile:
gcc attack.c -o attack
gcc victim.c -o victim
To run:
./attack file_1 file_2
./victim file_1
Pay attention: probably it will give some tries before actually working due to the timing of both the process attack and victim.
Improving soon...
<file_sep>/Rename_race_conditions/victim.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
int stat(const char *pathname, struct stat *statbuf);
int main(int argc, char *argv[]){
if(argc != 2){
fprintf(stderr, "Please enter 1 arg as file_1\nUsage: ./victim file_1\n");
return -1;
}
int fd;
char buffer[256];
printf("Input file: %s\n", argv[1]);
struct stat stat_data;
if(stat(argv[1], &stat_data) != 0){
fprintf(stderr, "Cannot stat file %s: %s\n", argv[1], strerror(errno));
return -1;
}
printf("stat uid => %d\n", stat_data.st_uid);
// 1 - Check the privileges of the input file passed as parameter with stat_data.st_uid
if(stat_data.st_uid == 0){
fprintf(stderr, "File is owned by ROOT, you can't access it\n");
return -1;
}
// 2 - Open the file
if((fd = open(argv[1], O_RDONLY)) < 0){
fprintf(stderr, "Open error: %s\nErrno code => %d\n", strerror(errno), errno);
return -1;
}
read(fd, buffer, sizeof(buffer));
printf("%s", buffer);
return 0;
}
<file_sep>/Symlink_race_conditions/HowItWorks.md
This is a very basic and simple simulation of a race condition between the couple system calls access() and open() via symlink().
# Explanation
Access() system call checks whether a process can access the file_1, if it returns 0 the access() allows the process to read/write/execute a certain file given as file_1.
After we gain the permission to handle the file_1 we switch it with another file of the same name linked to a "dangerous" file (e.g. /etc/passwd), this is file_2.
When open() is invoked it actually opens the file linked to file_2 (e.g. /etc/passwd or any file specified as file_2).
<file_sep>/Symlink_race_conditions/attack.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
int symlink(const char *target, const char *linkpath);
int unlink(const char *pathname);
int main(int argc, char *argv[]){
if(argc != 3){
fprintf(stderr, "Please enter 2 args as file_1 and file_2\nUsage: ./attack file_1 file_2\n");
return -1;
}
// Let's switch the file by linking a new same-name input file to a dangerous file passed as argv[2]
while(1){
// 1 - Let's try to remove the file by unlink() syscall
if(unlink(argv[1]) != 0){
// Cannot remove the file
perror("Unlink error: ");
fprintf(stderr, "Cannot remove the file, errno = %d\n", errno);
return -1;
}
// 2 - Create the link by symlink() using the first input file name as argument
if(symlink(argv[2], argv[1]) != 0){
// Cannot create the symlink
perror("Symlink error: ");
fprintf(stderr, "Failed link, errno = %d\n", errno);
return -1;
}
}
return 0;
}
<file_sep>/Rename_race_conditions/attack.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
int rename(const char *oldpath, const char *newpath);
int swapFiles(const char *a, const char *b, char *argv[]);
int swapFiles(const char *a, const char *b, char *argv[]){
const char *tempfile = "tempfile";
if(rename(argv[1], tempfile) != 0){
fprintf(stderr, "Error on first rename %s\nErrno code => %d\n", strerror(errno), errno);
return -1;
}
if(rename(argv[2], argv[1]) != 0){
fprintf(stderr, "Error on second rename %s\nErrno code => %d\n", strerror(errno), errno);
return -1;
}
if(rename(tempfile, argv[2]) != 0){
fprintf(stderr, "Error on third rename %s\nErrno code => %d\n", strerror(errno), errno);
return -1;
}
return 0;
}
int main(int argc, char *argv[]){
if(argc != 3){
fprintf(stderr, "Please enter 2 args as file_1 and file_2\nUsage: ./attack file_1 file_2\n");
return -1;
}
// Try to rename the target file argv[2] with the same name as bait file argv[1]
while(1){
swapFiles(argv[1], argv[2], argv);
}
return 0;
}
<file_sep>/Rename_race_conditions/HowItWorks.md
# Explanation
We stat() the file_1 information and we check if its UID is 0, if it is, it means the owner of that file is ROOT so we can't access it; otherwise we can open the file.
So what if we want to open a file which is owned by ROOT?
We simply give as input a regular file (with UID != 0) which not belongs to ROOT, doing so it gives us the allowance to bypass the checking (if UID == 0).
The race condition occurs between the checking and the opening of the file.
After bypassing the checking, we swap the file_1 with file_2 (see attack.c).
When open() is invoked it actually opens file_2 (e.g. /etc/passwd or any file specified as file_2).
That's it! We now have opened to a file we couldn't have access to with normal permission.
| a216629a5d44176b3f7e2829ca2609fb433b0c48 | [
"Markdown",
"C"
]
| 6 | Markdown | Gasu16/Race-Conditions | 380cc2f9cf2c588b2b8bbeaa2e45b55731c1f300 | 74bef852c19d7440fa8c65ea87e7c3e26e8f2d47 |
refs/heads/master | <file_sep>using System;
namespace OneElevatorTest.Interfaces
{
//Enumeration for describing elevator's direction.
public enum DirectionEnum
{
UP,
DOWN,
NONE
}
}
<file_sep>using System;
namespace OneElevatorTest.Interfaces
{
public interface Elevator
{
/**
* Tells which direction is the elevator going in.
*
* @return DirectionEnum Enumeration value describing the direction.
*/
DirectionEnum Direction { get; }
/**
* If the elevator is moving. This is the target floor.
*
* @return primitive integer number of floor
*/
int AddressedFloor { get; }
/**
* Get the Id of this elevator.
*
* @return primitive integer representing the elevator.
*/
int Id { get; }
/**
* Command to move the elevator to the given floor.
*
* @param toFloor
* int where to go.
*/
void moveElevator(int toFloor);
/**
* Check if the elevator is occupied at the moment.
*
* @return true if busy.
*/
bool isBusy { get; }
/**
* Reports which floor the elevator is at right now.
*
* @return int actual floor at the moment.
*/
int CurrentFloor { get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using OneElevatorTest.Interfaces;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace OneElevatorTest.Controllers
{
[Route("api/[controller]")]
public class ElevatorsController : Controller
{
// GET: api/elevators
[HttpGet]
public IActionResult Get()
{
var ElevatorList = new List<Elevator>();
// do some magic
return Ok(JsonConvert.SerializeObject(ElevatorList));
}
// GET api/elevators/5
[HttpGet("{id}")]
public IActionResult GetElevator(int id)
{
return Ok(Json(""));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace OneElevatorTest.Interfaces
{
// Interface for the Elevator Manager.
interface ElevatorManager
{
/**
* Request an elevator to the specified floor.
*
* @param toFloor
* addressed floor as integer.
* @return The Elevator that is going to the floor, if there is one to move.
*/
Elevator requestElevator(int toFloor);
/**
* A snapshot list of all elevators in the system.
*
* @return A List with all {@link Elevator} objects.
*/
List<Elevator> getElevators();
/**
* Telling the controller that the given elevator is free for new
* operations.
*
* @param elevator
* the elevator that shall be released.
*/
void releaseElevator(Elevator elevator);
}
}
<file_sep># Elevator Coding Challenge
Create an elevator controller!
This is a skeleton project with two interfaces that you must implement.
You are going to create an Elevator Manager and a number of Elevators that will be managed by the Manager.
There are a few extra classes already added to the project to get you up and running quickly.
## To Do
There are two interfaces to implement.
* `Elevator` - this is the elevator itself and has a few public methods to take care of. There can be n number of elevators at the same time
* `ElevatorManager` - this is the elevator manager that keeps track of all the elevators running in the elevator shaft. There should be only one ElevatorController
### Bonus files
There are a few classes and files added to get you faster up and running. It is not mandatory to use these classes in
your solution but you can use them to cut time in boiler plate coding.
* `ElevatorsController` - this is a REST controller that you can use and develop.
* `DirectionEnum` - this is an enumeration that could be useful.
## What We Expect
Implement the elevator system and make it as real as possible when it comes to the logic. Which elevator is best
suited for a waiting floor, more requests than available elevators and so on.
Write a test or a simulation that runs the system with a number of floors and elevators. The numbers should be flexible
and the system must work with one to many elevators.
Document how we start, simulate and monitor your solution. If there is a GUI or logging for monitoring does not matter
as long as you describe how it is supposed to be done.
Have fun! This is not a trap. It is a code challenge to check coding style etc. If there are features you don't have
time to add or if you have future changes in mind, write comments or document them.
### Deliver Your Solution
Add the code to a github or bitbucket repository. You can also make an archive of the project and e-mail it to us.
__We would like to see your solution within 7 days.__
## Build And Run (as is)
Using Run in Visual Studio
or
Implemented as a Docker service
| 91adf81e5a402e96f3d3d8c884d4e22eb6040424 | [
"Markdown",
"C#"
]
| 5 | C# | braxenator/elevatorsnet | 0870952984b84e86155523db99a01f36cfe70315 | a87f0ed88658cbd2a3acd4d48cca9d9512135b16 |
refs/heads/master | <file_sep> //import module
const EventEmitter = require('events')
//Instantiate event emitter
const eventEmitter = new EventEmitter()
//Use case-1 (normal)
//listen to the event
eventEmitter.on('usecase1',() => {
console.log('Use case-1 (normal): connected...')
})
//publish an event
eventEmitter.emit('usecase1')
//Use case-2 (with argument)
eventEmitter.on('usecase2',(serverName) => {
console.log(`Use case-2 (with argument): connected to ${serverName}`)
})
eventEmitter.emit('usecase2', 'testserver')
//Use case-3 (register multiple listener)
//The listeners execution order determined how the listeners have been registered.
//The Listeners executes the events synchronously in the current event loop cycle
//listen-1 to the event
eventEmitter.on('usecase3',() => {
console.log('Use case-3 (register multiple listener-1)')
})
//listen-2 to the event
eventEmitter.on('usecase3',(serverName) => {
console.log('Use case-3 (register multiple listener-2)')
})
eventEmitter.emit('usecase3')
//Use case-4 (listener must be register before emitting the event)
eventEmitter.on('usecase4',() => {
console.log('Use case-4 (listener must be register before emitting the event)')
})
eventEmitter.emit('usecase4', 'testserver')
//listen-2 to the event (omitted listener as registered after emitting event)
eventEmitter.on('usecase4',() => {
console.log('Use case-4 (this listener will be omitted)')
})
//Use case-5 (single instance of event emitter)
//emit and on functions must be called on the same EventEmitter instance, if called on two different event emitter instance then registred listener will be omitted
const em1 = new EventEmitter()
const em2 = new EventEmitter()
em1.on('usecase5',() => {
console.log('Use case-5 (omitted due to different instance of event emitter)')
})
em2.emit('usecase5')
//USe case-6 (off function)
//listen to the event
function printhello(){
console.log('Hello')
}
eventEmitter.on('usecase6', printhello)
//remove listener
eventEmitter.off('usecase6', printhello)
//this will be ignored
eventEmitter.on('usecase6', printhello)
//publish an event
eventEmitter.emit('usecase6')
//Use case-7 (once function)
//This will be called only once
eventEmitter.on('usecase7', () => {
console.log('Use case-7: on function')
})
eventEmitter.once('usecase7', () => {
console.log('Use case-7: once function')
})
//publish event multiple times
eventEmitter.emit('usecase7') //run on and once
eventEmitter.emit('usecase7') //run only on
//Use case-8 (Listener count)
eventEmitter.on('usecase8', () => {
console.log('Use case-8: first')
})
eventEmitter.on('usecase8', () => {
console.log('Use case-8: second')
})
eventEmitter.on('usecase8', () => {
console.log('Use case-8: third')
})
//publish event multiple times
eventEmitter.emit('usecase8')
//Listeners count for use case-8
console.log('Use case-8: Total registered listeners count is '+ eventEmitter.listenerCount('usecase8'))
//Use case-9 (returns all active eventNames)
console.log('all registered event names for all use cases : ', eventEmitter.eventNames())
//Use case-10 (addListener, removeListener, removeAllListeners functions)
//addListener and removeListener are exactely same as on and off respectively
//removeAllListeners will remove all the registered listeners for that event
<file_sep>NodeJS Event Emitter class with variety of use cases with examples of different functions offers by event emitter class for my blog article.
Most common and used functions:
1. eventEmitter.emit(eventName[, ...args])
2. eventEmitter.on(eventName, listener)
3. eventEmitter.once(eventName, listener)
4. eventEmitter.off(eventName, listener)
5. eventEmitter.addListener(eventName, listener)
6. eventEmitter.removeListener(eventName, listener)
7. eventEmitter.removeAllListeners([eventName])
8. eventEmitter.listenerCount(eventName)
9. eventEmitter.eventNames()
Steps to run:
1. clone git repository.
2. run node app.js
| 6e3b4739a15c30c421462b16235383dabf6f0152 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | shwetavw/emitter | a3bf35b3873132d6d4de666e0e452c4bf5c98026 | 8811ba78d5091d05f7f7c0f173c723514bb343e7 |
refs/heads/master | <repo_name>Okhane/friendly-adventure<file_sep>/src/Unittest_Calculatrice.py
import unittest
from tkinter import *
import tkinter
from GUITests import calc
'''Tests for the addition'''
class AddTestSuite(unittest.TestCase):
'''Adding 3 and 6 together should be 9.00'''
def test_TwoPosInt(self):
x = calc.evaluateExpression(self,'3+6')
self.assertEqual(x, 9.0)
'''Adding -4 and 23.4 should be 19.40'''
def test_NegIntPosfloat(self):
x = calc.evaluateExpression(self,'-4 + 23.4')
self.assertEqual(x, 19.4)
'''Adding -23423 and 467.324 should be 23890.32'''
def test_IntAndFloat(self):
x = calc.evaluateExpression(self, '23423 + 467.324')
self.assertEqual(x, 23890.32)
'''Adding 467.324 and -23423 should be 23890.32'''
def test_FloatAndInt(self):
x = calc.evaluateExpression(self, '467.324 + 23423')
self.assertEqual(x, 23890.32)
'''Adding 3.5 and 7.4333 should be 10.93'''
def test_FloatAndFloat(self):
x = calc.evaluateExpression(self, ' 3.5 + 7.4333')
self.assertEqual(x, 10.93)
'''Adding -4 and 0 should be -4.00'''
def test_NegtAndZero(self):
x = calc.evaluateExpression(self, ' -4 + 0')
self.assertEqual(x, -4.0)
'''Adding 99999980000001 and 19999998 should be 99999999999999.0'''
def test_TwoBigInts(self):
x = calc.evaluateExpression(self, ' 99999980000001 + 19999998')
self.assertEqual(x, 99999999999999.0)
'''Adding 99999980000001.001 and 19999998.999 should be 00 1000000000000.0'''
def test_TwoBigFloats(self):
x = calc.evaluateExpression(self, ' 99999980000001.001 + 19999998.999')
self.assertEqual(x, 100000000000000.0)
class SubtractTestSuite(unittest.TestCase):
'''Subtracting 4 from 2 should be -2'''
def test_PosIntAndPosInt(self):
x = calc.evaluateExpression(self,'2 - 4')
self.assertEqual(x, -2)
'''Subtracting 0 from -6 should be -6'''
def test_NegIntAndZero(self):
x = calc.evaluateExpression(self, '-6 - 0')
self.assertEqual(x, -6)
'''Subtracting 0 from 42 should be 42'''
def test_PosIntAndZero(self):
x = calc.evaluateExpression(self, '42 - 0')
self.assertEqual(x, 42)
'''Subtracting 2.25 from -2 should be -4.25'''
def test_NegIntAndPosFloat(self):
x = calc.evaluateExpression(self, '-2 - 2.25')
self.assertEqual(x, -4.25)
'''Subtracting 9 from 14.56 should be 5.56'''
def test_PosFloatAndPosInt(self):
x = calc.evaluateExpression(self, '14.56 - 9')
self.assertEqual(x, 5.56)
'''Subtracting 1.35 from 9 should be 7.65'''
def test_PosIntAndPosFloat(self):
x = calc.evaluateExpression(self, '9 - 1.35')
self.assertEqual(x, 7.65)
'''Subtracting 1.35 from 0.29 should be -1.06'''
def test_PosIntAndPosFloat(self):
x = calc.evaluateExpression(self, '0.29 - 1.35')
self.assertEqual(x, -1.06)
'''Adding a substraction of 10.99 to 1000 should be 989.01'''
def test_AddSignWithMinusSign(self):
x = calc.evaluateExpression(self, '1000 + - 10.99')
self.assertEqual(x, 989.01)
'''Subtracting 23.555555555 from 1.00001293423 should be -22.55554262077'''
def test_TwoLargeDecimals(self):
x = calc.evaluateExpression(self, '1.00001293423 - 23.555555555')
self.assertEqual(x, -22.56)
'''Subtracting 134514353425 from 64353673457867 should be 64219159104442'''
def test_TwoLargeInt(self):
x = calc.evaluateExpression(self, '64353673457867 - 134514353425')
self.assertEqual(x, 64219159104442)
class MultTestSuite(unittest.TestCase):
'''Multiplying 3 and 6 together should be 18.00'''
def test_TwoPosInt(self):
x = calc.evaluateExpression(self,'3*6')
self.assertEqual(x, 18.00)
'''Multiplying -60 and 13.32 together should be -799.20'''
def test_NegIntPosfloat(self):
x = calc.evaluateExpression(self,'-60 * 13.32')
self.assertEqual(x, -799.20)
'''Multiplying 182 and -75.987 together should be 18'''
def test_PosIntAndNegFloat(self):
x = calc.evaluateExpression(self, '182 * -75.987')
self.assertEqual(x, -13829.63)
'''Multiplying 467.324 and 0 should be 0.00'''
def test_FloatAndZero(self):
x = calc.evaluateExpression(self, '467.324 * 0')
self.assertEqual(x, 0.00)
'''Multiplying 0 and 999999 should be 0.00'''
def test_ZeroAndInt(self):
x = calc.evaluateExpression(self, ' 0 * 999999')
self.assertEqual(x, 0.00)
'''Multiplying 99999999 and 99999999 should be 99999980000001
Reaches display limits'''
def test_TwoBigInts(self):
x = calc.evaluateExpression(self, ' 9999999 * 9999999')
self.assertEqual(x, 99999980000001.0)
'''Multiplying 9999999.999 and 9999999.002 should be 99999990010000.00'''
def test_TwoBigFloats(self):
x = calc.evaluateExpression(self, ' 9999999.999 * 9999999.002')
self.assertEqual(x, 99999990010000.0)
class DivTestSuite(unittest.TestCase):
'''Divizing 18 by 6 should be 3.0'''
def test_TwoPosInt(self):
x = calc.evaluateExpression(self,'18 / 6')
self.assertEqual(x, 3.0)
'''Divizing -60 by 13.32 should be -4.51'''
def test_NegIntPosfloat(self):
x = calc.evaluateExpression(self,'-60 / 13.32')
self.assertEqual(x, -4.50)
'''Divizing 182 by -75.987 should be -2.40'''
def test_PosIntAndNegFloat(self):
x = calc.evaluateExpression(self, '182 / -75.987')
self.assertEqual(x, -2.40)
'''Divizing 467.324 and 0 should generate exception'''
def test_FloatAndZero(self):
try:
x = calc.evaluateExpression(self, '467.324 / 0')
except ZeroDivisionError:
print("")
class ChainOperationsTestSuite(unittest.TestCase):
'''Should consider operation priority and result to -586.74'''
def test_AllFourOperatorsWithFloatAndInt(self):
x = calc.evaluateExpression(self,'104 + 67 - 64.58 / 3 * 35.2')
self.assertEqual(x, -586.74)
'''Should handle parenthesis and result to 1325.79'''
def test_Parenthesis(self):
x = calc.evaluateExpression(self, '(104 + (67 - (64.58 / 2)) * 35.2)')
self.assertEqual(x, 1325.79)
class BadInputsTestSuite(unittest.TestCase):
'''Should not accept chars inside the operation'''
def test_Chars(self):
try:
x = calc.evaluateExpression(self,'Chars should not be accepted 3 + 4')
except:
self.assertTrue(True)
else:
self.assertTrue(False)
'''Should not accept a division by zero'''
def test_DivisonByZero(self):
try:
x = calc.evaluateExpression(self, '3 / 0')
except:
self.assertTrue(True)
else:
self.assertTrue(False)
'''Should not accept many zeros before a number'''
def test_ManyZeros(self):
try:
x = calc.evaluateExpression(self, '000005 + 2')
except:
self.assertTrue(True)
else:
self.assertTrue(False)
'''Should accept a comma followed by a number'''
def test_NoZeroAndComma(self):
x = calc.evaluateExpression(self, '.45 - .32')
self.assertEqual(x, 0.13)
if __name__ == '__main__':
unittest.main()
<file_sep>/src/GUITests.py
"""
Application Calculatrice avec tests de l'interface graphique intégrés
Par <NAME> et
<NAME>
"""
from tkinter import *
import math
import time
import random
import mock
from mock import MagicMock
class calc:
flag = 0
# Math evaluation of entry
def evaluateExpression(self, answer):
return round(eval(answer), 2)
def egale(self):
try:
self.value = self.evaluateExpression(self.e.get())
except ZeroDivisionError:
self.e.delete(0, END)
self.e.insert(0, 'Entree invalide')
self.flag = 1
else:
self.e.delete(0, END)
self.e.insert(0, format(self.value, '.2f'))
self.flag = 1
def test(event):
calc.egale(obj)
# Delete display
def clearall(self):
self.e.delete(0, END)
# Delete last character
def clear_1(self):
self.txt = self.e.get()[:-1]
self.e.delete(0, END)
self.e.insert(0, self.txt)
def action(self, val):
if self.flag == 1:
self.clearall()
self.flag = 0
self.e.insert(END, val)
# GUI init
def __init__(self, master):
root.resizable(0, 0)
self.flag = 0
master.title('Calculatrice')
master.geometry()
self.e = Entry(master, width=18, justify=RIGHT, font=("Arial", 30))
self.e.grid(columnspan=5, pady=5, sticky=W)
self.e.focus_set()
# bUILDING BUTTONS
B0 = Button(master, font=("Arial", 13), text="=", width=10, height=3, command=lambda: self.egale())
B0.grid(row=7, column=0, sticky=N + S + E + W, columnspan=4)
B1 = Button(master, font=("Arial", 13), text="±", width=10, height=3, command=lambda: self.action('-'))
B1.grid(row=6, column=1, sticky=N + S + E + W)
B2 = Button(master, font=("Arial", 13), text='AC', width=10, height=3, command=lambda: self.clearall())
B2.grid(row=6, column=0, sticky=N + S + E + W)
B3 = Button(master, font=("Arial", 13), text='DEL', width=10, height=3, command=lambda: self.clear_1())
B3.grid(row=5, column=0, sticky=N + S + E + W)
B4 = Button(master, font=("Arial", 13), text="+", width=10, height=3, command=lambda: self.action('+'))
B4.grid(row=4, column=3, sticky=N + S + E + W)
B5 = Button(master, font=("Arial", 13), text="*", width=10, height=3, command=lambda: self.action('*'))
B5.grid(row=2, column=3, sticky=N + S + E + W)
B6 = Button(master, font=("Arial", 13), text="-", width=10, height=3, command=lambda: self.action('-'))
B6.grid(row=3, column=3, sticky=N + S + E + W)
B7 = Button(master, font=("Arial", 13), text="/", width=10, height=3, command=lambda: self.action('/'))
B7.grid(row=5, column=3, sticky=N + S + E + W)
B8 = Button(master, font=("Arial", 13), text="7", width=10, height=3, bg='white',
command=lambda: self.action('7'))
B8.grid(row=2, column=0, sticky=N + S + E + W)
B9 = Button(master, font=("Arial", 13), text="8", width=10, height=3, bg='white',
command=lambda: self.action(8))
B9.grid(row=2, column=1, sticky=N + S + E + W)
B10 = Button(master, font=("Arial", 13), text="9", width=10, height=3, bg='white',
command=lambda: self.action(9))
B10.grid(row=2, column=2, sticky=N + S + E + W)
B11 = Button(master, font=("Arial", 13), text="4", width=10, height=3, bg='white',
command=lambda: self.action(4))
B11.grid(row=3, column=0, sticky=N + S + E + W)
B12 = Button(master, font=("Arial", 13), text="5", width=10, height=3, bg='white',
command=lambda: self.action(5))
B12.grid(row=3, column=1, sticky=N + S + E + W)
B13 = Button(master, font=("Arial", 13), text="6", width=10, height=3, bg='white',
command=lambda: self.action(6))
B13.grid(row=3, column=2, sticky=N + S + E + W)
B14 = Button(master, font=("Arial", 13), text="1", width=10, height=3, bg='white',
command=lambda: self.action(1))
B14.grid(row=4, column=0, sticky=N + S + E + W)
B15 = Button(master, font=("Arial", 13), text="2", width=10, height=3, bg='white',
command=lambda: self.action(2))
B15.grid(row=4, column=1, sticky=N + S + E + W)
B16 = Button(master, font=("Arial", 13), text="3", width=10, height=3, bg='white',
command=lambda: self.action(3))
B16.grid(row=4, column=2, sticky=N + S + E + W)
B17 = Button(master, font=("Arial", 13), text="0", width=10, height=3, bg='white',
command=lambda: self.action(0))
B17.grid(row=5, column=1, sticky=N + S + E + W)
B18 = Button(master, font=("Arial", 13), text=".", width=10, height=3,
command=lambda: self.action('.'))
B18.grid(row=5, column=2, sticky=N + S + E + W)
B19 = Button(master, font=("Arial", 13), text="(", width=10, height=3,
command=lambda: self.action('('))
B19.grid(row=6, column=2, sticky=N + S + E + W)
B20 = Button(master, font=("Arial", 13), text=")", width=10, height=3,
command=lambda: self.action(')'))
B20.grid(row=6, column=3, sticky=N + S + E + W)
# List of possible number buttons
numberButtonArray = [B8, B9, B10, B11, B12, B13, B14, B15, B16, B17]
# List of mathematical operator buttons
operatorButtonArray = [B4, B5, B6, B7]
for i in range(1,32):
cpt = 0
generatedByButtons = ""
loopCondition = True
while(loopCondition or cpt < 2):
if(cpt > 0):
# Add an operator
rand = self.randomOperatorGen()
operatorButtonArray[rand].invoke()
generatedByButtons = generatedByButtons + operatorButtonArray[rand]['text']
# Add atleast one number at first
rand = self.randomNumberGen()
numberButtonArray[rand].invoke()
generatedByButtons = generatedByButtons + numberButtonArray[rand]['text']
# While generator returns True, add numbers to the integer part of the expression
while (self.randomBoolGen()):
rand = self.randomNumberGen()
numberButtonArray[rand].invoke()
generatedByButtons = generatedByButtons + numberButtonArray[rand]['text']
# Randomly decide if there will be a decimal value
if(self.randomBoolGen()):
B18.invoke()
generatedByButtons = generatedByButtons + B18['text']
rand = self.randomNumberGen()
numberButtonArray[rand].invoke()
generatedByButtons = generatedByButtons + numberButtonArray[rand]['text']
# While generator returns True, add numbers to the decimal part of the expression
while (self.randomBoolGen()):
rand=self.randomNumberGen()
numberButtonArray[rand].invoke()
generatedByButtons = generatedByButtons + numberButtonArray[rand]['text']
cpt += 1
# Start deciding if we should keep going once we have atleast 2 numbers and 1 operator inbetween
if(cpt>2):
loopCondition = self.randomBoolGen()
displayedOp = self.e.get()
# Compare what is displayed on the GUI and what the events made internally
print('Activated buttons : ' + generatedByButtons)
print('Display is : ' + displayedOp)
if (generatedByButtons == displayedOp):
print('----------> OK : Display matches buttons sequence <----------')
else:
print('********** ERROR : Display does not match buttons sequence! **********')
try:
if (eval(displayedOp) == eval(generatedByButtons)):
print('----------> OK : Mathematic expressions provided same results <----------.')
else:
print('********** Warning : Mathematic expressions provided different results **********')
except:
print('----------> OK : Invalid input ash been caught <----------.')
self.clearall()
#print('Trying button AC')
B2.invoke()
displayedOp = self.e.get()
if (displayedOp == ""):
print('----------> OK : Display has been cleared <----------')
else:
print('********** ERROR : Display has not been cleared! **********')
B19.invoke()
B20.invoke()
B1.invoke()
displayedOp = self.e.get()
if (displayedOp == "()-"):
print('----------> OK : Display matches buttons sequence <----------')
else:
print('********** ERROR : Display does not match buttons sequence! **********')
B3.invoke()
B3.invoke()
displayedOp = self.e.get()
if (displayedOp == "("):
print('----------> OK : Display matches buttons sequence <----------')
else:
print('********** ERROR : Display does not match buttons sequence! **********')
self.clearall()
#Testing "=" with mock
self.egale = MagicMock(return_value = '----------> OK : The "=" button has been verified with mock <----------')
print(B0.invoke())
print('********** RUNNED ' + str(i+4) +' GUI TESTS **********')
def randomNumberGen(self):
rand = random.randint(0, 9)
return rand
def randomOperatorGen(self):
rand = random.randint(0, 3)
return rand
def randomBoolGen(self):
rand = random.randint(0,1)
if(rand == 0):
return False
else:
return True
# Creating object + mainloop
root = Tk()
obj = calc(root)
root.bind("<Return>", lambda event: calc.test(event)) # Attribue la fonction 'egale' a la touche Enter
root.mainloop()
<file_sep>/src/Calculatrice .py
"""
Application Calculatrice avec tests de l'interface graphique intégrés
Par <NAME> et
<NAME>
Pour le cours de VVL
"""
from tkinter import *
import math
import time
import random
import mock
from mock import MagicMock
class calc:
flag = 0
# Math evaluation of entry
def evaluateExpression(self, answer):
return round(eval(answer), 2)
def egale(self):
try:
self.value = self.evaluateExpression(self.e.get())
except ZeroDivisionError:
self.e.delete(0, END)
self.e.insert(0, 'Entree invalide')
self.flag = 1
else:
self.e.delete(0, END)
self.e.insert(0, format(self.value, '.2f'))
self.flag = 1
def test(event):
calc.egale(obj)
# Delete display
def clearall(self):
self.e.delete(0, END)
# Delete last character
def clear_1(self):
self.txt = self.e.get()[:-1]
self.e.delete(0, END)
self.e.insert(0, self.txt)
def action(self, val):
if self.flag == 1:
self.clearall()
self.flag = 0
self.e.insert(END, val)
# GUI init
def __init__(self, master):
root.resizable(0, 0)
self.flag = 0
master.title('Calculatrice')
master.geometry()
self.e = Entry(master, width=18, justify=RIGHT, font=("Arial", 30))
self.e.grid(columnspan=5, pady=5, sticky=W)
self.e.focus_set()
# bUILDING BUTTONS
B0 = Button(master, font=("Arial", 13), text="=", width=10, height=3, command=lambda: self.egale())
B0.grid(row=7, column=0, sticky=N + S + E + W, columnspan=4)
B1 = Button(master, font=("Arial", 13), text="±", width=10, height=3, command=lambda: self.action('-'))
B1.grid(row=6, column=1, sticky=N + S + E + W)
B2 = Button(master, font=("Arial", 13), text='AC', width=10, height=3, command=lambda: self.clearall())
B2.grid(row=6, column=0, sticky=N + S + E + W)
B3 = Button(master, font=("Arial", 13), text='DEL', width=10, height=3, command=lambda: self.clear_1())
B3.grid(row=5, column=0, sticky=N + S + E + W)
B4 = Button(master, font=("Arial", 13), text="+", width=10, height=3, command=lambda: self.action('+'))
B4.grid(row=4, column=3, sticky=N + S + E + W)
B5 = Button(master, font=("Arial", 13), text="*", width=10, height=3, command=lambda: self.action('*'))
B5.grid(row=2, column=3, sticky=N + S + E + W)
B6 = Button(master, font=("Arial", 13), text="-", width=10, height=3, command=lambda: self.action('-'))
B6.grid(row=3, column=3, sticky=N + S + E + W)
B7 = Button(master, font=("Arial", 13), text="/", width=10, height=3, command=lambda: self.action('/'))
B7.grid(row=5, column=3, sticky=N + S + E + W)
B8 = Button(master, font=("Arial", 13), text="7", width=10, height=3, bg='white',
command=lambda: self.action('7'))
B8.grid(row=2, column=0, sticky=N + S + E + W)
B9 = Button(master, font=("Arial", 13), text="8", width=10, height=3, bg='white',
command=lambda: self.action(8))
B9.grid(row=2, column=1, sticky=N + S + E + W)
B10 = Button(master, font=("Arial", 13), text="9", width=10, height=3, bg='white',
command=lambda: self.action(9))
B10.grid(row=2, column=2, sticky=N + S + E + W)
B11 = Button(master, font=("Arial", 13), text="4", width=10, height=3, bg='white',
command=lambda: self.action(4))
B11.grid(row=3, column=0, sticky=N + S + E + W)
B12 = Button(master, font=("Arial", 13), text="5", width=10, height=3, bg='white',
command=lambda: self.action(5))
B12.grid(row=3, column=1, sticky=N + S + E + W)
B13 = Button(master, font=("Arial", 13), text="6", width=10, height=3, bg='white',
command=lambda: self.action(6))
B13.grid(row=3, column=2, sticky=N + S + E + W)
B14 = Button(master, font=("Arial", 13), text="1", width=10, height=3, bg='white',
command=lambda: self.action(1))
B14.grid(row=4, column=0, sticky=N + S + E + W)
B15 = Button(master, font=("Arial", 13), text="2", width=10, height=3, bg='white',
command=lambda: self.action(2))
B15.grid(row=4, column=1, sticky=N + S + E + W)
B16 = Button(master, font=("Arial", 13), text="3", width=10, height=3, bg='white',
command=lambda: self.action(3))
B16.grid(row=4, column=2, sticky=N + S + E + W)
B17 = Button(master, font=("Arial", 13), text="0", width=10, height=3, bg='white',
command=lambda: self.action(0))
B17.grid(row=5, column=1, sticky=N + S + E + W)
B18 = Button(master, font=("Arial", 13), text=".", width=10, height=3,
command=lambda: self.action('.'))
B18.grid(row=5, column=2, sticky=N + S + E + W)
B19 = Button(master, font=("Arial", 13), text="(", width=10, height=3,
command=lambda: self.action('('))
B19.grid(row=6, column=2, sticky=N + S + E + W)
B20 = Button(master, font=("Arial", 13), text=")", width=10, height=3,
command=lambda: self.action(')'))
B20.grid(row=6, column=3, sticky=N + S + E + W)
# Creating object + mainloop
root = Tk()
obj = calc(root)
root.bind("<Return>", lambda event: calc.test(event)) # Attribue la fonction 'egale' a la touche Enter
root.mainloop()
| 9ed363997b7c017a873e99aa31cd342139dc7383 | [
"Python"
]
| 3 | Python | Okhane/friendly-adventure | ada5c992836697a87eee6047a43db9554c790684 | 50e1ab1e3d5c2f65a91f2c26020f21a8732d5477 |
refs/heads/master | <repo_name>pancx/node-kobuki<file_sep>/README.md
Node-kobuki
===========
Kobuki is a lowcost mobile research robot. Kobuki has highly reliable odometry and long battery hours and provides power for an external sensor and actuator. This project aims to implement the control of kobuki by using node.js and offer apis for javascript developers.
# Installation:
Install the following basic dependencies refer to their official pages.<br>
1. [Node.js](https://nodejs.org/en/)<br>
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Recommend that download the source of stable version, compile and install. <br>
2. [node-gyp](https://www.npmjs.com/package/node-gyp)<br>
node-gyp is a cross-platform command-line tool written in Node.js for compiling native addon modules for Node.js.<br>
You can install with npm:<br>
```
$ npm install -g node-gyp
```
3. [Kobuki linux driver](https://yujinrobot.github.io/kobuki/doxygen/enInstallationLinuxGuide.html)<br>
Install the kobuki driver for Linux.<br>
(You may need to install some dependencies like libftdi-dev and libusb-dev.)<br>
4. [widl-nan](https://github.com/01org/widl-nan)<br>
This toolchain transcompiles W3C Web IDL and Version 2 to the NAN C++ code. This tool improve efficiency of Node.js Addon developing, allows developers focus on spec definition and actual implementation codes.<br>
Clone this project to your workspace and install widl-nan. Notice the step `Compile your Web IDL`, repalce it by:<br>
```
$ ./node_modules/.bin/widl-nan kobuki.widl
```
And do not init helper files.<br>
# Kobuki APIs
You can find its native apis on its official page [kobuki_driver: Getting Started](https://yujinrobot.github.io/kobuki/doxygen/enGettingStartedGuide.html). <br>
This project provides javascript apis and try best to ensure their names, args and return values seem as the native apis.<br>
## **Raw Data**
The kobuki driver runs a background thread which continually retrieves packets from the kobuki, saving the raw data, and additionally doing some processing before updating the current state of the robot.
Raw data can be accessed at any time by one of the following getXXX commands:
**getCoreSensorData**<br>
**getDockIRData**<br>
**getCliffData**<br>
**getCurrentData**<br>
**getGpInputData**<br>
**getInertiaData**<br>
**getRawInertiaData**<br>
**getControllerInfoData**<br>
The gyro provides both filtered yaw angle as well as unfiltered 3-axis inertial data hence the two calls above.
## **Processed Data and Status**
The following are convenience methods for accessing the current state of the robot
**batteryStatus**<br>
**getHeading**<br>
**getAngularVelocity**<br>
**versionInfo** : hardware, firmware and software version strings.<br>
**getWheelJointStates**<br>
**isAlive** : true if a kobuki is detected and streaming data.<br>
**isEnabled** : true if the motor power is enabled<br>
**isShutdown** : true if the worker threads for this driver have been shut down.<br>
## **Soft Commands**
**resetOdometry**<br>
## **Hard Commands**
**setBaseControl**<br>
**setLed**<br>
**setDigitalOutput**<br>
**setExternalPower**<br>
**playSoundSequence**<br>
**setControllerGain**<br>
**getControllerGain**<br>
## **The Differential Drive Module**
The final function of importance is the **updateOdometry** method. This updates the current odometry state of the robot, fusing encoder and gyro heading data with the previous known state. For deterministic odometry, it is important this method is called each time a new data packet from the kobuki arrives. Refer to the simple control loop example for more information and working code to illustrate.
## **Events**
Sigslots are the primary way of kobuki driver to handle events emitted by the kobuki driver (c.f. with the usual function callbacks with void function pointers as arguments). You can go straight to the official documentation [Sigslots](https://yujinrobot.github.io/kobuki/doxygen/enSigslotsGuide.html) and [ecl_sigslots](http://wiki.ros.org/ecl_sigslots) to find more information. It provided an asynchronous way to control the robot indeed. This project implements Sigslots by inheriting EventEmitter(learn more in its page [EventEmitter](https://www.npmjs.com/package/events)) and overriding **addListener** and **removeListener**. <br>
The following represent the available events
* **streamdata** : informs when a new data packet has arrived from the kobuki
* **rosdebug** : relay debug messages
* **rosinfo** : relay info messages
* **roswarn** : relay warning messages
* **roserror** : relay error messages
* **buttonevent** : receive an event when a button state changes
* **bumperevent** : receive an event when the bumper state changes
* **cliffevent** : receive an event when a cliff sensor state changes
* **wheelevent** : receive an event when the wheel state (in/out) changes
* **powerevent** : receive an event when the power/charging state changes
* **inputevent** : receive an event when the gpio state changes
* **robotevent** : receive an event when the robot state changes
* **versioninfo** : receive version info strings on this signal
# Test & usage cases
Refer to the cases in the `test` folder to learn more usage of the javascript apis.
```
$ node test.js
```
<file_sep>/test/getWheelJointStates.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
var wheelJointStates = {
wheelLeftAngle: 0,
wheelLeftAngleRate: 0,
wheelRightAngle: 0,
wheelRightAngleRate: 0
};
while(true)
{
sleep(200);
/**
* @param {Object} wheelJointStates - defined as above
* @return {Object} WheelJointStates
*/
wheelJointStates = kobuki.getWheelJointStates(wheelJointStates);
console.log('Wheel left angle is: ' + wheelJointStates.wheelLeftAngle);
console.log('Wheel left angle rate is: ' + wheelJointStates.wheelLeftAngleRate);
console.log('Wheel right angle is: ' + wheelJointStates.wheelRightAngle);
console.log('Wheel right angle rate is: ' + wheelJointStates.wheelRightAngleRate);
}
<file_sep>/test/getCliffData.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
while(true)
{
sleep(100);
/**
* Get the cliff sensors' data
* @return {Object} CliffData has one menber, bottom, which is array of left, right and center cliff sensors' data.
*/
var cliffData = kobuki.getCliffData();
console.log('The cliff data is: [' + cliffData.bottom[0] + ', ' + cliffData.bottom[1] + ', ' + cliffData.bottom[2] + ']');
}
<file_sep>/test/versionInfo.js
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
/**
* Get the version info of firmware, hardware and software, and the udid of Kobuki.
* @return {Object} VersionInfo has four string members, firmware, hardware, software, and udid.
*/
var versionInfo = kobuki.versionInfo();
console.log('The firmware is: ' + versionInfo.firmware);
console.log('The hardware is: ' + versionInfo.hardware);
console.log('The software is: ' + versionInfo.software);
console.log('The udid is: ' + versionInfo.udid);
<file_sep>/test/getStatus.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
while(true)
{
sleep(300);
/**
* @return {Boollean} wheher kobuki is on.
*/
console.log('Is alive? ' + kobuki.isAlive());
/**
* @return {Boollean} wheher the motors are enabled.
*/
console.log('Is enabled? ' + kobuki.isEnabled());
/**
* @return {Boollean} wheher kobuki is shut down.
*/
console.log('Is shutdown? ' + kobuki.isShutdown());
}
<file_sep>/test/getRawInertiaData.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
while(true)
{
sleep(500);
/**
* Get raw inertia data
* @return {Object} ThreeAxisGyroData has frameId, followedDataLength and data
*/
var inertiaData = kobuki.getRawInertiaData();
console.log('The frameId is: [' + inertiaData.frameId + ']');
console.log('The followed data Length is: [' + inertiaData.followedDataLength + ']');
var i = 0;
console.log('The inertia data is: ');
while (i<inertiaData.followedDataLength)
{
console.log(inertiaData.data[i]);
i=i+1;
}
}
<file_sep>/test/updateOdometry.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
kobuki.setLed('led1', 'red');
var p = {
x:1,
y:1,
heading:1
};
var dx = 0, dth = 0;
/**
* updateOdometry will return new pose, x, y and hending, and the increment of mileage and heading from last call of updateOdometry.
* pose is updated all the time from Kobuki is started.
* @param {Object} p - manually reset the odometry, it can also be null.
* @return {Object} new pose
*/
var pose = kobuki.updateOdometry(p);
while (true)
{
sleep(200);
var pose = kobuki.updateOdometry();
dx = dx + pose.dx;
dth = dth + pose.dth;
console.log('[' + pose.x + ', ' + pose.y + ', ' + pose.heading + ']');
console.log('[' + dx + ', ' + dth + ']');
}
<file_sep>/test/setLed.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
while(true)
{
/**
* setLed could control the two Leds in the Kobuki.
* @param {String} Led number: 'led1', 'led2'
* @param {String} Led color: 'red', 'orange', 'green', 'black'
*/
kobuki.setLed('led1', 'red');
kobuki.setLed('led2', 'orange');
sleep(500);
kobuki.setLed('led1', 'orange');
kobuki.setLed('led2', 'green');
sleep(500);
kobuki.setLed('led1', 'green');
kobuki.setLed('led2', 'black');
sleep(500);
kobuki.setLed('led1', 'black');
kobuki.setLed('led2', 'red');
sleep(500);
}
<file_sep>/test/getHeading.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
while(true)
{
sleep(100);
/**
* Get the heading of Kobuki
* @return {Number} the heading of Kobuki
*/
var heading = kobuki.getHeading();
console.log('The heading is: ' + heading);
}
<file_sep>/test/getAngularVelocity.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
while(true)
{
sleep(100);
/**
* Get the angular velocity
* @return {Number} the angular velocity
*/
var value = kobuki.getAngularVelocity();
console.log('The angular velocity is: ' + value);
}
<file_sep>/binding.gyp
# Add your copyright and license header
#
{
"targets": [
{
"target_name": "node-kobuki",
"sources": [
"addon.cpp",
"gen/nan__kobuki_manager.cpp",
"kobuki_manager.cpp",
],
"include_dirs": [
"<!(node -e \"require('nan')\")",
".",
"../kobuki_core/install/include",
"../kobuki_core/src/ecl_core/ecl_eigen/include/eigen3.1.2",
"../kobuki_core/src/ecl_core/ecl_eigen/include/eigen3.1.2/Eigen"
],
"cflags!": [
"-fno-exceptions"
],
"cflags": [
"-std=c++11"
],
"cflags_cc!": [
"-fno-exceptions"
],
"libraries": [
"~/kobuki_core/install/lib/libkobuki.so",
"~/kobuki_core/install/lib/libecl_time.so",
"~/kobuki_core/install/lib/libecl_devices.so",
"~/kobuki_core/install/lib/libecl_exceptions.so",
"~/kobuki_core/install/lib/libecl_threads.so"
],
"xcode_settings": {
"OTHER_CFLAGS": [
"-std=c++11"
]
},
"conditions": [
[
"OS!=\"win\"",
{
"cflags+": [
"-std=c++11"
],
"cflags_c+": [
"-std=c++11"
],
"cflags_cc+": [
"-std=c++11"
]
}
],
[
"OS==\"mac\"",
{
"xcode_settings": {
"OTHER_CPLUSPLUSFLAGS": [
"-std=c++11",
"-stdlib=libc++"
],
"OTHER_LDFLAGS": [
"-stdlib=libc++"
],
"GCC_ENABLE_CPP_EXCEPTIONS": "YES",
"MACOSX_DEPLOYMENT_TARGET": "10.8"
}
}
]
]
}
]
}
<file_sep>/test/setDigitalOutput.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
var digitalOutput = {
values: [false, false, false, false],
mask: [false, false, false, false]
};
/**
* Kobuki has 4xdigital output. This function could set digital output.
* @param {Object} digitalOutput - Two arrays of boolean value to control the digital output.
*/
kobuki.setDigitalOutput(digitalOutput);
sleep(1000);//It takes some time for command to reach the kobuki.
<file_sep>/test.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('./build/Release/node-kobuki');
var kobuki = new addon.KobukiManager("/ttyUSB0");
//var kobuki = new Kobuki();
kobuki.setLed("led1", "red");
//kobuki.setBaseControl(-0.1, 0.2);
while(1)
{
sleep(200);
var pose = kobuki.updateOdometry();
console.log(pose.x);
console.log(pose.y);
console.log(pose.heading);
}
<file_sep>/test/playSoundSequence.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
/**
* play the build-in sound of Kobuki
* @param {String} SoundSequences - 'on', 'off', 'recharge', 'button', 'error', 'cleaningStart', 'cleaningEnd'.
*/
kobuki.playSoundSequence('on');
sleep(100);
kobuki.playSoundSequence('off');
sleep(100);
kobuki.playSoundSequence('recharge');
sleep(100);
kobuki.playSoundSequence('button');
sleep(100);
kobuki.playSoundSequence('error');
sleep(100);
kobuki.playSoundSequence('cleaningStart');
sleep(100);
kobuki.playSoundSequence('cleaningEnd');
sleep(100);
<file_sep>/test/getCurrentData.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
while(true)
{
sleep(100);
/**
* Get the current data
* @return {Object} CurrentData has current, array of current data
*/
var currentData = kobuki.getCurrentData();
console.log('The cliff data is: [' + currentData.current[0] + ', ' + currentData.current[1] + ']');
}
<file_sep>/test/events.js
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
/**
* This project implements Sigslots by inheriting EventEmitter and overriding addListener and removeListener.
* So you can use the same functions of EventEmitter to handle kobuki events.
* Functions of EventEmitter: addListener, on, once, removeListener, removeAllListeners, setMaxListeners, listeners, emit
* You can find more details in the official doc of node.js
*
* The following are the events and the data they pass
* streamdata : informs when a new data packet has arrived from the kobuki
* - void
* rosdebug : relay debug messages
* - String
* rosinfo : relay info messages
* - String
* roswarn : relay warning messages
* - String
* roserror : relay error messages
* - String
* buttonevent : receive an event when a button state changes
* -Object, state: 'released', 'pressed'. button: 'button0', 'button1', 'button2'
* bumperevent : receive an event when the bumper state changes
* -Object, state: 'released', 'pressed'. bumper: 'left', 'center', 'right'
* cliffevent : receive an event when a cliff sensor state changes
* -Object, state: 'floor', 'cliff'. sensor: 'left', 'center', 'right'
* wheelevent : receive an event when the wheel state (in/out) changes
* -Object, state: 'raised', 'dropped'. wheel: 'left', 'right'
* powerevent : receive an event when the power/charging state changes
* -Object, event: 'unplugged', 'pluggedToAdapter', 'pluggedToDockbase', 'chargeCompleted', 'batteryLow', 'batteryCritical'
* inputevent : receive an event when the gpio state changes
* -Object, values : Array of 4 boolean values
* robotevent : receive an event when the robot state changes
* -Object, state : 'offline', 'online', 'unknown'
* versioninfo : receive version info strings on this signal
* -Object, firmware, hardware, software, udid
*/
// Hint: New data will arrive from the kobuki in 50Hz
/*kobuki.on('newdata', evt => {
console.log('got new data');
});*/
kobuki.on('debug', function(debug) {
console.log('debug');
console.log(debug);
});
kobuki.on('info', function(info) {
console.log('info');
console.log(info);
});
kobuki.on('warn', function(warn) {
console.log('warn');
console.log(warn);
});
kobuki.on('error', function(error) {
console.log('error');
console.log(error);
});
var buttonListener = function(buttonevent) {
console.log(buttonevent.button, buttonevent.state);
}
kobuki.on('buttonevent', buttonListener);
kobuki.on('bumperevent', function(bumperevent) {
console.log(bumperevent.bumper, bumperevent.state);
});
kobuki.on('cliffevent', function(cliffevent) {
console.log(cliffevent.sensor, cliffevent.state);
});
kobuki.on('wheelevent', function(wheelevent) {
console.log(wheelevent.wheel, wheelevent.state);
});
kobuki.on('powerevent', function(powerevent) {
console.log(powerevent.event);
});
kobuki.on('inputevent', function(inputevent) {
console.log(inputevent.values[0], inputevent.values[1], inputevent.values[2], inputevent.values[3]);
});
kobuki.on('robotevent', function(robotevent) {
console.log(robotevent.state);
});
// TODO:kobuki will emit versioninfo when powered on,and the event can't be received correctly.
kobuki.on('versioninfo', function(versionInfo) {
console.log(versionInfo.firmware);
console.log(versionInfo.hardware);
console.log(versionInfo.software);
console.log(versionInfo.udid);
});
/*
kobuki.removeListener('buttonevent', buttonListener);
kobuki.removeAllListeners();
kobuki.once('buttonevent', buttonListener);
*/
<file_sep>/test/batteryStatus.js
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
/**
* Get the status of the battery.
* chargingSource: 'none', 'adapter', 'dock'
* chargingLevel: 'dangerous', 'low', 'healthy', 'maximum'
* chargingState: 'discharging', 'charged', 'charging'
* percent: a percent float number of battery voltage, 100% -> capacity / 5% -> dangerous
* @return {Object} an object with above four menbers
*/
var battery = kobuki.batteryStatus();
console.log('Charging source is: ' + battery.chargingSource);
console.log('Charging level is: ' + battery.chargingLevel);
console.log('Charging state is: ' + battery.chargingState);
console.log('battery percent is: ' + battery.percent.toFixed(1) + '%');
<file_sep>/test/setBaseControl.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
/**
* Send the speed control command to Kobuki
* @param {Number} linear velocity in m/s
* @param {Number} angular velocity in rad/s
*/
kobuki.setBaseControl(0.5, 0.0);
sleep(2000);
kobuki.setBaseControl(0.0, 1.0);
sleep(3141);
kobuki.setBaseControl(0.5, 0.0);
sleep(2000);
kobuki.setBaseControl(0.0, 0.0);
sleep(1000);
<file_sep>/kobuki_manager.cpp
// To add your copyright and license header
#include "kobuki_manager.h"
KobukiManager::KobukiManager() :
slot_stream_data(&KobukiManager::callNewDataEvent, *this),
slot_ros_debug(&KobukiManager::callRosDebug, *this),
slot_ros_info(&KobukiManager::callRosInfo, *this),
slot_ros_warn(&KobukiManager::callRosWarn, *this),
slot_ros_error(&KobukiManager::callRosError, *this),
slot_button_event(&KobukiManager::callButtonEvent, *this),
slot_bumper_event(&KobukiManager::callBumperEvent, *this),
slot_cliff_event(&KobukiManager::callCliffEvent, *this),
slot_wheel_event(&KobukiManager::callWheelEvent, *this),
slot_power_event(&KobukiManager::callPowerEvent, *this),
slot_input_event(&KobukiManager::callInputEvent, *this),
slot_robot_event(&KobukiManager::callRobotEvent, *this),
slot_version_info(&KobukiManager::callVersionInfo, *this)
{
kobuki::Parameters parameters;
parameters.sigslots_namespace = sigslots_namespace;
parameters.device_port = "/dev" + sigslots_namespace;
parameters.enable_acceleration_limiter = false;
kobuki.init(parameters);
kobuki.enable();
ecl::Sleep()(1);
}
KobukiManager::KobukiManager(const std::string& sigslotsNamespace) :
slot_stream_data(&KobukiManager::callNewDataEvent, *this),
slot_ros_debug(&KobukiManager::callRosDebug, *this),
slot_ros_info(&KobukiManager::callRosInfo, *this),
slot_ros_warn(&KobukiManager::callRosWarn, *this),
slot_ros_error(&KobukiManager::callRosError, *this),
slot_button_event(&KobukiManager::callButtonEvent, *this),
slot_bumper_event(&KobukiManager::callBumperEvent, *this),
slot_cliff_event(&KobukiManager::callCliffEvent, *this),
slot_wheel_event(&KobukiManager::callWheelEvent, *this),
slot_power_event(&KobukiManager::callPowerEvent, *this),
slot_input_event(&KobukiManager::callInputEvent, *this),
slot_robot_event(&KobukiManager::callRobotEvent, *this),
slot_version_info(&KobukiManager::callVersionInfo, *this)
{
kobuki::Parameters parameters;
sigslots_namespace = sigslotsNamespace;
parameters.sigslots_namespace = sigslots_namespace;
parameters.device_port = "/dev" + sigslots_namespace;
parameters.enable_acceleration_limiter = false;
kobuki.init(parameters);
kobuki.enable();
ecl::Sleep()(1);
}
KobukiManager::~KobukiManager() {
kobuki.setBaseControl(0,0); // linear_velocity, angular_velocity in (m/s), (rad/s)
kobuki.disable();
}
KobukiManager& KobukiManager::operator = (const KobukiManager& rhs) {
if (&rhs != this) {
// TODO(widl-nan): copy members from rhs
}
return *this;
}
CoreSensorsData KobukiManager::getCoreSensorData() {
CoreSensorsData coreSensors;
kobuki::CoreSensors::Data sensor_data = kobuki.getCoreSensorData();
coreSensors.set_timeStamp(sensor_data.time_stamp);
coreSensors.set_bumper(sensor_data.bumper);
coreSensors.set_wheelDrop(sensor_data.wheel_drop);
coreSensors.set_cliff(sensor_data.cliff);
coreSensors.set_leftEncoder(sensor_data.left_encoder);
coreSensors.set_rightEncoder(sensor_data.right_encoder);
coreSensors.set_leftPwm(sensor_data.left_pwm);
coreSensors.set_rightPwm(sensor_data.right_pwm);
coreSensors.set_buttons(sensor_data.buttons);
coreSensors.set_charger(sensor_data.charger);
coreSensors.set_battery(sensor_data.battery);
coreSensors.set_overCurrent(sensor_data.over_current);
return coreSensors;
}
DockIRData KobukiManager::getDockIRData() {
ArrayHelper helper;
DockIRData dock;
kobuki::DockIR::Data dockir_data = kobuki.getDockIRData();
helper.FromArrayT(dockir_data.docking.begin(), dockir_data.docking.end());
dock.set_docking(helper);
return dock;
}
CliffData KobukiManager::getCliffData() {
ArrayHelper helper;
CliffData cliff;
kobuki::Cliff::Data cliff_data = kobuki.getCliffData();
helper.FromArrayT(cliff_data.bottom.begin(), cliff_data.bottom.end());
cliff.set_bottom(helper);
return cliff;
}
CurrentData KobukiManager::getCurrentData() {
ArrayHelper helper;
CurrentData current;
kobuki::Current::Data current_data = kobuki.getCurrentData();
helper.FromArrayT(current_data.current.begin(), current_data.current.end());
current.set_current(helper);
return current;
}
GpInputData KobukiManager::getGpInputData() {
ArrayHelper helper;
GpInputData gpinput;
kobuki::GpInput::Data gpinput_data = kobuki.getGpInputData();
helper.FromArrayT(gpinput_data.analog_input.begin(), gpinput_data.analog_input.end());
gpinput.set_analogInput(helper);
gpinput.set_digitalInput(gpinput_data.digital_input);
return gpinput;
}
InertiaData KobukiManager::getInertiaData() {
ArrayHelper helper;
InertiaData inertia;
kobuki::Inertia::Data inertia_data = kobuki.getInertiaData();
helper.SetT(0,inertia_data.acc[0]);
helper.SetT(1,inertia_data.acc[1]);
helper.SetT(2,inertia_data.acc[2]);
inertia.set_acc(helper);
inertia.set_angle(inertia_data.angle);
inertia.set_angleRate(inertia_data.angle_rate);
return inertia;
}
ThreeAxisGyroData KobukiManager::getRawInertiaData() {
ArrayHelper helper;
ThreeAxisGyroData gyro;
kobuki::ThreeAxisGyro::Data three_axis_gyro = kobuki.getRawInertiaData();
for (unsigned int i=0; i<three_axis_gyro.followed_data_length; i++)
helper.SetT(i, three_axis_gyro.data[i]);
gyro.set_data(helper);
gyro.set_frameId(three_axis_gyro.frame_id);
gyro.set_followedDataLength(three_axis_gyro.followed_data_length);
return gyro;
}
ControllerInfoData KobukiManager::getControllerInfoData() {
kobuki::ControllerInfo::Data controller_info = kobuki.getControllerInfoData();
ControllerInfoData controllerInfoData;
controllerInfoData.set_type(controller_info.type);
controllerInfoData.set_pGain(controller_info.p_gain);
controllerInfoData.set_iGain(controller_info.i_gain);
controllerInfoData.set_dGain(controller_info.d_gain);
return controllerInfoData;
}
Battery KobukiManager::batteryStatus() {
kobuki::Battery battery = kobuki.batteryStatus();
kobuki::Battery::Level level = battery.level();
Battery batteryStatus;
if(battery.charging_source == battery.None)
batteryStatus.set_chargingSource("none");
else
{
if(battery.charging_source == battery.Adapter)
batteryStatus.set_chargingSource("adapter");
else
{
if(battery.charging_source == battery.Dock)
batteryStatus.set_chargingSource("dock");
}
}
if(level == battery.Dangerous)
batteryStatus.set_chargingLevel("dangerous");
else
{
if(level == battery.Low)
batteryStatus.set_chargingLevel("low");
else
{
if(level == battery.Healthy)
batteryStatus.set_chargingLevel("healthy");
else
{
if(level == battery.Maximum)
batteryStatus.set_chargingLevel("maximum");
}
}
}
if(battery.charging_state == battery.Discharging)
batteryStatus.set_chargingState("discharging");
else
{
if(battery.charging_state == battery.Charged)
batteryStatus.set_chargingState("charged");
else
{
if(battery.charging_state == battery.Charging)
batteryStatus.set_chargingState("charging");
}
}
batteryStatus.set_percent(battery.percent());
return batteryStatus;
}
double KobukiManager::getHeading() {
ecl::Angle<double> value = kobuki.getHeading();
return value;
}
double KobukiManager::getAngularVelocity() {
return kobuki.getAngularVelocity();
}
VersionInfo KobukiManager::versionInfo() {
kobuki::VersionInfo version_info = kobuki.versionInfo();
VersionInfo versionInfo;
versionInfo.set_firmware(version_info.toString(version_info.firmware));
versionInfo.set_hardware(version_info.toString(version_info.hardware));
//versionInfo.set_software(version_info.toString(version_info.software));
versionInfo.set_software(version_info.getSoftwareVersion());
versionInfo.set_udid(version_info.toString(version_info.udid0, version_info.udid1, version_info.udid2));
return versionInfo;
}
WheelJointStates KobukiManager::getWheelJointStates(const WheelJointStates& wheelJointStates) {
double wheel_left_angle = wheelJointStates.get_wheelLeftAngle();
double wheel_left_angle_rate = wheelJointStates.get_wheelLeftAngleRate();
double wheel_right_angle = wheelJointStates.get_wheelRightAngle();
double wheel_right_angle_rate = wheelJointStates.get_wheelRightAngleRate();
kobuki.getWheelJointStates(wheel_left_angle, wheel_left_angle_rate, wheel_right_angle, wheel_right_angle_rate);
WheelJointStates data;
data.set_wheelLeftAngle(wheel_left_angle);
data.set_wheelLeftAngleRate(wheel_left_angle_rate);
data.set_wheelRightAngle(wheel_right_angle);
data.set_wheelRightAngleRate(wheel_right_angle_rate);
return data;
}
bool KobukiManager::isAlive() {
return kobuki.isAlive();
}
bool KobukiManager::isEnabled() {
return kobuki.isEnabled();
}
bool KobukiManager::isShutdown() {
return kobuki.isShutdown();
}
void KobukiManager::resetOdometry() {
kobuki.resetOdometry();
}
void KobukiManager::setBaseControl(const double& linear, const double& angular) {
kobuki.setBaseControl(linear, angular);
}
void KobukiManager::setLed(const std::string& ledNo, const std::string& ledColor) {
kobuki::LedNumber no_enum;
kobuki::LedColour color_enum;
if (ledNo=="led1")
no_enum = kobuki::Led1;
else if (ledNo=="led2")
no_enum = kobuki::Led2;
else
return;
if (ledColor=="orange")
color_enum = kobuki::Orange;
else if (ledColor=="green")
color_enum = kobuki::Green;
else if (ledColor=="black")
color_enum = kobuki::Black;
else if (ledColor=="red")
color_enum = kobuki::Red;
else
return;
kobuki.setLed(no_enum, color_enum);
}
void KobukiManager::setDigitalOutput(const DigitalOutput& digitalOutput) {
ArrayHelper helper1, helper2;
helper1 = digitalOutput.get_values();
helper2 = digitalOutput.get_mask();
kobuki::DigitalOutput digital_output;
for(int i = 0; i<4; i++)
{
digital_output.values[i] = helper1.GetBoolean(i);//values[i];
digital_output.mask[i] = helper2.GetBoolean(i);//mask[i];
}
kobuki.setDigitalOutput(digital_output);
}
void KobukiManager::setExternalPower(const DigitalOutput& digitalOutput) {
ArrayHelper helper1, helper2;
helper1 = digitalOutput.get_values();
helper2 = digitalOutput.get_mask();
kobuki::DigitalOutput digital_output;
for(int i = 0; i<4; i++)
{
digital_output.values[i] = helper1.GetBoolean(i);//values[i];
digital_output.mask[i] = helper2.GetBoolean(i);//mask[i];
}
kobuki.setExternalPower(digital_output);
}
void KobukiManager::playSoundSequence(const std::string& soundSequence) {
kobuki::SoundSequences sound_enum;
if(soundSequence=="on")
sound_enum = kobuki::On;
else if(soundSequence=="off")
sound_enum = kobuki::Off;
else if(soundSequence=="recharge")
sound_enum = kobuki::Recharge;
else if(soundSequence=="button")
sound_enum = kobuki::Button;
else if(soundSequence=="error")
sound_enum = kobuki::Error;
else if(soundSequence=="cleaningStart")
sound_enum = kobuki::CleaningStart;
else if(soundSequence=="cleaningEnd")
sound_enum = kobuki::CleaningEnd;
else
return;
kobuki.playSoundSequence(sound_enum);
}
bool KobukiManager::setControllerGain(const ControllerInfoData& controllerInfoData) {
return kobuki.setControllerGain(controllerInfoData.get_type(), controllerInfoData.get_pGain(), controllerInfoData.get_iGain(), controllerInfoData.get_dGain());
}
bool KobukiManager::getControllerGain() {
return kobuki.getControllerGain();
}
PoseUpdateData KobukiManager::updateOdometry() {
ecl::Pose2D<double> pose_update;
ecl::linear_algebra::Vector3d pose_update_rates;
kobuki.updateOdometry(pose_update, pose_update_rates);
PoseUpdateData poseData;
pose_ecl *= pose_update;
poseData.set_dx(pose_update.x());
poseData.set_dth(pose_update.heading());
poseData.set_x(pose_ecl.x());
poseData.set_y(pose_ecl.y());
poseData.set_heading(pose_ecl.heading());
return poseData;
}
PoseUpdateData KobukiManager::updateOdometry(const PoseUpdateData& pose) {
ecl::Pose2D<double> pose_update;
ecl::linear_algebra::Vector3d pose_update_rates;
kobuki.updateOdometry(pose_update, pose_update_rates);
PoseUpdateData poseData;
pose_ecl.setPose(pose.get_x(), pose.get_y(), pose.get_heading());
pose_ecl *= pose_update;
poseData.set_dx(pose_update.x());
poseData.set_dth(pose_update.heading());
poseData.set_x(pose_ecl.x());
poseData.set_y(pose_ecl.y());
poseData.set_heading(pose_ecl.heading());
return poseData;
}
// Running in kobuki driver thread
void KobukiManager::callNewDataEvent() {
KobukiManager* me = this;
me->async_stream_data.data = me;
uv_async_send(&async_stream_data);
}
void KobukiManager::callRosDebug(const std::string& ros_debug) {
KobukiManager* me = this;
me->ros_debug = ros_debug;
me->async_ros_debug.data = me;
uv_async_send(&async_ros_debug);
}
void KobukiManager::callRosInfo(const std::string& ros_info) {
KobukiManager* me = this;
me->ros_info = ros_info;
me->async_ros_info.data = me;
uv_async_send(&async_ros_info);
}
void KobukiManager::callRosWarn(const std::string& ros_warn) {
KobukiManager* me = this;
me->ros_warn = ros_warn;
me->async_ros_warn.data = me;
uv_async_send(&async_ros_warn);
}
void KobukiManager::callRosError(const std::string& ros_error) {
KobukiManager* me = this;
me->ros_error = ros_error;
me->async_ros_error.data = me;
uv_async_send(&async_ros_error);
}
void KobukiManager::callButtonEvent(const kobuki::ButtonEvent& button_event) {
KobukiManager* me = this;
me->button_event = button_event;
me->async_button_event.data = me;
uv_async_send(&async_button_event);
}
void KobukiManager::callBumperEvent(const kobuki::BumperEvent& bumper_event) {
KobukiManager* me = this;
me->bumper_event = bumper_event;
me->async_bumper_event.data = me;
uv_async_send(&async_bumper_event);
}
void KobukiManager::callCliffEvent(const kobuki::CliffEvent& cliff_event) {
KobukiManager* me = this;
me->cliff_event = cliff_event;
me->async_cliff_event.data = me;
uv_async_send(&async_cliff_event);
}
void KobukiManager::callWheelEvent(const kobuki::WheelEvent& wheel_event) {
KobukiManager* me = this;
me->wheel_event = wheel_event;
me->async_wheel_event.data = me;
uv_async_send(&async_wheel_event);
}
void KobukiManager::callPowerEvent(const kobuki::PowerEvent& power_event) {
KobukiManager* me = this;
me->power_event = power_event;
me->async_power_event.data = me;
uv_async_send(&async_power_event);
}
void KobukiManager::callInputEvent(const kobuki::InputEvent& input_event) {
KobukiManager* me = this;
me->input_event = input_event;
me->async_input_event.data = me;
uv_async_send(&async_input_event);
}
void KobukiManager::callRobotEvent(const kobuki::RobotEvent& robot_event) {
KobukiManager* me = this;
me->robot_event = robot_event;
me->async_robot_event.data = me;
uv_async_send(&async_robot_event);
}
void KobukiManager::callVersionInfo(const kobuki::VersionInfo& version_info) {
KobukiManager* me = this;
me->version_info = const_cast<kobuki::VersionInfo*> (&version_info);
me->async_version_info.data = me;
uv_async_send(&async_version_info);
}
// Running in v8 thread
void KobukiManager::newDataEvent(uv_async_t *handle) {
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
v8::Local<v8::Value> argv[1] = {
Nan::New("newdata").ToLocalChecked()
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 1, argv);
}
void KobukiManager::rosDebug(uv_async_t *handle) {
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
v8::Local<v8::Value> argv[2] = {
Nan::New("debug").ToLocalChecked(),
Nan::New(me->ros_debug).ToLocalChecked()
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
void KobukiManager::rosInfo(uv_async_t *handle) {
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
v8::Local<v8::Value> argv[2] = {
Nan::New("info").ToLocalChecked(),
Nan::New(me->ros_info).ToLocalChecked()
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
void KobukiManager::rosWarn(uv_async_t *handle) {
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
v8::Local<v8::Value> argv[2] = {
Nan::New("warn").ToLocalChecked(),
Nan::New(me->ros_warn).ToLocalChecked()
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
void KobukiManager::rosError(uv_async_t *handle) {
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
v8::Local<v8::Value> argv[2] = {
Nan::New("error").ToLocalChecked(),
Nan::New(me->ros_error).ToLocalChecked()
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
void KobukiManager::buttonEvent(uv_async_t *handle) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
std::string button, state;
switch(me->button_event.button){
case kobuki::ButtonEvent::Button0 : button = "button0"; break;
case kobuki::ButtonEvent::Button1 : button = "button1"; break;
case kobuki::ButtonEvent::Button2 : button = "button2"; break;
}
switch(me->button_event.state){
case kobuki::ButtonEvent::Released : state = "released"; break;
case kobuki::ButtonEvent::Pressed : state = "pressed"; break;
}
v8::Local<v8::Object> js_button_event = v8::Object::New(isolate);
js_button_event->Set(v8::String::NewFromUtf8(isolate, "state"), Nan::New(state).ToLocalChecked());
js_button_event->Set(v8::String::NewFromUtf8(isolate, "button"), Nan::New(button).ToLocalChecked());
v8::Local<v8::Value> argv[2] = {
Nan::New("buttonevent").ToLocalChecked(),
js_button_event
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
void KobukiManager::bumperEvent(uv_async_t *handle) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
std::string bumper, state;
switch(me->bumper_event.bumper){
case kobuki::BumperEvent::Left : bumper = "left"; break;
case kobuki::BumperEvent::Center : bumper = "center"; break;
case kobuki::BumperEvent::Right : bumper = "right"; break;
}
switch(me->bumper_event.state){
case kobuki::BumperEvent::Released : state = "released"; break;
case kobuki::BumperEvent::Pressed : state = "pressed"; break;
}
v8::Local<v8::Object> js_bumper_event = v8::Object::New(isolate);
js_bumper_event->Set(v8::String::NewFromUtf8(isolate, "state"), Nan::New(state).ToLocalChecked());
js_bumper_event->Set(v8::String::NewFromUtf8(isolate, "bumper"), Nan::New(bumper).ToLocalChecked());
v8::Local<v8::Value> argv[2] = {
Nan::New("bumperevent").ToLocalChecked(),
js_bumper_event
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
void KobukiManager::cliffEvent(uv_async_t *handle) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
std::string sensor, state;
switch(me->cliff_event.sensor){
case kobuki::CliffEvent::Left : sensor = "left"; break;
case kobuki::CliffEvent::Center : sensor = "center"; break;
case kobuki::CliffEvent::Right : sensor = "right"; break;
}
switch(me->cliff_event.state){
case kobuki::CliffEvent::Floor : state = "floor"; break;
case kobuki::CliffEvent::Cliff : state = "cliff"; break;
}
v8::Local<v8::Object> js_cliff_event = v8::Object::New(isolate);
js_cliff_event->Set(v8::String::NewFromUtf8(isolate, "state"), Nan::New(state).ToLocalChecked());
js_cliff_event->Set(v8::String::NewFromUtf8(isolate, "sensor"), Nan::New(sensor).ToLocalChecked());
v8::Local<v8::Value> argv[2] = {
Nan::New("cliffevent").ToLocalChecked(),
js_cliff_event
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
void KobukiManager::wheelEvent(uv_async_t *handle) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
std::string wheel, state;
switch(me->wheel_event.wheel){
case kobuki::WheelEvent::Left : wheel = "left"; break;
case kobuki::WheelEvent::Right : wheel = "right"; break;
}
switch(me->wheel_event.state){
case kobuki::WheelEvent::Raised : state = "raised"; break;
case kobuki::WheelEvent::Dropped : state = "dropped"; break;
}
v8::Local<v8::Object> js_wheel_event = v8::Object::New(isolate);
js_wheel_event->Set(v8::String::NewFromUtf8(isolate, "state"), Nan::New(state).ToLocalChecked());
js_wheel_event->Set(v8::String::NewFromUtf8(isolate, "wheel"), Nan::New(wheel).ToLocalChecked());
v8::Local<v8::Value> argv[2] = {
Nan::New("wheelevent").ToLocalChecked(),
js_wheel_event
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
void KobukiManager::powerEvent(uv_async_t *handle) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
std::string event;
switch(me->power_event.event){
case kobuki::PowerEvent::Unplugged : event = "unplugged"; break;
case kobuki::PowerEvent::PluggedToAdapter : event = "pluggedToAdapter"; break;
case kobuki::PowerEvent::PluggedToDockbase : event = "pluggedToDockbase"; break;
case kobuki::PowerEvent::ChargeCompleted : event = "chargeCompleted"; break;
case kobuki::PowerEvent::BatteryLow : event = "batteryLow"; break;
case kobuki::PowerEvent::BatteryCritical : event = "batteryCritical"; break;
}
v8::Local<v8::Object> js_power_event = v8::Object::New(isolate);
js_power_event->Set(v8::String::NewFromUtf8(isolate, "event"), Nan::New(event).ToLocalChecked());
v8::Local<v8::Value> argv[2] = {
Nan::New("powerevent").ToLocalChecked(),
js_power_event
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
void KobukiManager::inputEvent(uv_async_t *handle) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
v8::Local<v8::Array> js_values = v8::Array::New(isolate, 4);
for(int i = 0; i < 4; i++) {
js_values->Set(i, v8::Boolean::New(isolate, me->input_event.values[i]));
}
v8::Local<v8::Object> js_input_event = v8::Object::New(isolate);
js_input_event->Set(v8::String::NewFromUtf8(isolate, "values"), js_values);
v8::Local<v8::Value> argv[2] = {
Nan::New("inputevent").ToLocalChecked(),
js_input_event
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
void KobukiManager::robotEvent(uv_async_t *handle) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
std::string state;
switch(me->robot_event.state){
case kobuki::RobotEvent::Offline : state = "offline"; break;
case kobuki::RobotEvent::Online : state = "online"; break;
case kobuki::RobotEvent::Unknown : state = "unknown"; break;
}
v8::Local<v8::Object> js_robot_event = v8::Object::New(isolate);
js_robot_event->Set(v8::String::NewFromUtf8(isolate, "state"), Nan::New(state).ToLocalChecked());
v8::Local<v8::Value> argv[2] = {
Nan::New("robotevent").ToLocalChecked(),
js_robot_event
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
void KobukiManager::versionInfo(uv_async_t *handle) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Nan::HandleScope scope;
auto me = static_cast<KobukiManager*>(handle->data);
v8::Local<v8::Object> js_version_info = v8::Object::New(isolate);
std::cout<<me->version_info->toString(me->version_info->firmware)<<std::endl; //todo
js_version_info->Set(v8::String::NewFromUtf8(isolate, "firmware"), Nan::New(me->version_info->toString(me->version_info->firmware)).ToLocalChecked());
js_version_info->Set(v8::String::NewFromUtf8(isolate, "hardware"), Nan::New(me->version_info->toString(me->version_info->hardware)).ToLocalChecked());
js_version_info->Set(v8::String::NewFromUtf8(isolate, "software"), Nan::New(me->version_info->getSoftwareVersion()).ToLocalChecked());
js_version_info->Set(v8::String::NewFromUtf8(isolate, "udid"), Nan::New(me->version_info->toString(me->version_info->udid0, me->version_info->udid1, me->version_info->udid2)).ToLocalChecked());
//, v8::Boolean::New(isolate, me->input_event.values[i]));
v8::Local<v8::Value> argv[2] = {
Nan::New("versioninfo").ToLocalChecked(),
js_version_info
};
v8::Local<v8::Object> JavaScriptObj = Nan::New(me->js_this_);
Nan::MakeCallback(JavaScriptObj, "emit", 2, argv);
}
v8::Handle<v8::Promise> KobukiManager::connect(const std::string& eventName) {
if(eventName=="/stream_data") {
uv_async_init(uv_default_loop(), &async_stream_data, newDataEvent);
//callNewDataEvent();//for test
slot_stream_data.connect(sigslots_namespace + eventName);
}
else if(eventName=="/ros_debug") {
uv_async_init(uv_default_loop(), &async_ros_debug, rosDebug);
//callRosDebug(ros_debug);//for test
slot_ros_debug.connect(sigslots_namespace + eventName);
}
else if(eventName=="/ros_info") {
uv_async_init(uv_default_loop(), &async_ros_info, rosInfo);
//callRosInfo(ros_info);//for test
slot_ros_info.connect(sigslots_namespace + eventName);
}
else if(eventName=="/ros_warn") {
uv_async_init(uv_default_loop(), &async_ros_warn, rosWarn);
//callRosWarn(ros_warn);//for test
slot_ros_warn.connect(sigslots_namespace + eventName);
}
else if(eventName=="/ros_error") {
uv_async_init(uv_default_loop(), &async_ros_error, rosError);
//callRosError(ros_error);//for test
slot_ros_error.connect(sigslots_namespace + eventName);
}
else if(eventName=="/button_event") {
uv_async_init(uv_default_loop(), &async_button_event, buttonEvent);
//callButtonEvent(button_event);//for test
slot_button_event.connect(sigslots_namespace + eventName);
}
else if(eventName=="/bumper_event") {
uv_async_init(uv_default_loop(), &async_bumper_event, bumperEvent);
//callBumperEvent(bumper_event);//for test
slot_bumper_event.connect(sigslots_namespace + eventName);
}
else if(eventName=="/cliff_event") {
uv_async_init(uv_default_loop(), &async_cliff_event, cliffEvent);
//callCliffEvent(cliff_event);//for test
slot_cliff_event.connect(sigslots_namespace + eventName);
}
else if(eventName=="/wheel_event") {
uv_async_init(uv_default_loop(), &async_wheel_event, wheelEvent);
//callWheelEvent(wheel_event);//for test
slot_wheel_event.connect(sigslots_namespace + eventName);
}
else if(eventName=="/power_event") {
uv_async_init(uv_default_loop(), &async_power_event, powerEvent);
//callPowerEvent(power_event);//for test
slot_power_event.connect(sigslots_namespace + eventName);
}
else if(eventName=="/input_event") {
uv_async_init(uv_default_loop(), &async_input_event, inputEvent);
//callInputEvent(input_event);//for test
slot_input_event.connect(sigslots_namespace + eventName);
}
else if(eventName=="/robot_event") {
uv_async_init(uv_default_loop(), &async_robot_event, robotEvent);
//callRobotEvent(robot_event);//for test
slot_robot_event.connect(sigslots_namespace + eventName);
}
else if(eventName=="/version_info") {
uv_async_init(uv_default_loop(), &async_version_info, versionInfo);
//callVersionInfo(*version_info);//for test
signal_version_info.connect(sigslots_namespace + eventName);
slot_version_info.connect(sigslots_namespace + eventName);
}
}
void KobukiManager::disconnect(const std::string& eventName) {
if(eventName=="/stream_data") {
uv_close((uv_handle_t*)&async_stream_data, NULL);
slot_stream_data.disconnect();
}
else if(eventName=="/ros_debug") {
uv_close((uv_handle_t*)&async_ros_debug, NULL);
slot_ros_debug.disconnect();
}
else if(eventName=="/ros_info") {
uv_close((uv_handle_t*)&async_ros_info, NULL);
slot_ros_info.disconnect();
}
else if(eventName=="/ros_warn") {
uv_close((uv_handle_t*)&async_ros_warn, NULL);
slot_ros_warn.disconnect();
}
else if(eventName=="/ros_error") {
uv_close((uv_handle_t*)&async_ros_error, NULL);
slot_ros_error.disconnect();
}
else if(eventName=="/button_event") {
uv_close((uv_handle_t*)&async_button_event, NULL);
slot_button_event.disconnect();
}
else if(eventName=="/bumper_event") {
uv_close((uv_handle_t*)&async_bumper_event, NULL);
slot_bumper_event.disconnect();
}
else if(eventName=="/cliff_event") {
uv_close((uv_handle_t*)&async_cliff_event, NULL);
slot_cliff_event.disconnect();
}
else if(eventName=="/wheel_event") {
uv_close((uv_handle_t*)&async_wheel_event, NULL);
slot_wheel_event.disconnect();
}
else if(eventName=="/power_event") {
uv_close((uv_handle_t*)&async_power_event, NULL);
slot_power_event.disconnect();
}
else if(eventName=="/input_event") {
uv_close((uv_handle_t*)&async_input_event, NULL);
slot_input_event.disconnect();
}
else if(eventName=="/robot_event") {
uv_close((uv_handle_t*)&async_robot_event, NULL);
slot_robot_event.disconnect();
}
else if(eventName=="/version_info") {
uv_close((uv_handle_t*)&async_version_info, NULL);
signal_version_info.disconnect();
slot_version_info.disconnect();
}
}<file_sep>/test/getInertiaData.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
while(true)
{
sleep(100);
/**
* Get inertia data
* @return {Object} InertiaData has angle, angleRate, acc
*/
var inertiaData = kobuki.getInertiaData();
console.log('The angle is: [' + inertiaData.angle + ']');
console.log('The angleRate is: [' + inertiaData.angleRate + ']');
console.log('The inertia data is: [' + inertiaData.acc[0] + ', ' + inertiaData.acc[1] + ', ' + inertiaData.acc[2] + ']');
}
<file_sep>/test/getGpInputData.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
while(true)
{
sleep(100);
/**
* Get general purpose input data
* @return {Object} GpInputData has digitalInput, an unsigned int number, and analogInput, array of unsigned int number.
*/
var gpInputData = kobuki.getGpInputData();
console.log('The digital input data is: [' + gpInputData.digitalInput + ']');
console.log('The analog input data is: [' + gpInputData.analogInput[0] + ', ' + gpInputData.analogInput[1] + ', ' + gpInputData.analogInput[2] + gpInputData.analogInput[3] + ']');
}
<file_sep>/kobuki_manager.h
// To add your copyright and license header
#ifndef _KOBUKI_MANAGER_H_
#define _KOBUKI_MANAGER_H_
#include <node.h>
#include <v8.h>
#include <csignal>
#include <ecl/time.hpp>
#include <ecl/sigslots.hpp>
#include <ecl/geometry/pose2d.hpp>
#include <ecl/linear_algebra.hpp>
#include "kobuki_driver/kobuki.hpp"
#include <string>
#include "gen/generator_helper.h"
#include "gen/array_helper.h"
#include "gen/core_sensors_data.h"
#include "gen/dockir_data.h"
#include "gen/cliff_data.h"
#include "gen/current_data.h"
#include "gen/gp_input_data.h"
#include "gen/inertia_data.h"
#include "gen/three_axis_gyro_data.h"
#include "gen/controller_info_data.h"
#include "gen/battery.h"
#include "gen/version_info.h"
#include "gen/wheel_joint_states.h"
#include "gen/digital_output.h"
#include "gen/pose_update_data.h"
//#include "gen/thread-event-helper.h"
#include "gen/promise-helper.h"
class KobukiManager {
public:
KobukiManager();
explicit KobukiManager(const std::string& sigslotsNamespace);
~KobukiManager();
KobukiManager& operator = (const KobukiManager& rhs);
public:
//kobuki APIs
CoreSensorsData getCoreSensorData();
DockIRData getDockIRData();
CliffData getCliffData();
CurrentData getCurrentData();
GpInputData getGpInputData();
InertiaData getInertiaData();
ThreeAxisGyroData getRawInertiaData();
ControllerInfoData getControllerInfoData();
Battery batteryStatus();
double getHeading();
double getAngularVelocity();
VersionInfo versionInfo();
WheelJointStates getWheelJointStates(const WheelJointStates& wheelJointStates);
bool isAlive();
bool isEnabled();
bool isShutdown();
void resetOdometry();
void setBaseControl(const double& linear, const double& angular);
void setLed(const std::string& ledNo, const std::string& ledColor);
void setDigitalOutput(const DigitalOutput& digitalOutput);
void setExternalPower(const DigitalOutput& digitalOutput);
void playSoundSequence(const std::string& soundSequence);
bool setControllerGain(const ControllerInfoData& controllerInfoData);
bool getControllerGain();
PoseUpdateData updateOdometry();
PoseUpdateData updateOdometry(const PoseUpdateData& pose);
//sigslots callbacks
void callNewDataEvent();
void callRosDebug(const std::string& ros_debug);
void callRosInfo(const std::string& ros_info);
void callRosWarn(const std::string& ros_warn);
void callRosError(const std::string& ros_error);
void callButtonEvent(const kobuki::ButtonEvent& button_event);
void callBumperEvent(const kobuki::BumperEvent& bumper_event);
void callCliffEvent(const kobuki::CliffEvent& cliff_event);
void callWheelEvent(const kobuki::WheelEvent& wheel_event);
void callPowerEvent(const kobuki::PowerEvent& power_event);
void callInputEvent(const kobuki::InputEvent& input_event);
void callRobotEvent(const kobuki::RobotEvent& robot_event);
void callVersionInfo(const kobuki::VersionInfo& version_info);
//v8 event callbacks
static void newDataEvent(uv_async_t *handle);
static void rosDebug(uv_async_t *handle);
static void rosInfo(uv_async_t *handle);
static void rosWarn(uv_async_t *handle);
static void rosError(uv_async_t *handle);
static void buttonEvent(uv_async_t *handle);
static void bumperEvent(uv_async_t *handle);
static void cliffEvent(uv_async_t *handle);
static void wheelEvent(uv_async_t *handle);
static void powerEvent(uv_async_t *handle);
static void inputEvent(uv_async_t *handle);
static void robotEvent(uv_async_t *handle);
static void versionInfo(uv_async_t *handle);
v8::Handle<v8::Promise> connect(const std::string& eventName);
void disconnect(const std::string& eventName);
void SetJavaScriptThis(v8::Local<v8::Object> JavaScriptThis) {
js_this_.Reset(JavaScriptThis);
}
private:
kobuki::Kobuki kobuki;
ecl::Pose2D<double> pose_ecl;
std::string sigslots_namespace = "/kobuki";
Nan::Persistent<v8::Object> js_this_;
//slots name
ecl::Slot<> slot_stream_data;
ecl::Slot<const std::string&> slot_ros_debug;
ecl::Slot<const std::string&> slot_ros_info;
ecl::Slot<const std::string&> slot_ros_warn;
ecl::Slot<const std::string&> slot_ros_error;
ecl::Slot<const kobuki::ButtonEvent&> slot_button_event;
ecl::Slot<const kobuki::BumperEvent&> slot_bumper_event;
ecl::Slot<const kobuki::CliffEvent&> slot_cliff_event;
ecl::Slot<const kobuki::WheelEvent&> slot_wheel_event;
ecl::Slot<const kobuki::PowerEvent&> slot_power_event;
ecl::Slot<const kobuki::InputEvent&> slot_input_event;
ecl::Slot<const kobuki::RobotEvent&> slot_robot_event;
ecl::Slot<const kobuki::VersionInfo&> slot_version_info;
ecl::Signal<const kobuki::VersionInfo&> signal_version_info;
//uv_async_t name
uv_async_t async_stream_data;
uv_async_t async_button_event;
uv_async_t async_bumper_event;
uv_async_t async_cliff_event;
uv_async_t async_wheel_event;
uv_async_t async_power_event;
uv_async_t async_input_event;
uv_async_t async_robot_event;
uv_async_t async_version_info;
uv_async_t async_ros_debug;
uv_async_t async_ros_info;
uv_async_t async_ros_warn;
uv_async_t async_ros_error;
//data
kobuki::ButtonEvent button_event;
kobuki::BumperEvent bumper_event;
kobuki::CliffEvent cliff_event;
kobuki::WheelEvent wheel_event;
kobuki::PowerEvent power_event;
kobuki::InputEvent input_event;
kobuki::RobotEvent robot_event;
kobuki::VersionInfo *version_info;
std::string ros_debug;
std::string ros_info;
std::string ros_warn;
std::string ros_error;
};
#endif // _KOBUKI_MANAGER_H_
<file_sep>/test/getCoreSensorData.js
function sleep(d){
for(var t=Date.now(); Date.now() - t <=d;);
}
var addon = require('../index');
var kobuki = new addon.KobukiManager('/ttyUSB0');
while(true)
{
sleep(500);
/**
* Get the core sensor data of Kobuki, including timestamp, bumper sensor, wheeldrop sensor, cliff sensor,
* encoders, pwm, buttons, charger state, battery, overcurrent.
* All above are raw data, find more info in page https://yujinrobot.github.io/kobuki/doxygen/enAppendixProtocolSpecification.html
* @return {Object} ControllerInfoData
*/
var sensorData = kobuki.getCoreSensorData();
console.log('Timestamp is: ' + sensorData.timeStamp);
console.log('Bumper sensor data is: ' + sensorData.bumper);
console.log('Wheeldrop sensor data is: ' + sensorData.wheelDrop);
console.log('Cliff sensor data is: ' + sensorData.cliff);
console.log('Encoders data is: [' + sensorData.leftEncoder + ', ' + sensorData.rightEncoder +']');
console.log('PWM data is: [' + sensorData.leftPwm + ', ' + sensorData.rightPwm + ']');
console.log('Buttons data is: ' + sensorData.buttons);
console.log('Charger data is: ' + sensorData.charger);
console.log('Battery data is: ' + sensorData.battery);
console.log('Overcurrent data is: ' + sensorData.overCurrent);
}
| 5d1a31c1ad5ac171433cb5188568599aca432e3e | [
"Markdown",
"Python",
"JavaScript",
"C++"
]
| 23 | Markdown | pancx/node-kobuki | 9ff0f42cb5c86c6bdba07e360f01b2f500423a0d | ae161e9c937c1dfeab2ea9dcaa1cdf7dfa5e0f40 |
refs/heads/main | <repo_name>Gauravdeep983/cnn-scraping<file_sep>/README.md
# cnn-scraping
Python Project for INSY 5336
| 578b364d7612e8055f7a985287a50f0342ba1012 | [
"Markdown"
]
| 1 | Markdown | Gauravdeep983/cnn-scraping | f454529e8397de6bd4f4691eb47d84f1d5eeb4d5 | 8345046f7205a6a6d186e1fe97a72d554c004b6a |
refs/heads/main | <repo_name>Jpstilley/CodeWarsKatasCSharp<file_sep>/CodeWarsKatasCSharp/Kata.cs
using System;
namespace CodeWarsKatasCSharp
{
public class Kata
{
}
}
<file_sep>/CodeWarsKatasCSharp/Program.cs
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
namespace CodeWarsKatasCSharp
{
class Program
{
static void Main(string[] args)
{
int[] array = { 8, 9, 10, 11, 12, 14, 15 };
Console.WriteLine(FirstNonConsecutive(array));
}
/* Find the first non-consecutive number
https://www.codewars.com/kata/58f8a3a27a5c28d92e000144/train/csharp
public static object FirstNonConsecutive(int[] arr)
{
int index = 0;
while (index < arr.Length - 1)
{
if(index + 1 < arr.Length)
{
if (arr[index] + 1 != arr[index + 1])
{
return arr[index + 1];
}
else
{
index++;
}
}
else
{
index++;
}
}
return null;
}*/
/*public static string GetReadableTime(int seconds)
{
int hours = (seconds / 3600);
string formattedHours = (hours < 10) ? $"0{hours}" : $"{hours}";
seconds % = 3600;
int minutes = seconds / 60;
string formattedMins = (minutes < 10) ? $"0{minutes}" : $"{minutes}";
seconds % = 60;
string formattedSecs = (seconds < 10) ? $"0{seconds}" : $"{seconds}";
return $"{formattedHours}:{formattedMins}:{formattedSecs}";
}*/
/*Moving Zeros To The End
https://www.codewars.com/kata/52597aa56021e91c93000cb0/solutions/csharp
public static int[] MoveZeroes(int[] arr)
{
int[] answer = new int[arr.Length];
int indexOfArr = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] > 0)
{
answer[indexOfArr] = arr[i];
indexOfArr++;
}
}
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == 0)
{
answer[indexOfArr] = arr[i];
indexOfArr++;
}
}
return answer;
}*\
/*Create Phone Number
https://www.codewars.com/kata/525f50e3b73515a6db000b83/train/csharp
public static string CreatePhoneNumber(int[] numbers)
{
string phoneNumber = "";
for (int i = 0; i < numbers.Length; i++)
{
if(i < 1)
{
phoneNumber += $"({numbers[i]}";
}
else if (i < 3 || i > 3)
{
phoneNumber += $"{numbers[i]}";
}
if (i == 3)
{
phoneNumber += $") {numbers[i]}";
}
if(i == 5)
{
phoneNumber += "-";
}
}
return phoneNumber;
}*/
/*Multiples of 3 or 5
https://www.codewars.com/kata/514b92a657cdc65150000006/train/csharp
public static int Solution(int value)
{
int threes = 0;
int fives = 0;
value--;
while (value > 2)
{
if (value % 3 == 0 && value % 5 != 0)
{
threes += value;
}
if (value % 5 == 0)
{
fives += value;
}
value--;
}
return threes + fives;
}*/
/*Replace With Alphabet Position
https://www.codewars.com/kata/546f922b54af40e1e90001da/train/csharp
public static string AlphabetPosition(string text)
{
string onlyLetters = "";
string answer = "";
foreach(char letter in text)
{
if (Char.IsLetter(letter))
{
onlyLetters += letter;
}
}
for (int i = 0; i < onlyLetters.Count(); i++)
{
if (i.Equals(onlyLetters.Count() - 1))
{
answer += $"{Char.ToUpper(onlyLetters[i]) - 64}";
}
else
{
answer += $"{Char.ToUpper(onlyLetters[i]) - 64} ";
}
}
return answer;
}*/
/*The Deaf Rats of Hamelin
https://www.codewars.com/kata/598106cb34e205e074000031/train/csharp
public static int CountDeafRats(string town)
{
int piedPiper = 0;
List<string> townList = new List<string>();
string aRat = "";
for (int i = 0; i < town.Length; i++)
{
if (town[i] != 'P' && town[i] != ' ')
{
aRat = $"{town[i]}{town[i + 1]}";
townList.Add(aRat);
i++;
}
if(town[i] == 'P')
{
townList.Add($"{town[i]}");
piedPiper = townList.IndexOf("P");
}
}
int ratCount = 0;
for (int i = 0; i < townList.Count(); i++)
{
if (townList[i] == "O~" && i < piedPiper)
{
ratCount++;
}
if (townList[i] == "~O" && i > piedPiper)
{
ratCount++;
}
}
return ratCount;
}*/
/*public static string GetOrder(string input) TODO
{
string[] orders = new string[] { "burger", "fries", "chicken", "pizza", "sandwich", "onionrings", "milkshake" , "coke" };
Regex.Replace(input, "burger", );
string fixedOrder = "";
foreach(string order in orders)
{
if ( == order)
{
pu
}
}
return string.Empty;*/
/*Find the unique number
https://www.codewars.com/kata/585d7d5adb20cf33cb000235/train/csharp
public static int GetUnique(IEnumerable<int> numbers)
{
int[] nums = numbers.ToArray();
int firstOne = nums[0];
int lastOne = nums[nums.Length - 1];
for(int i = 1; i < nums.Length; i++)
{
if (nums[i] != firstOne && nums[i] != lastOne)
{
return nums[i];
}
else if (nums[i] != firstOne)
{
return firstOne;
}
else if (nums[i] != lastOne)
{
return lastOne;
}
}
return firstOne;
}*/
/*Unique In Order
https://www.codewars.com/kata/54e6533c92449cc251001667/train/csharp
public static IEnumerable<T> UniqueInOrder<T>(IEnumerable<T> iterable)
{
List<T> answer = new List<T>();
T[] useable = iterable.ToArray();
if (iterable == null || iterable.Count() == 0)
{
return iterable;
}
answer.Add(useable[0]);
T lastOne = useable[0];
for(int i = 1; i < useable.Length; i++)
{
if(IComparer<T>.Equals(lastOne, useable[i]))
{
}
else
{
answer.Add(useable[i]);
}
lastOne = useable[i];
}
return answer;
}*/
/*Find the smallest - TODO
https://www.codewars.com/kata/573992c724fc289553000e95/train/csharp
public static long[] Smallest(long n)
{
long min = 0;
long indexOfSmall = 0;
int[] originalNumber = n.ToString().Select(t => int.Parse(t.ToString())).ToArray();
for (int i = 1; i < originalNumber.Length; i++)
{
if(i < 2)
{
min = originalNumber[i];
indexOfSmall = i;
}
if (min > originalNumber[i])
{
min = originalNumber[i];
indexOfSmall = i;
}
}
int indexOfRemoved = 0;
long[] smallestRemoved = new long[originalNumber.Length - 1];
for (int i = 0; i < originalNumber.Length; i++)
{
if(originalNumber[i] == min )
{
indexOfSmall = i;
}
else
{
smallestRemoved[indexOfRemoved] = originalNumber[i];
indexOfRemoved++;
}
}
int index = 0;
long newMin = min;
long indexOfNewSmall = 0;
string smallestNumber = "";
while (index < originalNumber.Length - 1)
{
if(min < smallestRemoved[index])
{
smallestNumber += min;
indexOfNewSmall = index;
min = 10;
}
else
{
smallestNumber += smallestRemoved[index];
index++;
if (index < smallestRemoved.Length && index > 1)
{
min = smallestRemoved[index];
}
}
}
long smallConvertedToNumber = Convert.ToInt64(smallestNumber);
long[] answer = new long[3]{ smallConvertedToNumber, indexOfSmall, indexOfNewSmall };
return answer;
}*/
/*public static string Likes(string[] name)
{
if(name.Length == 0)
{
return "no one likes this";
}
if(name.Length == 1)
{
return $"{name[0]} likes this";
}
if(name.Length == 2)
{
return $"{name[0]} and {name[1]} like this";
}
if (name.Length == 3)
{
return $"{name[0]}, {name[1]} and {name[2]} like this";
}
else
{
return $"{name[0]}, {name[1]} and {name.Length - 2} others like this";
}
}*/
/*Filter out the geese
https://www.codewars.com/kata/57ee4a67108d3fd9eb0000e7/train/csharp
public static IEnumerable<string> GooseFilter(IEnumerable<string> birds)
{
// return IEnumerable of string containing all of the strings in the input collection, except those that match strings in geese
string[] geese = new string[] { "African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher" };
List<string> correctGeese = new List<string>();
foreach (string bird in birds)
{
bool inList = false;
foreach (string goose in geese)
{
if (bird.Contains(goose))
{
inList = true;
}
}
if (!inList)
{
correctGeese.Add(bird);
}
}
return correctGeese;
}*/
/* 8kyu interpreters: HQ9+
https://www.codewars.com/kata/591588d49f4056e13f000001/train/csharp
public static string Interpret(string code)
{
if (code == "H")
{
return "Hello World!";
}
else if (code == "Q")
{
return code;
}
else if (code == "9")
{
string beers = "";
for (int i = 99; i > 1; i--)
{
beers += $"{i} bottles of beer on the wall, {i} bottles of beer.\n" +
$"Take one down and pass it around, {i - 1} bottles of beer on the wall.\n";
}
beers += $"2 bottles of beer on the wall, 2 bottles of beer.\n" +
$"Take one down and pass it around, 1 bottle of beer on the wall.\n" +
$"1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around," +
$" no more bottles of beer on the wall.\nNo more bottles of beer on the wall, no more" +
$" bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.";
return beers;
}
else
{
return null;
}
}*/
/*For UFC Fans(Total Beginners) : <NAME> vs George <NAME>re
https://www.codewars.com/kata/for-ufc-fans-total-beginners-conor-mcgregor-vs-george-saint-pierre/train/csharp
public static string Quote(string fighter)
{
fighter = fighter.ToLower();
if (fighter == "conor mcgregor")
{
return "I'd like to take this chance to apologize.. To absolutely NOBODY!";
}
else
{
return "I am not impressed by your performance.";
}
}*/
/*Counting sheep...
https://www.codewars.com/kata/54edbc7200b811e956000556/train/csharp
public static int CountSheeps(bool[] sheeps)
{
int result = 0;
foreach (bool sheep in sheeps)
{
if (sheep == true)
{
result++;
}
}
return result;
}*/
/*You only need one - Beginner
https://www.codewars.com/kata/you-only-need-one-beginner/train/csharp
public static bool Check(object[] a, object x)
{
return a.Contains(x);
}*/
/*Opposite number
https://www.codewars.com/kata/opposite-number/train/csharp
public static int Opposite(int number)
{
if (number > 0)
{
number = number - (number * 2);
return number;
}
else
{
number = number + (number * -2);
return number;
}
}*/
/*Return Negative
https://www.codewars.com/kata/return-negative/train/csharp
public static int MakeNegative(int number)
{
string changeIt = "";
int negative = 0;
if (number > 0)
{
changeIt = $"-{number.ToString()}";
negative = Convert.ToInt32(changeIt);
return negative;
}
return number;
}*/
/*Remove First and Last Character
https://www.codewars.com/kata/56bc28ad5bdaeb48760009b0/train/csharp
public static string Remove_char(string s)
{
var removed = "";
for (int i = 1; i < s.Length - 1; i++)
{
removed += s[i];
}
return removed;
}*/
/*MakeUpperCase
https://www.codewars.com/kata/makeuppercase/train/csharp
public static string MakeUpperCase(string str)
{
str = str.ToUpper();
return str;
}*/
/*Man in the west
https://www.codewars.com/kata/man-in-the-west/train/csharp
public static bool CheckTheBucket(string[] bucket)
{
foreach (string result in bucket)
{
if (result == "gold")
{
return true;
}
}
return false;
}*/
/*Reversed sequence
https://www.codewars.com/kata/reversed-sequence/train/csharp
public static int[] ReverseSeq(int n)
{
int[] sequence = new int[n];
int value = n;
for (int i = 0; i < n; i++)
{
sequence[i] = value;
value--;
}
return sequence;
}*/
/*Are arrow functions odd?
https://www.codewars.com/kata/are-arrow-functions-odd/train/csharp
public static List<int> Odds(List<int> values) =>
values.Where(value => value % 2 != 0).ToList();*/
/*Count Odd Numbers below n
https://www.codewars.com/kata/count-odd-numbers-below-n/train/csharp
public static ulong OddCount(ulong n)
{
return n / 2;
}*/
/*String repeat
https://www.codewars.com/kata/string-repeat/train/csharp
public static string RepeatStr(int n, string s)
{
string repeatedString = "";
for (int i = 0; i < n; i++)
{
repeatedString += s;
}
return repeatedString;
}*/
/*Remove String Spaces
https://www.codewars.com/kata/remove-string-spaces/train/csharp
public static string NoSpace(string input)
{
string unspaced = "";
for (int letter = 0; letter < input.Length; letter++)
{
if (!Char.IsWhiteSpace(input[letter]))
{
unspaced += input[letter];
}
}
return unspaced;
}*/
/*A Strange Trip to the Market
https://www.codewars.com/kata/a-strange-trip-to-the-market/train/csharp
public static bool IsLockNessMonster(string sentence)
{
sentence = sentence.ToLower();
if (sentence.Contains("tree fiddy") || sentence.Contains("3.50") || sentence.Contains("three fifty"))
{
return true;
}
return false;
}*/
/*Kata Example Twist
https://www.codewars.com/kata/525c1a07bb6dda6944000031/solutions/csharp
public static string[] Websites = new string[1000];
static string[] websites = TwistIt();
public static string[] TwistIt()
{
Array.Fill(Websites, "codewars");
return Websites;
}*/
/*Basic subclasses - Adam and Eve
https://www.codewars.com/kata/basic-subclasses-adam-and-eve/train/csharp
public class God
{
public static Human[] Create()
{
Human[] people = new Human[2] { new Man(), new Woman() };
return people;
}
}
public class Human { }
public class Man : Human { }
public class Woman : Human { }*/
/*Grasshopper - Terminal game combat function
https://www.codewars.com/kata/grasshopper-terminal-game-combat-function-1/train/csharp
public static float Combat(float health, float damage)
{
health -= damage;
if (health < 0)
health = 0;
return health;
}*/
/*Sentence Smash
https://www.codewars.com/kata/sentence-smash/train/csharp
static void Main(string[] args)
{
string[] words = { "this", "is", "a", "really", "long", "sentence" };
Console.WriteLine(Smash(words));
}*/
/*public static string Smash(string[] words)
{
var sentence = "";
for (int index = 0; index < words.Length; index++)
{
if (index != words.Length - 1)
{
sentence += $"{words[index]} ";
}
else
{
sentence += $"{words[index]}";
}
}
return sentence;
}*/
/*Calculate average
https://www.codewars.com/kata/calculate-average/train/csharp
static void Main(string[] args)
{
double[] array = { };
Console.WriteLine(FindAverage(array));
}
public static double FindAverage(double[] array)
{
double total = 0;
if (!array.All(value => value.Equals(double.NaN)))
{
foreach (double value in array)
{
total += value;
}
return total / array.Length;
}
else
{
return 0;
}
}*/
/*Calculate BMI
https://www.codewars.com/kata/57a429e253ba3381850000fb/train/csharp
static void Main(string[] args)
{
Console.WriteLine(Bmi(80, 1.80));
}
public static string Bmi(double weight, double height)
{
double bmi = (weight / Math.Pow(height, 2));
if (bmi <= 18.5)
{
return "Underweight";
}
else if (bmi <= 25.0)
{
return "Normal";
}
else if (bmi <= 30.0)
{
return "Overweight";
}
else
{
return "Obese";
}
}*/
/*The Supermarket Queue
https://www.codewars.com/kata/57b06f90e298a7b53d000a86/train/csharp
static void Main(string[] args)
{
int[] customers = { 1, 2, 3, 4 };
Console.WriteLine(QueueTime(customers, 2));
}
int[] customers = { 1, 2, 3, 4 };
public static long QueueTime(int[] customers, int n)
{
int[] tillsFilled = new int[n];
int nextCustomer = 0;
int tempTime = -1;
do
{
for (int index = 0; index < tillsFilled.Length; index++)
{
if (tillsFilled[index] != 0)
{
tillsFilled[index]--;
}
if (tillsFilled[index] == 0 && nextCustomer < customers.Length)
{
tillsFilled[index] = customers[nextCustomer];
nextCustomer++;
}
}
tempTime++;
} while (!tillsFilled.All(till => till.Equals(0)));
return tempTime;
}*/
/*Detect Pangram
https://www.codewars.com/kata/545cedaa9943f7fe7b000048/train/csharp
public static bool IsPangram(string str)
{
return str.ToLower().Where(ch => Char.IsLetter(ch)).GroupBy(ch => ch).Count() == 26;
}*/
/*Sum of Triangular Numbers
https://www.codewars.com/kata/580878d5d27b84b64c000b51/train/csharp
static void Main(string[] args)
{
Console.WriteLine(SumTriangularNumbers(4));
}
public static int SumTriangularNumbers(int n)
{
var result = 0;
if (n <= 0)
{
return 0;
}
else
{
result = (n * (n + 1) * (n + 2)) / 6;
}
return result;
}*/
/*Break camelCase
https://www.codewars.com/kata/5208f99aee097e6552000148/train/csharp
static void Main(string[] args)
{
var alpha = "camelCasing";
Console.WriteLine(BreakCamelCase(alpha));
}
public static string BreakCamelCase(string str)
{
for (int index = 0; index < str.Length; index++)
{
if (Char.IsUpper(str[index]))
{
str = str.Insert(index, " ");
index++;
}
}
return str;
}*/
/*Love vs friendship
https://www.codewars.com/kata/59706036f6e5d1e22d000016/train/csharp
public static int WordsToMarks(string str)
{
var wordTotal = 0;
char[] wordSeperated = str.ToCharArray();
foreach (char letter in wordSeperated)
{
wordTotal += (char.ToUpper(letter) - 64);
}
return wordTotal;
}*/
/*Find the stray number
https://www.codewars.com/kata/57f609022f4d534f05000024/train/csharp
public static int Stray(int[] numbers)
{
Array.Sort(numbers);
if (numbers[0] != numbers[1])
{
return numbers[0];
}
else
{
return numbers[numbers.Length - 1];
}
}*/
/*Two Sum
https://www.codewars.com/kata/52c31f8e6605bcc646000082/train/csharp
public static int[] TwoSum(int[] numbers, int target)
{
int[] answer = new int[2];
for (int i = 0; i < numbers.Length; i++)
{
for (int j = 1; j < numbers.Length; j++)
{
if (numbers[i] + numbers[j] == target)
{
answer[0] = i;
answer[1] = j;
return answer;
}
}
}
return answer;
}*/
/*Sort Number
https://www.codewars.com/kata/5174a4c0f2769dd8b1000003/train/csharp
public static int[] SortNumbers(int[] nums)
{
if (nums != null && nums.Length != 0)
{
Array.Sort(nums);
}
else
{
nums = new int[0];
}
return nums;
}*/
/*Testing 1-2-3
https://www.codewars.com/kata/54bf85e3d5b56c7a05000cf9/train/csharp
public static List<string> Number(List<string> lines)
{
for (int i = 0; i < lines.Count; i++)
{
lines[i] = $"{i + 1}: {lines[i]}";
}
return lines;
}*/
/*The Coupon Code
https://www.codewars.com/kata/539de388a540db7fec000642/train/csharp
public static bool CheckCoupon(string enteredCode, string correctCode, string currentDate, string expirationDate)
{
if (enteredCode == correctCode && Convert.ToDateTime(currentDate) <= Convert.ToDateTime(expirationDate))
return true;
else
return false;
}*/
}
}
| f6496da9c118cf6872215b682017bbee1cc4a414 | [
"C#"
]
| 2 | C# | Jpstilley/CodeWarsKatasCSharp | f995ac859144962dde66d2216f00d2c1c74f7b90 | 38767c63152a171835fa90bfdf112a53693f772b |
refs/heads/master | <repo_name>npatsakula/cm_heat_equation<file_sep>/priv/vizualization.py
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import ast
with open('result.txt', 'r') as file:
for string in file:
data = ast.literal_eval(string.strip())
fig = plt.figure()
ax = fig.gca(projection='3d')
# Make data.
X = np.arange(data[0][0], data[0][1], data[0][2])
print(data[0][0], data[0][1], data[0][2])
Y = np.arange(data[1][0], data[1][1], data[1][2])
print(data[1][0], data[1][1], data[1][2])
Z = data[2]
print(len(Z))
X, Y = np.meshgrid(X, Y)
# Plot the surface.
surf = ax.plot_surface(np.array(X), np.array(Y), np.array(Z), cmap=cm.coolwarm,
linewidth=1, antialiased=False)
# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
<file_sep>/Makefile
PROJECT = cm_heat_equation
PROJECT_DESCRIPTION = Calculation of the heat equation in grid nodes. Plotting.
PROJECT_VERSION ?= $(shell git describe --tags --always | sed 's/-/./g')
PROJECT_MOD = cm_heat_equation_app
SHELL_ERL = erl -eval 'application:ensure_all_started($(PROJECT))'
include erlang.mk
| b255867c8f130ba0ffd1d63da3c90f7789b57904 | [
"Python",
"Makefile"
]
| 2 | Python | npatsakula/cm_heat_equation | c73618329535bca0ae13da4640d275f8fbd4adcb | 2cf8c2198d6c8a6db325462959d7b2d7d9bfe13c |
refs/heads/master | <repo_name>lq150415/hobby<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
use hobby\User;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
Model::unguard();
User::create([
'name' => '<NAME>',
'lastname' => 'Quisbert',
'lastnamesec' => 'Quispe',
'role' => 'Administrador',
'username' => 'admin',
'password' => bcrypt('<PASSWORD>'),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
$this->command->info('Usuario por defecto creado!');
Model::reguard();
}
}
<file_sep>/readme.md
# hobby
administrador de pagina hobbyblue
<file_sep>/app/Sold.php
<?php
namespace hobby;
use Illuminate\Database\Eloquent\Model;
class Sold extends Model
{
//
}
| e977f8d17b7b6945cfdb873e6b4b25e8746455dd | [
"Markdown",
"PHP"
]
| 3 | PHP | lq150415/hobby | 02a2a60e849f6db5d3322d2c3c18b8efa802ea1a | e6bc33c0a88c46d946ce955edb7251ab91268b67 |
refs/heads/master | <file_sep>import math
import numpy
import numpy as np
from keras.layers import Dense, Embedding
from keras.layers import LSTM
from keras.models import Sequential
from matplotlib import pyplot
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from statsmodels.tsa.ar_model import AR
dynamic = True
a = [13, 11, 6]
b = [3, 4, 11] # b/2pi
c = [14.88, 1.88, 7.22]
T = 2 * math.pi
print(T)
def fun(x):
result = [a[i] * math.sin(b[i] * x + c[i]) for i in range(len(a))]
return sum(result)
test_to_train = 4
x = np.arange(0, test_to_train * T, 0.1)
y = np.array([fun(i) for i in x])
print(x)
print(y)
train_size = len(x) // test_to_train
x_train, x_test = x[1:train_size], x[train_size:]
train, test = y[1:train_size], y[train_size:]
x_train = np.reshape(x_train, (x_train.shape[0], 1))
x_test = np.reshape(x_test, (x_test.shape[0], 1))
model = Sequential()
model.add(Embedding(10000000000, 11))
model.add(LSTM(4, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(1, activation='sigmoid'))
# try using different optimizers and different optimizer configs
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.fit(x_train, train, epochs=100, batch_size=32, verbose=2)
lstm_prediction = model.predict(x_test)
pyplot.plot(x_test, lstm_prediction, color='green')
pyplot.title("Ongoing " + ("dynamic" if dynamic else "static"))
pyplot.legend(["expected", "AR", "LSTM"])
pyplot.show()
<file_sep>import math
def lcm(a, b):
return abs(a*b) // math.gcd(a, b)
<file_sep>from __future__ import print_function
from keras.callbacks import LambdaCallback
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.optimizers import RMSprop
from keras.utils.data_utils import get_file
import numpy as np
import random
import sys
import io
char_count = 57
sentece_length = 40
path = get_file(
'nietzsche.txt',
origin='https://s3.amazonaws.com/text-datasets/nietzsche.txt')
with io.open(path, encoding='utf-8') as f:
text = f.read().lower()
chars = sorted(list(set(text)))
print('total chars:', len(chars))
char_indices = dict((c, i) for i, c in enumerate(chars))
indices_char = dict((i, c) for i, c in enumerate(chars))
# cut the text in semi-redundant sequences of maxlen characters
maxlen = sentece_length
step = 3
sentences = []
next_chars = []
for i in range(0, len(text) - maxlen, step):
sentences.append(text[i: i + maxlen])
next_chars.append(text[i + maxlen])
print('nb sequences:', len(sentences))
print('chars', chars)
print('Vectorization...')
x = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool)
y = np.zeros((len(sentences), len(chars)), dtype=np.bool)
for i, sentence in enumerate(sentences):
for t, char in enumerate(sentence):
x[i, t, char_indices[char]] = 1
y[i, char_indices[next_chars[i]]] = 1
np.random.seed(322)
coef = [np.random.rand() + 0.01 for i in range(sentece_length)]
coef[1] = 0.00000001
# feed
symbols = x[1]
print(text[sentece_length:2*sentece_length], end="")
for i in range(100):
preds = [(symbols[j] * coef[j]) for j in range(sentece_length)]
preds = np.sum(preds, axis=0)
preds = np.asarray(preds).astype('float64') + 0.001
preds = np.log(preds) / 0.5
exp_preds = np.exp(preds)
preds = exp_preds / np.sum(exp_preds)
probas = np.random.multinomial(1, preds, 1)
new_symbol_index = np.argmax(probas)
# new_symbol_index = np.argmax(preds)
print(indices_char[new_symbol_index], end="")
new_symbol = np.zeros(len(char_indices))
new_symbol[new_symbol_index] = 1
for j in range(len(symbols)-1):
symbols[j] = symbols[j + 1]
symbols[sentece_length - 1] = new_symbol
<file_sep>import math
import numpy
import numpy as np
from keras.layers import Dense
from keras.layers import LSTM
from keras.models import Sequential
from matplotlib import pyplot
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from statsmodels.tsa.ar_model import AR
dynamic = True
a = [13, 11, 6]
b = [3, 4, 11] # b/2pi
c = [14.88, 1.88, 7.22]
T = 2 * math.pi
print(T)
np.random.seed(6)
def fun(x):
result = [a[i] * math.sin(b[i] * x + c[i]) for i in range(len(a))]
return sum(result)
test_to_train = 4
x = np.arange(0, test_to_train * T, 0.1)
y = np.array([fun(i) for i in x])
print(x)
print(y)
train_size = len(x) // test_to_train
x_train, x_test = x[1:train_size], x[train_size:]
train, test = y[1:train_size], y[train_size:]
# train autoregression
model = AR(y[0:len(y) // 2])
model_fit = model.fit()
print('Lag: %s' % model_fit.k_ar)
print('Coefficients: %s' % model_fit.params)
# make predictions
predictions = model_fit.predict(start=len(train), end=len(train) + len(test) - 1, dynamic=dynamic)
for i in range(len(predictions)):
print('predicted=%f, expected=%f' % (predictions[i], test[i]))
error = mean_squared_error(test, predictions)
print('Test MSE: %.3f' % error)
# plot results
pyplot.plot(x_test, test)
# pyplot.plot(x_test, predictions, color='red')
# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset) - look_back - 1):
a = dataset[i:(i + look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return numpy.array(dataX), numpy.array(dataY)
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = np.reshape(y, (y.shape[0], 1))
dataset = scaler.fit_transform(dataset)
# reshape into X=t and Y=t+1
look_back = 11
train, test = dataset[0:train_size, :], dataset[train_size - look_back:len(dataset), :]
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
print(trainX)
# reshape input to be [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
lstm_model = Sequential()
lstm_model.add(LSTM(4, input_shape=(1, look_back)))
lstm_model.add(Dense(1))
lstm_model.compile(loss='mean_squared_error', optimizer='adam')
lstm_model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
lstm_prediction = []
window = dataset[train_size - look_back:train_size]
for i in range(len(x_test)):
testX = numpy.reshape(window, (1, 1, look_back))
scaled_prediction = lstm_model.predict(testX)
current_prediction = scaler.inverse_transform(scaled_prediction)[0][0]
window = np.roll(window, -1)
window[look_back - 1] = scaled_prediction
lstm_prediction.append(current_prediction)
pyplot.plot(x_test[0:len(lstm_prediction)], lstm_prediction, color='green')
pyplot.title("Ongoing " + ("dynamic" if dynamic else "static"))
pyplot.legend(["expected", "AR", "LSTM"])
pyplot.show()
<file_sep>import math
from matplotlib import pyplot
from statsmodels.tsa.ar_model import AR
from sklearn.metrics import mean_squared_error
import numpy as np
import numpy
import matplotlib.pyplot as plt
from pandas import read_csv
import math
import tensorflow
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
a = [13, 11, 6]
b = [3, 4, 11] # b/2pi
c = [14.88, 1.88, 7.22]
T = 2 * math.pi
print(T)
def fun(x):
result = [a[i] * math.sin(b[i] * x + c[i]) for i in range(len(a))]
return sum(result)
x = np.arange(0, 2 * T, 0.1)
y = np.array([fun(i) for i in x])
print(x)
print(y)
train_size = len(x) // 2
x_train, x_test = x[1:train_size], x[train_size:]
train, test = y[1:train_size], y[train_size:]
# train autoregression
model = AR(train)
model_fit = model.fit()
print('Lag: %s' % model_fit.k_ar)
print('Coefficients: %s' % model_fit.params)
# make predictions
predictions = model_fit.predict(start=len(train), end=len(train) + len(test) - 1, dynamic=False)
for i in range(len(predictions)):
print('predicted=%f, expected=%f' % (predictions[i], test[i]))
error = mean_squared_error(test, predictions)
print('Test MSE: %.3f' % error)
# plot results
pyplot.plot(x_test, test)
pyplot.plot(x_test, predictions, color='red')
# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset) - look_back - 1):
a = dataset[i:(i + look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return numpy.array(dataX), numpy.array(dataY)
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = np.reshape(y, (y.shape[0], 1))
dataset = scaler.fit_transform(dataset)
# reshape into X=t and Y=t+1
look_back = 11
train, test = dataset[0:train_size, :], dataset[train_size - look_back:len(dataset), :]
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
print(trainX)
# reshape input to be [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
lstm_model = Sequential()
lstm_model.add(LSTM(4, input_shape=(1, look_back)))
lstm_model.add(Dense(1))
lstm_model.compile(loss='mean_squared_error', optimizer='adam')
lstm_model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
lstm_prediction = lstm_model.predict(testX)
lstm_prediction = scaler.inverse_transform(lstm_prediction)
pyplot.plot(x_test[0:len(lstm_prediction)], lstm_prediction, color='green')
pyplot.show()
| cb9d994ce45181e2364ad226bbde0adbd924355e | [
"Python"
]
| 5 | Python | reppmg/ml8 | 946f8c369ddc47b57457d17ad4fb83fe12dfd839 | 88be712c40c8740c468c21b47b9a09ff28e0ec71 |
refs/heads/master | <repo_name>asunar/weather-event-processor<file_sep>/samconfig.toml
version = 0.1
[default]
[default.deploy]
[default.deploy.parameters]
stack_name = "weather-event-processor"
s3_bucket = "aws-sam-cli-managed-default-samclisourcebucket-oztwdx5e9lhd"
s3_prefix = "weather-event-processor"
region = "us-east-1"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
<file_sep>/manualTest.sh
# Upload test data to bucket
aws s3 cp src/BulkEvents/src/test/testData/sampledata.json s3://weather-event-processor-223200533796-us-east-1-start
sam logs -n BulkEventsLambda --stack-name weather-event-processor -s 'yesterday' -e 'tomorrow' --profile personal
sam logs -n SingleEventLambda --stack-name weather-event-processor -s 'yesterday' -e 'tomorrow' --profile personal
# Expected: Received weather event
<file_sep>/src/DataPipeline.Common/src/WeatherEvent.cs
namespace DataPipeline.Common
{
public class WeatherEvent
{
public string LocationName { get; set; }
public double Temperature { get; set; }
public long Timestamp { get; set; }
public double Longitude { get; set; }
public double Latitude { get; set; }
}
}
<file_sep>/src/BulkEvents/src/test/BulkEventLambdaUnitTests.cs
using System;
using System.IO;
using Amazon.S3.Model;
using FluentAssertions;
using Xunit;
namespace BulkEvents.Tests
{
public class BulkEventLambdaUnitTests
{
// ReSharper disable once InconsistentNaming
private const string TEST_DATA_PATH = "../../../testData";
[Fact]
public void ShouldReadWeatherEvents()
{
var bulkEventsLambda = new BulkEventsLambda(null, null, "dummyTopic");
var mockS3Response = new GetObjectResponse
{
ResponseStream = File.OpenRead(Path.Combine(TEST_DATA_PATH, "sampledata.json"))
};
var weatherEvents = bulkEventsLambda.ReadWeatherEvents(mockS3Response);
weatherEvents.Count.Should().Be(3);
weatherEvents[0].LocationName.Should().Be("New York, NY");
weatherEvents[0].Temperature.Should().Be(91);
weatherEvents[0].Timestamp.Should().Be(1564428897);
weatherEvents[0].Latitude.Should().Be(40.70);
weatherEvents[0].Longitude.Should().Be(-73.99);
}
[Fact]
public void ShouldThrowWithBadData()
{
var mockS3Response = new GetObjectResponse
{
ResponseStream = File.OpenRead(Path.Combine(TEST_DATA_PATH, "baddata.json"))
};
var lambda = new BulkEventsLambda(null, null, "dummy");
Action act = () => lambda.ReadWeatherEvents(mockS3Response);
act.Should().Throw<System.Text.Json.JsonException>();
}
}
}<file_sep>/src/BulkEvents/src/BulkEventsLambda.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.Json;
using Amazon.Lambda.Core;
using Amazon.Lambda.S3Events;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Util;
using Amazon.SimpleNotificationService;
using DataPipeline.Common;
[assembly:LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace BulkEvents
{
public class BulkEventsLambda
{
private readonly AmazonS3Client _s3;
private readonly AmazonSimpleNotificationServiceClient _sns;
private readonly string _snsTopic;
public BulkEventsLambda() : this(new AmazonS3Client(), new AmazonSimpleNotificationServiceClient(), Environment.GetEnvironmentVariable("FAN_OUT_TOPIC"))
{
}
public BulkEventsLambda(AmazonS3Client s3, AmazonSimpleNotificationServiceClient sns, string snsTopic )
{
_s3 = s3;
_sns = sns;
if(string.IsNullOrEmpty(snsTopic)) throw new ArgumentNullException(nameof(snsTopic));
_snsTopic = snsTopic;
}
public void S3EventHandler(S3Event s3Event)
{
var weatherEvents = new List<WeatherEvent>();
foreach (var eventRecord in s3Event.Records)
{
var s3Object = GetObjectFromS3(eventRecord);
weatherEvents = ReadWeatherEvents(s3Object);
Console.WriteLine($"Received {weatherEvents.Count} events.");
}
weatherEvents.ForEach(PublishToSns);
}
private GetObjectResponse GetObjectFromS3(S3EventNotification.S3EventNotificationRecord s3Record)
{
var request = new GetObjectRequest
{
BucketName = s3Record.S3.Bucket.Name,
Key = s3Record.S3.Object.Key
};
return _s3.GetObjectAsync(request).Result;
}
public List<WeatherEvent> ReadWeatherEvents(GetObjectResponse response)
{
using (var responseStream = response.ResponseStream)
using (var reader = new StreamReader(responseStream))
{
return JsonSerializer.Deserialize<List<WeatherEvent>>(reader.ReadToEnd(), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true});
}
}
private void PublishToSns(WeatherEvent weatherEvent)
{
var response = _sns.PublishAsync(_snsTopic,JsonSerializer.Serialize(weatherEvent)).Result;
if(response.HttpStatusCode != HttpStatusCode.OK) Console.WriteLine($"Failed to publish weather event for {weatherEvent.LocationName}");
}
}
}
<file_sep>/src/SingleEvent/src/SingleEventLambda.cs
using System;
using System.Linq;
using System.Text.Json;
using Amazon.Lambda.Core;
using Amazon.Lambda.SNSEvents;
using DataPipeline.Common;
[assembly:LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace SingleEvent
{
public class SingleEventLambda
{
public void SnsEventHandler(SNSEvent snsEvent)
{
snsEvent.Records.ToList().ForEach(x =>
{
Console.WriteLine($"Message received: {x.Sns.Message}");
var weatherEvent = JsonSerializer.Deserialize<WeatherEvent>(x.Sns.Message);
LogEvent(weatherEvent);
});
}
private static void LogEvent(WeatherEvent weatherEvent)
{
Console.WriteLine("Received weather event:");
Console.WriteLine($"Location: {weatherEvent.LocationName}");
Console.WriteLine($"Temperature: {weatherEvent.Temperature}");
Console.WriteLine($"Latitude: {weatherEvent.Latitude}");
Console.WriteLine($"Longitude: {weatherEvent.Longitude}");
}
}
}<file_sep>/src/BulkEvents/src/test/BulkEventLambdaFunctionalTests.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Lambda.S3Events;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Util;
using Amazon.SimpleNotificationService;
using FakeItEasy;
using FluentAssertions;
using Xunit;
namespace BulkEvents.Tests
{
public class BulkEventLambdaFunctionalTests
{
private readonly S3Event _fakeS3Event;
private readonly AmazonSimpleNotificationServiceClient _fakeSns;
private readonly AmazonS3Client _fakeS3;
private readonly GetObjectRequest _s3GetObjectRequest;
private readonly string _snsTopic;
// ReSharper disable once InconsistentNaming
private const string TEST_DATA_PATH = "../../../testData";
public BulkEventLambdaFunctionalTests()
{
_fakeS3Event = new S3Event()
{
Records = new List<S3EventNotification.S3EventNotificationRecord>
{
new S3EventNotification.S3EventNotificationRecord
{
S3 = new S3EventNotification.S3Entity
{
Bucket = new S3EventNotification.S3BucketEntity
{
Name = "fakeBucket"
},
Object = new S3EventNotification.S3ObjectEntity
{
Key = "fakeKey"
}
}
}
}
};
_fakeSns = A.Fake<AmazonSimpleNotificationServiceClient>();
_fakeS3 = A.Fake<AmazonS3Client>();
_s3GetObjectRequest = new GetObjectRequest()
{
BucketName = "fakeBucket",
Key = "fakeKey"
};
_snsTopic = "test-topic";
}
[Fact]
public void ShouldPublishForEachWeatherEvent()
{
// Create mock object response from sampledata.json
var s3ResponseWithSampleData = new GetObjectResponse
{
ResponseStream = File.OpenRead(Path.Combine(TEST_DATA_PATH, "sampledata.json"))
};
// Tell fake S3 to return to return the mock object response created above.
A.CallTo(() =>
_fakeS3.GetObjectAsync(A<GetObjectRequest>.That.Matches(x => x.BucketName == _s3GetObjectRequest.BucketName && x.Key == _s3GetObjectRequest.Key), A<CancellationToken>._))
.Returns(Task.FromResult(s3ResponseWithSampleData));
var bulkEventsLambda = new BulkEventsLambda(_fakeS3, _fakeSns, _snsTopic);
bulkEventsLambda.S3EventHandler(_fakeS3Event);
// 3 events in sampledata.json => expect 3 sns publish calls.
A.CallTo(() =>
_fakeSns.PublishAsync(_snsTopic, A<string>._, CancellationToken.None))
.MustHaveHappened(3, Times.Exactly);
var expectedMessage = "{\"LocationName\":\"New York, NY\",\"Temperature\":91,\"Timestamp\":1564428897,\"Longitude\":-73.99,\"Latitude\":40.7}" ;
A.CallTo(() =>
_fakeSns.PublishAsync(_snsTopic, expectedMessage, CancellationToken.None))
.MustHaveHappenedOnceExactly();
}
[Fact]
public void ShouldThrowWithInvalidJson()
{
var s3ResponseWithBadData = new GetObjectResponse
{
ResponseStream = File.OpenRead(Path.Combine(TEST_DATA_PATH, "baddata.json"))
};
// Tell fake S3 to return to return the mock object response created above.
A.CallTo(() =>
_fakeS3.GetObjectAsync(A<GetObjectRequest>.That.Matches(x => x.BucketName == _s3GetObjectRequest.BucketName && x.Key == _s3GetObjectRequest.Key), A<CancellationToken>._))
.Returns(Task.FromResult(s3ResponseWithBadData));
var bulkEventsLambda = new BulkEventsLambda(_fakeS3, _fakeSns, _snsTopic);
Action act = () => bulkEventsLambda.S3EventHandler(_fakeS3Event);
act.Should().Throw<System.Text.Json.JsonException>();
}
}
}<file_sep>/end-to-end-tests/DataPipelineTest.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
using Amazon.CloudWatchLogs;
using Amazon.CloudWatchLogs.Model;
using Amazon.S3;
using Amazon.S3.Model;
using FluentAssertions;
using Xunit;
namespace DataPipelineTests
{
public class DataPipelineTest
{
private readonly string _stackName;
private readonly AmazonCloudFormationClient _cloudFormationClient;
private AmazonCloudWatchLogsClient _logsClient;
private const string TEST_DATA_PATH = "../../../testData";
public DataPipelineTest(string stackName="chapter6-data-pipeline")
{
if(string.IsNullOrEmpty(stackName)) throw new ArgumentNullException(nameof(stackName));
_stackName = stackName;
_cloudFormationClient = new AmazonCloudFormationClient();
}
private string ResolvePhysicalId(string logicalId)
{
var req = new DescribeStackResourceRequest()
{StackName = _stackName, LogicalResourceId = logicalId};
var result = _cloudFormationClient.DescribeStackResourceAsync(req).Result;
return result.StackResourceDetail.PhysicalResourceId;
}
private List<string> GetLogMessages(string lambdaName)
{
var logGroup = GetLogGroup(lambdaName);
_logsClient = new AmazonCloudWatchLogsClient();
var logStreams = _logsClient
.DescribeLogStreamsAsync(new DescribeLogStreamsRequest(logGroup)).Result
.LogStreams;
var responses = new List<GetLogEventsResponse>();
foreach (var logStream in logStreams)
{
responses.Add(_logsClient.GetLogEventsAsync(new GetLogEventsRequest(logGroup, logStream.LogStreamName)).Result);
}
// Each response has many events so
// simple Select would yield a nested array [[event1, event2,...event99] , [event101, event102,...event199] , [event200, event201,...event299]]
// SelectMany flattens the array [event1, event2,...event299]]
var messages = responses.SelectMany(x => x.Events)
.Where(x => x.Message.StartsWith("Location:"))
.Select(x => x.Message)
.ToList();
return messages;
}
private string GetLogGroup(string lambdaName)
{
return $"/aws/lambda/{lambdaName}";
}
[Fact(Skip = "TODO: Fix permissions then enable")]
public void DataPipelineEndtoEndTest()
{
string bucketName = ResolvePhysicalId("PipelineStartBucket");
string key = Guid.NewGuid().ToString();
var s3 = new AmazonS3Client();
s3.PutObjectAsync(new PutObjectRequest()
{
BucketName = bucketName,
Key = key,
FilePath = Path.Combine(TEST_DATA_PATH, "sampledata.json")
});
Thread.Sleep(30000);
var messages = GetLogMessages(ResolvePhysicalId("SingleEventLambda"));
messages.Should().ContainMatch("*New York, NY E2E Test*");
messages.Should().ContainMatch("*Manchester, UK E2E Test*");
messages.Should().ContainMatch("*Arlington, VA E2E Test*");
// 3. Delete object from S3 bucket (to allow a clean CloudFormation teardown)
s3.DeleteObjectAsync(bucketName, key);
// 4. Delete Lambda log groups
var singleEventLambda = ResolvePhysicalId("SingleEventLambda");
_logsClient.DeleteLogGroupAsync(
new DeleteLogGroupRequest(GetLogGroup(singleEventLambda)));
var bulkEventsLambda = ResolvePhysicalId("BulkEventsLambda");
_logsClient.DeleteLogGroupAsync(
new DeleteLogGroupRequest(GetLogGroup(bulkEventsLambda)));
}
}
}
| 82e9537677084b6b6022410c62d5a5c996b75df0 | [
"TOML",
"C#",
"Shell"
]
| 8 | TOML | asunar/weather-event-processor | 94ddb27d157bf68b09e964f5a7daadf97488bdf4 | fa2a14fbeef66fc9c1ec448001e8b4e5e265365e |
refs/heads/master | <file_sep>#include "Queue.h"
#include <iostream>
using namespace std;
int main()
{
Queue Q;
Q.addQ(10);
Q.addQ(20);
Q.addQ(30);
Q.addQ(40);
cout << Q.front() << endl;
Q.removeQ();
Q.addQ(50);
Q.addQ(60);
Q.addQ(70);
Q.addQ(80);
Q.addQ(90);
Q.addQ(100);
cout << Q.front() << endl;
Q.removeQ();
cout << Q.front() << endl;
Q.removeQ();
cout << Q.front() << endl;
Q.removeQ();
Q.addQ(110);
cout << Q.front() << endl;
Q.removeQ();
cout << Q.front() << endl;
Q.removeQ();
cout << Q.front() << endl;
system("pause");
return (0);
}<file_sep># Queue
Implementation of a queue using C++
<file_sep>#include "Queue.h"
#include <iostream>
using namespace std;
Queue::Queue()
{
myFront = myBack = counter = 0;
myArray[MAX_CAPACITY] = { 0 };
}
inline bool Queue::empty() const
{ return counter == 0; }
inline bool Queue::full()const
{return counter == MAX_CAPACITY;}
void Queue::addQ(const QElement &value)
{
if (!full())
{
counter++;
myArray[myBack] = value;
myBack = (myBack + 1) % MAX_CAPACITY;
}
else
cout << "Queue is full!, could not add " << value << " to queue!" << endl;
}
void Queue::removeQ()
{
if (!empty())
{
counter--;
myFront = (myFront + 1) % MAX_CAPACITY;
}
else
cout << "Queue is empty!" << endl;
}
QElement Queue::front() const
{
if (!empty())
return myArray[myFront];
else
cout << "No items in queue to display!" << endl;
}
<file_sep>#ifndef QUEUE_H
#define QUEUE_H
const unsigned int MAX_CAPACITY = 8;
typedef int QElement;
class Queue
{
private:
QElement myArray[MAX_CAPACITY];
unsigned int myFront,
myBack,
counter;
public:
Queue();
bool empty() const;
bool full() const;
void addQ(const QElement &value);
void removeQ();
QElement front() const;
};
#endif
| 395033a9fc03d62173ab8c3113a7eb01448afef7 | [
"Markdown",
"C++"
]
| 4 | C++ | FMenchaca/Queue | 38985cee53f22fb05aebaea5bf607b2049940a8b | 3d9288fa94c3512dd00fb4f61ef9952ef0df704a |
refs/heads/master | <file_sep>FROM python
RUN pip install elasticsearch
<file_sep>import os
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
TO_INSERT = [
{'name': 'First', 'text': 'MIDWAY upon the journey of our life'},
{'name': 'Second', 'text': 'I found myself within a forest dark,'},
{'name': 'Third', 'text': 'For the straightforward pathway had been lost.'},
{'name': 'Fourth', 'text': 'Ah me! how hard a thing it is to say'},
{'name': 'Fifth', 'text': 'What was this forest savage, rough, and stern,'},
{'name': 'Sixth', 'text': 'Which in the very thought renews the fear.'},
{'name': 'Seventh', 'text': 'So bitter is it, death is little more;'},
{'name': 'Eighth', 'text': 'But of the good to treat, which there I found,'},
{'name': 'Ninth', 'text': 'Speak will I of the other things I saw there.'},
{'name': 'Tenth', 'text': 'I cannot well repeat how there I entered,'},
]
engine = create_engine('postgresql://{}:{}@db:5432/{}'.format(os.environ['POSTGRES_USER'],
os.environ['POSTGRES_PASSWORD'],
os.environ['POSTGRES_DB']),
echo=True)
metadata = MetaData()
post = Table('post', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
Column('text', String))
metadata.create_all(engine)
conn = engine.connect()
conn.execute(post.insert(), TO_INSERT)
<file_sep>import sys
from elasticsearch import Elasticsearch
class Search:
_query_phrase = ''
_index = 'post*'
_fields = ['name', 'text']
size = 10
from_ = 0
def __init__(self):
self.connection = Elasticsearch('elasticsearch', port=9200)
def set_query(self, query_phrase):
self._query_phrase = query_phrase
def run(self):
index = self._get_index()
query = self._form_query()
results = self.connection.search(index=index, body=query,
size=self.size, from_=self.from_)
return self._clean_results(results)
def _get_index(self) -> str:
list_of_indices = list(self.connection.indices.get_alias(self._index))
list_of_indices.sort(reverse=True)
return list_of_indices[1]
def _clean_results(self, results: dict):
clean_results = [hit['_source'] for hit in results['hits']['hits']]
return clean_results
def _form_query(self) -> dict:
return {
'query': {
'bool': {
'should': [
{
'query_string': {
'fields': self._fields,
'query': self._query_phrase,
'analyzer': 'english',
'default_operator': 'AND',
}
},
{
'query_string': {
'fields': self._fields,
'query': self._query_phrase,
'analyzer': 'standard',
'default_operator': 'AND',
}
}
]
}
}
}
if __name__ == '__main__':
query = sys.argv[1]
search = Search()
if len(sys.argv) > 3:
search.size = sys.argv[3]
if len(sys.argv) > 2:
search.from_ = sys.argv[2]
search.set_query(query)
result = search.run()
print(result)
<file_sep>import time
from elasticsearch import Elasticsearch
class DeleteObsolete:
def __init__(self):
self.connection = Elasticsearch('elasticsearch', port=9200)
def get_indexes(self):
list_of_indexes = list(self.connection.indices.get_alias("*"))
list_of_indexes.sort(reverse=True)
base_indexes = set(i.split('-')[0] for i in list_of_indexes if len(i.split('-')) > 1)
return list_of_indexes, base_indexes
def get_to_delete(self, list_of_indexes, base_indexes):
to_delete = []
for base_name in base_indexes:
to_delete += self.get_to_delete_for_single_base(base_name, list_of_indexes)
return to_delete
def get_to_delete_for_single_base(self, base_name, list_of_indexes):
indexes = []
for al in list_of_indexes:
if al.startswith(base_name):
indexes.append(al)
return indexes[3:]
def delete_indexes(self, to_delete):
for i in to_delete:
self.connection.indices.delete(index=i, ignore=[400, 404])
return to_delete
def run(self):
try:
to_delete = self.get_to_delete(*self.get_indexes())
return self.delete_indexes(to_delete)
except Exception as e:
return e
if __name__ == '__main__':
while True:
instance = DeleteObsolete()
result = instance.run()
print('Deleted following indexes:', result)
time.sleep(60)
| f39b2364885c18118e746f98223ea9675be88b99 | [
"Python",
"Dockerfile"
]
| 4 | Dockerfile | Suja-K/elasticsearch-article | 74b0df24ff5ce764262ba760e8a2a0057b7eb085 | 390285a4b1d5b9128e580439e55ec7666ccbb0da |
refs/heads/master | <file_sep>import React, { Component } from 'react'
import Issue from './Issue'
class IssueList extends React.Component {
render() {
return <div className="issue-list">
<label className="switch">
<div className="slider "></div>
</label>
<table id="issueTable">
<tr>
<th>Summary</th>
<th>Company</th>
<th>Created</th>
</tr>
<tr>
<td>
<div className="content">Unable to add new phone line</div>
<div className="editIcon"> <button className="glyphicon glyphicon-edit" /></div>
</td>
<td>AT&T</td>
<td>Today</td>
</tr>
<tr>
<td><div className="content">Xbox live account is diabled</div>
<div className="editIcon"> <button className="glyphicon glyphicon-edit" />
</div></td>
<td>Microsoft</td>
<td>2 days ago</td>
</tr>
</table>
<button className="newIssue">
<div className="glyphicon glyphicon-plus-sign"></div>
</button>
</div>
}
}
export default IssueList<file_sep>import React from 'react'
class Login extends React.Component {
render() {
return <div className="auth-wrapper">
<div className="auth-inner">
<form>
<h3>Login</h3>
<button class="loginBtn loginBtn--facebook">
Login with Facebook
</button>
<button class="loginBtn loginBtn--google">
Login with Google
</button>
</form>
</div>
</div>
}
}
export default Login;
<file_sep>import React from 'react'
import Issue from './Issue'
import IssueList from './IssueList'
import Button from 'react-bootstrap/Button';
class Dashboard extends React.Component{
render(){
return <div className="dashboard-wrapper">
<h1>Dashboard</h1>
<IssueList />
<Button className="glyphicon glyphicon-circle-empty-plus newIssue" />
</div>
}
}
export default Dashboard
<file_sep>import React from 'react'
class Issue extends React.Component{
render(){
return <h1>Issue</h1>
}
}
export default Issue<file_sep>import React from 'react'
import IssueList from './IssueList'
import Login from './Login'
import Dashboard from './Dashboard'
import Settings from './Settings'
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from 'react-router-dom'
class App extends React.Component {
render() {
return <Router>
<div className="App">
<nav className="navbar navbar-expand-lg navbar-light fixed-top">
<div className="container">
<Link className="navbar-brand" to={"/login"}>Candor</Link>
<div className="collapse navbar-collapse" id="navbarTogglerDemo02">
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<Link className="nav-link" to={"/login"}>Login</Link>
</li>
</ul>
</div>
</div>
</nav>
<div className="main-wrapper">
<Switch>
<Route path="/login">
<Login />
</Route>
<Route path="/dashboard">
<Dashboard />
</Route>
<Route path="/">
<Login />
</Route>
</Switch>
</div>
</div>
</Router>
}
}
export default App
<file_sep>This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Get Started
- Install [NodeJS](https://nodejs.org/en/) & [Git](https://git-scm.com/)
- Optional - Install yarn globally `npm install -g yarn`
- Clone the project `git clone https://github.com/batchu/elysian-web` and `cd elysian-web`
- Run the command in elysian-web folder `npm install`
- Start the project 'npm run start`, open http://localhost:3000 on your browser
## Essential GIT commands
- Add, Commit & Push - `git add -am "message" && git push`
- Reset git reset<file_sep>import React,{Component} from 'react'
export default Google | a7be6b5534c2946f83b133e40a8dc100e37b959c | [
"JavaScript",
"Markdown"
]
| 7 | JavaScript | SSaiPrasad7/candor-web | 89957c099894e2ee962ae5614a0d5a08c6ed50d0 | ee23f047da1915c73d2da0d9e603e2901c65e87e |
refs/heads/main | <file_sep>rootProject.name = 'icontract-hypothesis-pycharm'
<file_sep>// Copyright (c) 2020 <NAME> <<EMAIL>>
package ch.ristin.icontract_hypothesis_pycharm;
import javax.annotation.Nullable;
import java.io.File;
/**
* Provide operations on the paths of virtual files and projects.
*/
public class Pathing {
/**
* Translate the path with slashes as separators ("/") to a system-dependent separators.
*
* @param path to be translated
* @return system-dependent path
*/
static public @Nullable
String systemDependentPath(@Nullable String path) {
if (path == null) {
return null;
}
return path.replace('/', File.separatorChar);
}
/**
* Replace the base path with "." if path prefixed by it.
*
* @param path to some file
* @param basePath base path of a project
* @return path with base path stripped to "." if prefixed by it; otherwise just the path
*/
static public
@Nullable
String stripBaseBath(@Nullable String path, @Nullable String basePath) {
if (path == null) {
return null;
}
if (basePath == null) {
return path;
}
if (path.startsWith(basePath)) {
return "." + path.substring(basePath.length());
}
return path;
}
}
<file_sep>// Copyright (c) 2020 <NAME> <<EMAIL>>
package ch.ristin.icontract_hypothesis_pycharm;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.jetbrains.python.PythonFileType;
import com.jetbrains.python.psi.PyFile;
import com.jetbrains.python.psi.PyFunction;
import com.jetbrains.python.psi.resolve.QualifiedNameFinder;
import javax.annotation.Nullable;
public class Contextualizing {
/**
* Infer the context from the caret.
*
* @param event event defining the context
* @return context of the caret or null if the context could not be inferred (*e.g.*, if not editing a Python file)
*/
static public @Nullable
Context infer(AnActionEvent event) {
final var dataContext = event.getDataContext();
final VirtualFile virtualFile = dataContext.getData(CommonDataKeys.VIRTUAL_FILE);
if (virtualFile == null) {
return null;
}
if (!(virtualFile.getFileType() instanceof PythonFileType)) {
return null;
}
final Project project = event.getProject();
if (project == null) {
return null;
}
// Try to find the module
final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
if (psiFile == null) {
return null;
}
@Nullable String module = QualifiedNameFinder.findShortestImportableName(psiFile, virtualFile);
final EditorEx editor = (EditorEx) CommonDataKeys.EDITOR.getData(event.getDataContext());
if (editor == null) {
// We can only retrieve the information about the module.
return new Context(null, psiFile, module, project);
}
final int offset = editor.getExpectedCaretOffset();
var element = psiFile.findElementAt(offset);
PyFunction pyFunction = null; // a global function corresponding to the caret
while (element != null && !(element instanceof PyFile)) {
if (element instanceof PyFunction) {
pyFunction = (PyFunction) element;
}
element = element.getParent();
}
if (element == null) {
// We couldn't infer the global function, so we can only test the whole file.
return new Context(null, psiFile, module, project);
}
return new Context(pyFunction, psiFile, module, project);
}
/**
* Compute the path as view of a context.
*
* @param context of an action
* @return system-dependent path (with base path replaced by ".", if prefixed)
*/
static public String path(Context context) {
final @Nullable String basePath = context.project.getBasePath();
final String path = context.psiFile.getVirtualFile().getPath();
return Pathing.systemDependentPath(Pathing.stripBaseBath(path, basePath));
}
}
<file_sep>package ch.ristin.icontract_hypothesis_pycharm;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.jetbrains.python.packaging.PyPackageManager;
/**
* Check that the dependencies are correctly installed and inform the user via dialogs otherwise.
*/
public class Checking {
/**
* Check that the correct version of icontract-hypothesis is installed in the virtual environment.
*
* @param project related to the event
* @return true if everything is OK
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
static public boolean icontractHypothesis(Project project) {
final Sdk sdk = ProjectRootManager.getInstance(project).getProjectSdk();
if (sdk == null) {
Messages.showMessageDialog(
project,
"There is no SDK specified for the project.\n\n" +
"Icontract-hypothesis-pycharm needs an interpreter to run icontract-hypothesis.",
"No SDK Specified",
Messages.getErrorIcon());
return false;
}
final var packages = PyPackageManager.getInstance(sdk).getPackages();
if (packages == null) {
Messages.showMessageDialog(
project,
"There are no packages specified for the SDK: " + sdk.getName() + ".\n" +
"Icontract-hypothesis-pycharm depends on the package icontract-hypothesis.",
"No Packages Specified for the SDK",
Messages.getErrorIcon());
return false;
}
String versionFound = "";
for (var pkg : packages) {
if (pkg.getName().equals("icontract-hypothesis")) {
versionFound = pkg.getVersion();
break;
}
}
if (versionFound.equals("")) {
Messages.showMessageDialog(
project,
"The package icontract-hypothesis has not been installed " +
"in the virtual environment of your current SDK: " + sdk.getName() + ".\n\n" +
"Icontract-hypothesis-pycharm depends on icontract-hypothesis.\n" +
"Please install it in your virtual environment.",
"No Icontract-Hypothesis Found",
Messages.getErrorIcon());
return false;
}
if (!versionFound.startsWith("1.")) {
Messages.showMessageDialog(
project,
"The version of this icontract-hypothesis-pycharm expects the version 1.*.* " +
"of the icontract-hypothesis.\n\n" +
"However, icontract-hypothesis " + versionFound + " is installed " +
"in the virtual environment of your current SDK: " + sdk.getName() + ".\n\n" +
"Please install the expected version of icontract-hypothesis in your virtual environment.",
"Unexpected Version of Icontract-Hypothesis Found",
Messages.getErrorIcon());
return false;
}
return true;
}
}
<file_sep># icontract-hypothesis-pycharm
Icontract-hypothesis-pycharm is a plug-in for [PyCharm IDE](https://www.jetbrains.com/pycharm/) that
allows you to automatically test your Python code using
[icontract-hypothesis](https://github.com/mristin/icontract-hypothesis).
## Installation
**Install icontract-hypothesis-pycharm**.
Use [Plug-in manager](https://www.jetbrains.com/help/pycharm/managing-plugins.html) in your PyCharm:
File ⟶ Settings ⟶ Plugins.
Select `icontract-hypothesis-pycharm`.
<img src="readme/settings.png" width=300 alt="settings" />
<img src="readme/settings-plugins.png" width=400 alt="settings-plugins" />
<img src="readme/settings-plugins-install.png" width=700 alt="settings-plugins-install" />
**Install icontract-hypothesis**.
As icontract-hypothesis-pycharm is only a thin wrapper around
[icontract-hypothesis](https://github.com/mristin/icontract-hypothesis), please install
[icontract-hypothesis](https://github.com/mristin/icontract-hypothesis) manually in
the virtual environment of your project.
For example, through: File ⟶ Settings ⟶ Project ⟶ Python Interpreter.
<img src="readme/settings.png" width=300 alt="settings" />
<img src="readme/settings-project-interpreter.png" width=600 alt="settings-project-interpreter" />
<img src="readme/settings-install-package.png" width=600 alt="settings-install-package" />
If you are writing a package using
[`setup.py`](https://packaging.python.org/tutorials/packaging-projects/), you might want to include
[icontract-hypothesis](https://github.com/mristin/icontract-hypothesis) in
[your test dependencies](https://stackoverflow.com/questions/15422527/best-practices-how-do-you-list-required-dependencies-in-your-setup-py).
## Usage
You can use icontract-hypothesis-pycharm from within an editor (with an open Python file) through
the editor pop-up menu:
<img src="readme/editor-popup.png" width=900 alt="editor pop-up menu" />
Alternatively, you can select a file in the project view and access icontract-hypothesis-pycharm
through the project view pop-up menu:
<img src="readme/project-view-popup.png" width=450 alt="project view pop-up menu" />
### Actions
Icontract-hypothesis-pycharm creates the run configuration based on the selected action (described
below).
You can view and edit these run configurations manually or re-run them (usually by pressing
Shift+F10).
Icontract-hypothesis-pycharm will *not* overwrite the run configurations so the manual changes will
persist.
For example, it is practical to modify the run configuration to disable certain health checks or
set Hypothesis parameters (such as
[`max_examples`](https://github.com/mristin/icontract-hypothesis#testing-tool)).
The icontract-hypothesis infers the Hypothesis strategies based on the contracts and types.
Depending on the user, the following actions are executed:
**Test {module or function}**.
The inferred Hypothesis strategies are executed (*i.e.*, the module or function are automatically
tested).
**Inspect {module or function}**.
The inferred Hypothesis strategies are written to standard output so that the user can inspect them.
**Ghostwrite explicit {module} to STDOUT**.
The Hypothesis strategies inferred for a module are used to ghost-write and print a test file
to the standard output.
The strategies are explicitly written (*i.e.*, the test file involves no references to
`icontract-hypothesis`).
**Ghostwrite explicit {module} to ...**.
The Hypothesis strategies inferred for a module are used to ghost-write a test file.
The user is asked to select the destination.
The strategies are explicitly written (*i.e.*, the test file involves no references to
`icontract-hypothesis`).
## Contributing
Feature requests or bug reports are always very, very welcome!
Please see quickly if the issue does not already exist in the
[issue section](https://github.com/mristin/icontract-hypothesis-pycharm/issues) and, if not,
create [a new issue](https://github.com/mristin/icontract-hypothesis-pycharm/issues/new).
You can also contribute in code.
Please use [GitHub's fork workflow](https://gist.github.com/Chaser324/ce0505fbed06b947d962).
The commit messages follow [<NAME>' guidelines](https://chris.beams.io/posts/git-commit/).
Please discuss briefly the feature you'd like to implement beforehand so that we can
explore together the use case and how it fits with the overall vision.
## Versioning
We follow a bit unusual semantic versioning schema:
* X is the oldest supported version of
[icontract-hypothesis](https://github.com/mristin/icontract-hypothesis),
* Y is the minor version (new or modified features), and
* Z is the patch version (only bug fixes).
<file_sep># Tips and Tricks when Developing a PyCharm Plug-in
Written by: <NAME> (<EMAIL>, 2021-01-20)
I found it hard to develop a PyCharm plug-in.
There were very few tutorials available, the information is scattered and the documentation usually
refers to IntelliJ SDK, but I couldn't find the up-to-date PyCharm API.
This left me with [JetBrains youtrack](https://youtrack.jetbrains.com) being my main source of
information.
Here is the list of tutorials that I found so far:
* [Live Development of a PyCharm Plugin (video)](https://www.youtube.com/watch?v=cR-28eaXGQI)
* http://kflu.github.io/2019/08/24/2019-08-24-writing-pycharm-plugin/
* https://github.com/JetBrains/intellij-sdk-code-samples/tree/main/product_specific/pycharm_basics
Here is the documentation of the IntelliJ Platform SDK:
https://plugins.jetbrains.com/docs/intellij/welcome.html
The group IDs and action IDs are pre-defined in:
https://github.com/JetBrains/intellij-community/blob/master/platform/platform-resources/src/idea/LangActions.xml
Here is how you can get an offset in the file:
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206150409-How-do-I-get-to-PSI-from-a-document-or-editor-
A couple of PyCharm plug-ins I used as a reference:
* [pysynthetic-intellij](https://github.com/jhominal/pysynthetic-intellij)
* [pydantic-pycharm-plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin)
## Creating a New Project
I used IntelliJ IDEA Community 2020.3.
Here are the steps:
**Download and install a java development kit.**
I installed [adopt-openjdk-11](https://adoptopenjdk.net/).
It has to be the version 11, otherwise the JARs are incompatible with PyCharm 2020.
**Create a new project in IntelliJ.**
**Select Gradle project and tick "IntelliJ Platform Plugin"**.

**Specify the project coordinates.**

**Re-write `build.gradle` in the root directory.**
Remove the section `patchPluginXml` as we will directly edit the `plugin.xml`.
Fix `intellij` section. Don't forget to include `plugins "python-ce"`!
**Re-write `src/main/resources/META-INF/plugin.xml`.**
Change the plug-in and vendor information.
Include `<depends>com.intellij.modules.python</depends>`.
Don't worry if it is marked red -- the PyCharm CE will be downloaded only in the next
step.
Remove `<extension>`'s for now. (Add extensions later if the plug-in really needs them.)
**Try to compile the project without any actions specified so far.**
The PyCharm-CE should be automatically downloaded together with the sources so that
you can easily debug.
The download might take a couple of minutes.
In contrast to [this tutorial](http://kflu.github.io/2019/08/24/2019-08-24-writing-pycharm-plugin/)
and instructions from [pysynthetic-intellij](https://github.com/jhominal/pysynthetic-intellij),
I didn't have to manually download PyCharm-CE and Gradle took care of it for me.
Restart IntelliJ now just for good luck.
**Define the `<action>`s in `plugin.xml`.**
Consult the IntelliJ Platform SDK on
[how to gropu actions](https://plugins.jetbrains.com/docs/intellij/grouping-action.html).
See in particular what attributes `compact` and `popup` mean. (These were not obvious to me.)
As far as I can tell, if you want to hide the whole group when the user selects, say, a non-Python
file, you need to implement your own action group by extending the
`com.intellij.openapi.actionSystem.DefaultActionGroup` and deciding when to show it in the
overridden `update` method.
**Check that the Python dependencies are installed.**
Consult https://plugins.jetbrains.com/docs/intellij/sdk.html to see how to obtain the project's
SDK.
(This was very tricky to search for on the web.)
Get the project's SDK with:
```java
final Sdk sdk = ProjectRootManager.getInstance(project).getProjectSdk();
```
Get the list of installed packages with:
```java
final var packages = PyPackageManager.getInstance(sdk).getPackages();
```
**Deploy the plugin.**
The documentation from https://plugins.jetbrains.com/docs/intellij/deploying-plugin.html is
confusing as it is not refering to a Gradle project though Gradle projects are *recommended* for
plugin development ("Gradle plugin is the recommended solution for building IntelliJ plugins",
see https://plugins.jetbrains.com/docs/intellij/gradle-build-system.html).
[This IntelliJ support ticket](https://intellij-support.jetbrains.com/hc/en-us/community/posts/360000592024-Unable-to-prepare-IntelliJ-plugin-for-deployment)
explains the issue.
This is the section of the official documentation that explains how to build and publish the plugin:
https://plugins.jetbrains.com/docs/intellij/deployment.html.
You need to manually create a Gradle task as a run configuration:
* Click on "Edit configurations",
* Click on "+" (to add a new run configuration),
* Select "Gradle",
* Make the plug-in project your Gradle project,
* Write manually `buildPlugin` in the field "Tasks", and
* Run it.
The distribution should be available in `build/distributions/{your plugin}.zip`.
**Upload the plugin.**
Visit https://plugins.jetbrains.com/plugin/add.
<file_sep>plugins {
id 'java'
id 'org.jetbrains.intellij' version '0.6.5'
}
group 'ch.ristin.icontract_hypothesis_pycharm'
version '1.0.0'
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}
// See https://github.com/JetBrains/gradle-intellij-plugin/
intellij {
pluginName project.name
version "2020.1"
type "PC"
updateSinceUntilBuild false
downloadSources true
plugins "python-ce"
}
test {
useJUnitPlatform()
}<file_sep>// Copyright (c) 2020 <NAME> <<EMAIL>>
package ch.ristin.icontract_hypothesis_pycharm;
import com.intellij.execution.RunManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
/**
* Test with icontract-hypothesis.
*/
public class TestAction extends AnAction {
/**
* Specify and run the "icontract-hypothesis test" command as a run configuration.
*
* @param event Event received when the associated menu item is chosen.
*/
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
final Project project = event.getProject();
assert project != null;
if (!Checking.icontractHypothesis(project)) {
return;
}
Context context = Contextualizing.infer(event);
assert context != null;
final String path = Contextualizing.path(context);
String target = path;
if (context.pyFunction != null) {
target += " " + context.pyFunction.getName();
}
String runName = String.format("icontract-hypothesis test %s", target);
var scriptParameters = new ArrayList<String>();
scriptParameters.add("test");
scriptParameters.add("--path");
scriptParameters.add(path);
if (context.pyFunction != null) {
scriptParameters.add("--include");
scriptParameters.add(context.pyFunction.getName());
}
var runManager = RunManager.getInstance(project);
var runner = Running.FindOrCreateRunner(
runManager, runName, scriptParameters,
Pathing.systemDependentPath(context.project.getBasePath()));
Running.execute(runManager, runner);
}
/**
* Change the visibility/enabled as well as the title of the action depending on the context.
*
* @param event Event received when the associated menu item is chosen.
*/
@Override
public void update(@NotNull AnActionEvent event) {
Context context = Contextualizing.infer(event);
final Presentation presentation = event.getPresentation();
if (context == null) {
presentation.setEnabledAndVisible(false);
return;
}
// Change the name depending whether it is a module or a global function
String target;
if (context.pyFunction != null) {
target = context.pyFunction.getName();
} else {
target = Contextualizing.path(context);
}
presentation.setText(String.format("test %s", target), false);
presentation.setDescription(
String.format("Infer the Hypothesis strategy for %s and execute it", target));
presentation.setEnabledAndVisible(true);
}
}
| 6ccf82647168095f261e5a90c1c1943772c57f15 | [
"Markdown",
"Java",
"Gradle"
]
| 8 | Gradle | mristin/icontract-hypothesis-pycharm | 7235fecfe4ff5f3b77600417863f34610e569637 | 26b9717a1a21bc43e16be74c66decfe376b96070 |
refs/heads/master | <file_sep>spring.datasource.url=jdbc:postgresql://localhost:5432/adminservice-prod
spring.datasource.username=
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
server.port=9090<file_sep>package com.cognizant.goldenretrievers.adminservices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BadgeController {
@Autowired
private BadgesDataStore badgeDataStore;
@PostMapping("/requestBadge")
public String test(@RequestBody BadgeRequest badgeRequest) {
if (null == badgeRequest || badgeRequest.getEmployeeId().isEmpty()) {
BadgeResult badgeResult = new BadgeResult();
badgeResult.setStatusMessage("error");
//return badgeResult.toString();
return badgeResult.getBadgeId();
}
return badgeDataStore.getBadge(badgeRequest.getEmployeeId());
}
@PostMapping("/returnBadge")
public String returnBadges(@RequestBody BadgeRequest badgeRequest){
if (null == badgeRequest || badgeRequest.getBadgeNumber().isEmpty()) {
BadgeResult badgeResult = new BadgeResult();
badgeResult.setStatusMessage("error");
return badgeResult.toString();
}
return badgeDataStore.returnIssuedBadge(badgeRequest.getBadgeNumber());
}
}
<file_sep>package com.cognizant.goldenretrievers.adminservices;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
public class BadgeResult {
private String badgeId;
private String statusMessage;
public BadgeResult(){}
@JsonCreator
public BadgeResult(@JsonProperty("statusMessage") final String statusMessage, @JsonProperty("badgeId") final String badgeId) {
this.statusMessage = statusMessage;
this.badgeId = badgeId;
}
public String getBadgeId() {
return badgeId;
}
public void setBadgeId(String badgeId) {
this.badgeId = badgeId;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
@Override
public String toString() {
return "{\"badgeId\" :" + "\"" + badgeId+ "\" ," + "\"statusMessage\":"
+ "\"" + statusMessage+ "\" " + "}";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BadgeResult)) return false;
BadgeResult that = (BadgeResult) o;
return Objects.equals(getBadgeId(), that.getBadgeId()) &&
Objects.equals(getStatusMessage(), that.getStatusMessage());
}
@Override
public int hashCode() {
return Objects.hash(getBadgeId(), getStatusMessage());
}
}
<file_sep>package com.cognizant.goldenretrievers.adminservices;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.stereotype.Component;
@Component
public class BadgeRequest {
private String employeeId;
private String badgeNumber;
public String getBadgeNumber() {
return badgeNumber;
}
public void setBadgeNumber(String batchNumber) {
this.badgeNumber = batchNumber;
}
public BadgeRequest(){
}
@JsonCreator
public BadgeRequest(@JsonProperty("employeeId") final String employeeId){
this.employeeId = employeeId;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
employeeId = employeeId;
}
}
<file_sep>package com.cognizant.goldenretrievers.adminservices;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.deploy.net.HttpResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.hamcrest.Matchers.contains;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class BadgeControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
private BadgeRequest badgeRequest;
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Test
public void requestForBadgeReturnRequestedBadge() throws Exception{
BadgeResult resultObject = new BadgeResult();
resultObject.setBadgeId("1");
resultObject.setStatusMessage("badge Assigned successfully");
String actual = mvc.perform(post("/requestBadge")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"employeeId\" :" + "\"" + "2" + "\"" + "}"))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
BadgeResult resultObject1 = new BadgeResult();
resultObject1.setBadgeId("2");
resultObject1.setStatusMessage("badge Assigned successfully");
String actual1 = mvc.perform(post("/requestBadge")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"employeeId\" :" + "\"" + "3" + "\"" + "}"))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
BadgeResult resultObject2 = new BadgeResult();
resultObject2.setBadgeId("3");
resultObject2.setStatusMessage("badge Assigned successfully");
String actual2 = mvc.perform(post("/requestBadge")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"employeeId\" :" + "\"" + "5" + "\"" + "}"))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
BadgeResult actualObject2 = OBJECT_MAPPER.readValue(actual2, new TypeReference<BadgeResult>() {
});
//Assert
assertThat(actualObject2, is(resultObject2));
}
@Test
public void returnForBadgeWhatYou() throws Exception{
String actual = mvc.perform(post("/requestBadge")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"employeeId\" :" + "\"" + "2" + "\"" + "}"))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
BadgeResult resultObject1 = new BadgeResult();
resultObject1.setBadgeId("1");
resultObject1.setStatusMessage("returned successfully");
String actual1 = mvc.perform(post("/returnBadge")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"badgeNumber\" :" + "\"" + "1" + "\"" + "}"))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
BadgeResult actualObject1 = OBJECT_MAPPER.readValue(actual1, new TypeReference<BadgeResult>() {
});
//Assert
assertThat(actualObject1, is(resultObject1));
}
}
<file_sep># golden-retrievers-admin
| f4fac5f0a4b5b058dccd4ba3fed4f04ca9c231dc | [
"Markdown",
"Java",
"INI"
]
| 6 | INI | bhagyeshree/demo-admin | 890925b8271c6961d0702f94f12010f03561b557 | 570c6df2cea72ebd277a7d3e5c0368d03c53cc1f |
refs/heads/main | <file_sep>package br.com.boticario.cashback.service;
import br.com.boticario.cashback.model.Status;
import br.com.boticario.cashback.model.Order;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ExceptionsUseCaseService {
public static final List<String> DOCUMENTS = List.of("15350946056");
public void approveExceptions(Order order) {
if (DOCUMENTS.contains(order.getReseller().getDocument())) {
order.setStatus(Status.APPROVED);
}
}
}
<file_sep>package br.com.boticario.cashback.controller;
import br.com.boticario.cashback.controller.dto.OrderDto;
import br.com.boticario.cashback.controller.form.OrderForm;
import br.com.boticario.cashback.service.OrderService;
import br.com.boticario.cashback.service.ResellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping(path = "/orders")
public class OrderController {
private final ResellerService resellerService;
private final OrderService orderService;
@Autowired
public OrderController(ResellerService resellerService, OrderService orderService) {
this.resellerService = resellerService;
this.orderService = orderService;
}
@PostMapping
public ResponseEntity<OrderDto> create(@Valid @RequestBody OrderForm form, UriComponentsBuilder uriBuilder) {
var model = form.toModel(resellerService);
orderService.create(model);
URI uri = uriBuilder.path("/resellers/{id}").buildAndExpand(model.getId()).toUri();
var dto = new OrderDto(model);
return ResponseEntity.created(uri).body(dto);
}
@GetMapping
public ResponseEntity<List<OrderDto>> list() {
var listOfOrders = orderService.findAll();
var dto = listOfOrders.stream().map(OrderDto::new).collect(Collectors.toList());
return ResponseEntity.ok(dto);
}
}
<file_sep>package br.com.boticario.cashback.service;
import br.com.boticario.cashback.model.Order;
import br.com.boticario.cashback.model.Reseller;
import br.com.boticario.cashback.repository.OrderRepository;
import br.com.boticario.cashback.repository.ResellerRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
OrderRepository orderRepository;
@Test
void when_model_is_valid_should_success() {
var orderService = new OrderService(orderRepository);
Reseller reseller = new Reseller();
reseller.setId(1L);
reseller.setName("Reseller");
reseller.setDocument("00000000000");
reseller.setEmail("<EMAIL>");
reseller.setPassword("<PASSWORD>");
Order order = new Order();
order.setId(1L);
order.setOrderDate(LocalDateTime.now());
order.setPrice(new BigDecimal("100.00"));
order.setReseller(reseller);
orderService.create(order);
Mockito.verify(orderRepository, Mockito.times(1)).save(order);
}
}
<file_sep>package br.com.boticario.cashback.controller.dto;
import br.com.boticario.cashback.controller.form.NewResellerForm;
import br.com.boticario.cashback.model.Reseller;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.crypto.password.PasswordEncoder;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(MockitoExtension.class)
public class NewResellerFormTest {
@Mock
private PasswordEncoder passwordEncoder;
@Test
void when_form_is_valid_should_return_model() {
NewResellerForm form = new NewResellerForm();
form.setName("Reseller");
form.setDocument("00000000000");
form.setEmail("<EMAIL>");
form.setPassword("<PASSWORD>");
Reseller reseller = form.toModel(passwordEncoder);
assertEquals(reseller.getName(), form.getName());
assertEquals(reseller.getDocument(), form.getDocument());
assertEquals(reseller.getEmail(), form.getEmail());
}
}
<file_sep>package br.com.boticario.cashback.config.security;
import br.com.boticario.cashback.model.Reseller;
import br.com.boticario.cashback.repository.ResellerRepository;
import br.com.boticario.cashback.service.TokenService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AuthenticationByTokenFilter extends OncePerRequestFilter {
private final TokenService tokenService;
private final ResellerRepository resellerRepository;
public AuthenticationByTokenFilter(TokenService tokenService, ResellerRepository resellerRepository) {
this.tokenService = tokenService;
this.resellerRepository = resellerRepository;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
var token = getToken(request);
boolean valid = tokenService.isValidToken(token);
if (valid) {
authenticateUser(token);
}
filterChain.doFilter(request, response);
}
private void authenticateUser(String token) {
Long userId = tokenService.getUserId(token);
Reseller reseller = resellerRepository.findById(userId).get();
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(reseller, null, reseller.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
private String getToken(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (token == null || !token.startsWith("Bearer ")) {
return null;
}
return token.substring(7, token.length());
}
}
<file_sep>package br.com.boticario.cashback.service;
import br.com.boticario.cashback.model.Reseller;
import br.com.boticario.cashback.repository.ResellerRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class ResellerServiceTest {
@Mock
ResellerRepository resellerRepository;
@Test
void when_model_is_valid_should_success() {
ResellerService resellerService = new ResellerService(resellerRepository);
Reseller model = new Reseller();
model.setId(1L);
model.setName("Reseller");
model.setDocument("00000000000");
model.setEmail("<EMAIL>");
model.setPassword("<PASSWORD>");
resellerService.create(model);
Mockito.verify(resellerRepository, Mockito.times(1)).save(model);
}
}
<file_sep>package br.com.boticario.cashback.constant;
public final class Paths {
private Paths() {
throw new AssertionError("Cannot be instantiated");
}
public static final String RESELLERS = "/resellers";
}
<file_sep>package br.com.boticario.cashback.model;
public enum Status {
VALIDATING,
APPROVED
}
<file_sep>package br.com.boticario.cashback.controller;
import br.com.boticario.cashback.controller.dto.TokenDto;
import br.com.boticario.cashback.controller.form.LoginForm;
import br.com.boticario.cashback.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping("/login")
@Profile(value = {"prod", "test"})
public class LoginController {
private final TokenService tokenService;
private final AuthenticationManager authManager;
@Autowired
public LoginController(TokenService tokenService, AuthenticationManager authManager) {
this.tokenService = tokenService;
this.authManager = authManager;
}
@PostMapping
public ResponseEntity<TokenDto> authenticate(@RequestBody @Valid LoginForm form) {
var loginData = form.mapToUsernamePasswordAuthenticationToken();
try {
var authentication = authManager.authenticate(loginData);
var token = tokenService.createToken(authentication);
return ResponseEntity.ok(new TokenDto(token, "Bearer"));
} catch (AuthenticationException e) {
return ResponseEntity.badRequest().build();
}
}
}
<file_sep>package br.com.boticario.cashback.controller.dto;
import br.com.boticario.cashback.model.Reseller;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ResellerDtoTest {
@Test
void when_model_is_valid_should_instantiates() {
Reseller model = new Reseller();
model.setId(1L);
model.setName("Reseller");
model.setDocument("00000000000");
model.setEmail("<EMAIL>");
model.setPassword("<PASSWORD>");
ResellerDto resellerDto = new ResellerDto(model);
assertEquals(resellerDto.getName(), model.getName());
assertEquals(resellerDto.getDocument(), model.getDocument());
assertEquals(resellerDto.getEmail(), model.getEmail());
}
}
| 388d058da61075d0db7c98ec587a0958a05a7d48 | [
"Java"
]
| 10 | Java | SamuelLFA/cashback | 74b2352adfa4f152d239529032610e498c661dfc | 997b7566199607cb8ae71d81b37f613a308b202e |
refs/heads/master | <file_sep>#!/bin/bash
echo "compiling javacc"
javacc Moopl-grammar.jj
printf "\ncompiling java source\n"
javac *.java
printf "\ntesting tokens\n"
java TestTokens tokens
echo "done"<file_sep>#!/bin/bash
./build.sh
java TestTokens tokens
<file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_162) on Tue Mar 06 20:52:41 UTC 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>MooplParserConstants</title>
<meta name="date" content="2018-03-06">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="MooplParserConstants";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/MooplParserConstants.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="MooplParser.html" title="class in <Unnamed>"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="MooplParserTokenManager.html" title="class in <Unnamed>"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="index.html?MooplParserConstants.html" target="_top">Frames</a></li>
<li><a href="MooplParserConstants.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<h2 title="Interface MooplParserConstants" class="title">Interface MooplParserConstants</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="MooplParser.html" title="class in <Unnamed>">MooplParser</a>, <a href="MooplParserTokenManager.html" title="class in <Unnamed>">MooplParserTokenManager</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="typeNameLabel">MooplParserConstants</span></pre>
<div class="block">Token literal values and constants.
Generated by org.javacc.parser.OtherFilesGen#start()</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#ARRAYOF">ARRAYOF</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#BOOL">BOOL</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#CLASS">CLASS</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#CLOSEBRACE">CLOSEBRACE</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#CLOSEPAREN">CLOSEPAREN</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#CLOSESBR">CLOSESBR</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#COMMA">COMMA</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#DEFAULT">DEFAULT</a></span></code>
<div class="block">Lexical state.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#DO">DO</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#DOT">DOT</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#ELSE">ELSE</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#ENDST">ENDST</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#EOF">EOF</a></span></code>
<div class="block">End of File.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#EQUALS">EQUALS</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#EXTENDS">EXTENDS</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#FALSE">FALSE</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#FUN">FUN</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#ID">ID</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#IF">IF</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#INT">INT</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#INTEGER_LITERAL">INTEGER_LITERAL</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#ISNULL">ISNULL</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#LENGTH">LENGTH</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#NEW">NEW</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#NOT">NOT</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#OBJECT">OBJECT</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#OP">OP</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#OPENBRACE">OPENBRACE</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#OPENPAREN">OPENPAREN</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#OPENSBR">OPENSBR</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#OUTPUT">OUTPUT</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#PROC">PROC</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#RETURN">RETURN</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#SELF">SELF</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#THEN">THEN</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.lang.String[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#tokenImage">tokenImage</a></span></code>
<div class="block">Literal token values.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#TRUE">TRUE</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="MooplParserConstants.html#WHILE">WHILE</a></span></code>
<div class="block">RegularExpression Id.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="EOF">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>EOF</h4>
<pre>static final int EOF</pre>
<div class="block">End of File.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.EOF">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="PROC">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PROC</h4>
<pre>static final int PROC</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.PROC">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="FUN">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>FUN</h4>
<pre>static final int FUN</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.FUN">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="CLASS">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CLASS</h4>
<pre>static final int CLASS</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.CLASS">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="EXTENDS">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>EXTENDS</h4>
<pre>static final int EXTENDS</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.EXTENDS">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="RETURN">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>RETURN</h4>
<pre>static final int RETURN</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.RETURN">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="BOOL">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>BOOL</h4>
<pre>static final int BOOL</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.BOOL">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="TRUE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>TRUE</h4>
<pre>static final int TRUE</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.TRUE">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="FALSE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>FALSE</h4>
<pre>static final int FALSE</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.FALSE">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="SELF">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>SELF</h4>
<pre>static final int SELF</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.SELF">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="INT">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>INT</h4>
<pre>static final int INT</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.INT">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="ARRAYOF">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ARRAYOF</h4>
<pre>static final int ARRAYOF</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.ARRAYOF">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="IF">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>IF</h4>
<pre>static final int IF</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.IF">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="THEN">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>THEN</h4>
<pre>static final int THEN</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.THEN">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="ELSE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ELSE</h4>
<pre>static final int ELSE</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.ELSE">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="WHILE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>WHILE</h4>
<pre>static final int WHILE</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.WHILE">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="DO">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>DO</h4>
<pre>static final int DO</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.DO">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="OUTPUT">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>OUTPUT</h4>
<pre>static final int OUTPUT</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.OUTPUT">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="LENGTH">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>LENGTH</h4>
<pre>static final int LENGTH</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.LENGTH">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="NEW">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>NEW</h4>
<pre>static final int NEW</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.NEW">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="OBJECT">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>OBJECT</h4>
<pre>static final int OBJECT</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.OBJECT">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="ISNULL">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ISNULL</h4>
<pre>static final int ISNULL</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.ISNULL">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="DOT">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>DOT</h4>
<pre>static final int DOT</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.DOT">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="COMMA">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>COMMA</h4>
<pre>static final int COMMA</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.COMMA">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="EQUALS">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>EQUALS</h4>
<pre>static final int EQUALS</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.EQUALS">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="OPENSBR">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>OPENSBR</h4>
<pre>static final int OPENSBR</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.OPENSBR">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="CLOSESBR">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CLOSESBR</h4>
<pre>static final int CLOSESBR</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.CLOSESBR">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="OPENBRACE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>OPENBRACE</h4>
<pre>static final int OPENBRACE</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.OPENBRACE">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="CLOSEBRACE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CLOSEBRACE</h4>
<pre>static final int CLOSEBRACE</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.CLOSEBRACE">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="OPENPAREN">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>OPENPAREN</h4>
<pre>static final int OPENPAREN</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.OPENPAREN">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="CLOSEPAREN">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CLOSEPAREN</h4>
<pre>static final int CLOSEPAREN</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.CLOSEPAREN">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="ENDST">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ENDST</h4>
<pre>static final int ENDST</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.ENDST">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="NOT">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>NOT</h4>
<pre>static final int NOT</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.NOT">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="OP">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>OP</h4>
<pre>static final int OP</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.OP">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="INTEGER_LITERAL">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>INTEGER_LITERAL</h4>
<pre>static final int INTEGER_LITERAL</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.INTEGER_LITERAL">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="ID">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ID</h4>
<pre>static final int ID</pre>
<div class="block">RegularExpression Id.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.ID">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="DEFAULT">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>DEFAULT</h4>
<pre>static final int DEFAULT</pre>
<div class="block">Lexical state.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="constant-values.html#MooplParserConstants.DEFAULT">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="tokenImage">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>tokenImage</h4>
<pre>static final java.lang.String[] tokenImage</pre>
<div class="block">Literal token values.</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/MooplParserConstants.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="MooplParser.html" title="class in <Unnamed>"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="MooplParserTokenManager.html" title="class in <Unnamed>"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="index.html?MooplParserConstants.html" target="_top">Frames</a></li>
<li><a href="MooplParserConstants.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
<file_sep>#!/bin/bash
javacc Moopl-grammar.jj
rm *.class
javac *.java
<file_sep>#!/bin/bash
function parse {
echo parsing nt_$1\(\)
sed -ie "s|parser\.nt_.*()|parser\.nt_$1()|g" Parse.java
javac Parse.java
for var in "${@:2}"
do
echo "$var" | java Parse
done
}
function examples {
parse Program
for file in examples/*.moopl
do
echo file: $file
echo "$(<$file)" | java Parse
done
}
function pretty {
for file in examples/*.moopl
do
out="$(java PrettyPrint $file | sed -e 's|//.*$||g')"
in="$(cat $file | sed -e 's|//.*$||g')"
printf "%s\n\n" $file
#diff -I '/\*.*\*/' -BEwy --suppress-common-lines --color=auto <(echo "$out") <(echo "$in")
diff -I '/\*.*\*/' -BEwy --color=auto <(echo "$out") <(echo "$in")
done
}
#parsing
javacc Moopl-grammar.jj
sed -ie "s|.*parser.nt_Program()|\t\t\t//parser.nt_Program()|g" PrettyPrint.java
rm *.class
javac *.java
#add tests for Moopl-grammar.jj here
examples
#semantic analysis
javacc Moopl.jj
sed -ie "s|.*parser.nt_Program()|\t\t\tparser.nt_Program()|g" PrettyPrint.java
rm *.class
javac *.java
#add tests for Moopl.jj here
examples
pretty
| 36a97ea75103b6ca1057cb774463da52307b451c | [
"HTML",
"Shell"
]
| 5 | Shell | ChristopherMichael-Stokes/IN2009-Part1 | 4896c12235d85f93b4f0af235485a981d3502ba9 | 4410a8bf4deb842289a3fab1991926f45f73e5bb |
refs/heads/master | <file_sep>package main
import "fmt"
func main() {
var i int
var m map[string]string
var a []int
passIntByValue(i)
fmt.Printf("passIntByValue: %d\n", i)
passIntByPointer(&i)
fmt.Printf("passIntByPointer: %d\n", i)
passIntByInterface(&i)
fmt.Printf("passIntByInterface: %d\n", i)
passIntByInterfaceValue(i)
fmt.Printf("passIntByInterfaceValue: %d\n", i)
fmt.Printf("before processing the map %t\n", m != nil)
passMapByValue(m)
fmt.Printf("passMapByValue %t\n", m != nil)
fmt.Printf("before processing the array %t\n", a != nil)
passArrayByValue(a)
fmt.Printf("passArrayByValue %t\n", a != nil)
passArrayByPointer(&a)
fmt.Printf("passArrayByPointer %t\n", a != nil)
typeCast(&i)
// it prints
// passIntByValue: 0
// passIntByPointer: 88
// passIntByInterface: 77
// passIntByInterfaceValue (inside): 66
// passIntByInterfaceValue: 77
// before processing the map false
// passMapByPointer (inside): true
// passMapByValue false
// before processing the array false
// passArrayByValue (inside): true
// passArrayByValue false
// passArrayByPointer true
// typeCast *int: 77
}
func passIntByValue(v int) {
v = 999
}
func passIntByPointer(v *int) {
*v = 88 // equivalent to v = 88
}
func passIntByInterface(v interface{}) {
temp := v.(*int)
*temp = 77
}
func passIntByInterfaceValue(v interface{}) {
temp := v.(int)
temp = 66
fmt.Printf("passIntByInterfaceValue (inside): %d\n", temp)
}
func passMapByValue(v map[string]string) {
v = make(map[string]string)
fmt.Printf("passMapByPointer (inside): %t\n", v != nil)
}
func passArrayByValue(v []int) {
v = make([]int, 10)
fmt.Printf("passArrayByValue (inside): %t\n", v != nil)
}
func passArrayByPointer(v *[]int) {
*v = make([]int, 10)
}
func typeCast(v interface{}) {
switch c := v.(type) {
case int:
fmt.Printf("typeCast int: %d\n", c)
case string:
fmt.Printf("typeCase string: %s\n", c)
case *int:
fmt.Printf("typeCast *int: %d\n", *c)
default:
fmt.Println("typeCast does not support this type")
}
}
| 89559dabd55abf6159741522aa7dd1cf9fc8e62b | [
"Go"
]
| 1 | Go | alexhokl/go-pointers | 0cb8db17dd54edcdc3136952f3dc88f937129350 | 0d6a19712262f157ec32c1d0d48d0718347b9e93 |
refs/heads/master | <file_sep>package View;
/**
* @author <NAME>
* @vesrion 1.15.0 8/6/2020
* @see java.lang.System
**/
import Model.Books;
import Model.Products;
import Model.DigitalItems;
import javax.swing.JOptionPane;
public class CheckoutScreen extends javax.swing.JFrame {
/**
* The CheckoutScreen is used to get the selected item from the MainScreen, and display the info for checkout.
*
* @param args (parameters is data that is selected and passed trough to the CheckoutScreen.
* @returns selected data as String.
*
**/
Products OrderedProduct;
Books OrderedBooks;
DigitalItems OrderedDigitalItems;
public CheckoutScreen(Products p, DigitalItems d, Books b) {
initComponents();
if (p != null) {
this.OrderedProduct = p;
this.CheckoutTextArea.setLineWrap(true);
this.CheckoutTextArea.setText("Product ID: " + p.getProductID() + "\n" + "Product name: " + p.getProductName() + "\n" + "Product price: R" + p.getProductPrice() + "\n" + "Product description: " + p.getProductDescription() + "\n" + "____________________________" + "\n");
this.CheckoutTextArea.setEditable(false);
}
if (b != null) {
this.OrderedBooks = b;
this.CheckoutTextArea.setLineWrap(true);
this.CheckoutTextArea.setText("Book ID: " + b.getBookID() + "\n" + "Book name: " + b.getBookName() + "\n" + "Book price: R" + b.getBookPrice() + "\n" + "Book description: " + b.getBookDiscription() + "\n" + "____________________________" + "\n");
this.CheckoutTextArea.setEditable(false);
}
if (d != null) {
this.OrderedDigitalItems = d;
this.CheckoutTextArea.setLineWrap(true);
this.CheckoutTextArea.setText("Digital Item ID: " + d.getDigitalItemID() + "\n" + "Digital Item name: " + d.getDigitalItemName() + "\n" + "Digital Item price: R" + d.getDigitalItemPrice() + "\n" + "Digital Item description: " + d.getDigitalItemDescription() + "\n" + "____________________________" + "\n");
this.CheckoutTextArea.setEditable(false);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
CheckoutTextArea = new javax.swing.JTextArea();
jPanel3 = new javax.swing.JPanel();
CheckoutConfirmCheckBox = new javax.swing.JCheckBox();
CheckoutButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jPanel1.setBackground(new java.awt.Color(0, 102, 255));
jPanel1.setLayout(null);
jLabel1.setFont(new java.awt.Font("Arial", 1, 48)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 0));
jLabel1.setText("Checkout:");
jPanel1.add(jLabel1);
jLabel1.setBounds(10, 10, 370, 60);
jPanel2.setBackground(new java.awt.Color(255, 255, 0));
jPanel2.setLayout(null);
CheckoutTextArea.setColumns(20);
CheckoutTextArea.setRows(5);
CheckoutTextArea.setToolTipText("Checkout product info.");
jScrollPane1.setViewportView(CheckoutTextArea);
jPanel2.add(jScrollPane1);
jScrollPane1.setBounds(30, 10, 1030, 290);
jPanel3.setBackground(new java.awt.Color(255, 204, 51));
jPanel3.setLayout(null);
CheckoutConfirmCheckBox.setBackground(new java.awt.Color(0, 153, 255));
CheckoutConfirmCheckBox.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
CheckoutConfirmCheckBox.setText("Confirm Checkout?");
CheckoutConfirmCheckBox.setToolTipText("Checkout confirm.");
jPanel3.add(CheckoutConfirmCheckBox);
CheckoutConfirmCheckBox.setBounds(470, 10, 170, 24);
CheckoutButton.setBackground(new java.awt.Color(0, 255, 255));
CheckoutButton.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
CheckoutButton.setForeground(new java.awt.Color(0, 51, 255));
CheckoutButton.setText("Checkout");
CheckoutButton.setToolTipText("Checkout button,");
CheckoutButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
CheckoutButtonMouseClicked(evt);
}
});
jPanel3.add(CheckoutButton);
CheckoutButton.setBounds(480, 50, 140, 30);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 1090, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 366, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void CheckoutButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CheckoutButtonMouseClicked
if (this.CheckoutConfirmCheckBox.isSelected()) {
DeliveryScreen scrn = new DeliveryScreen();
scrn.setVisible(true);
scrn.setLocationRelativeTo(null);
this.dispose();
} else {
JOptionPane.showMessageDialog(rootPane, "You have not confirmed checkout!");
}
}//GEN-LAST:event_CheckoutButtonMouseClicked
public boolean formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
System.out.println("Window opened");
return true;
}//GEN-LAST:event_formWindowOpened
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CheckoutScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CheckoutScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CheckoutScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CheckoutScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
CheckoutScreen scr = new CheckoutScreen(null, null, null);
scr.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton CheckoutButton;
private javax.swing.JCheckBox CheckoutConfirmCheckBox;
private javax.swing.JTextArea CheckoutTextArea;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
<file_sep>package Model;
/**
* This is the Books Model Object that has characteristics and stores all the data read from persistent storage.
* This Object is called and the data is extracted in the MainScreen.java
*
* @author <NAME>
* @version 1.15.0
* @see java.lang.System
**/
public class Books {
/**
* The book class has characteristics and a constructor used to assign those characteristics.
* @params args (The book characteristics. These are used to assign the values.)
* @returns (returns a constructor that holds data arrays)
**/
private String BookID;
private String BookName;
private int BookPrice;
private String BookDiscription;
// Creation of Book Attribute with characteristics
public Books(String BookID, String BookName, int BookPrice, String BookDiscription) {
this.BookID = BookID;
this.BookName = BookName;
this.BookPrice = BookPrice;
this.BookDiscription = BookDiscription;
}
public String getBookDiscription() {
return BookDiscription;
}
public void setBookDiscription(String BookDiscription) {
this.BookDiscription = BookDiscription;
}
public String getBookID() {
return BookID;
}
public void setBookID(String BookID) {
this.BookID = BookID;
}
public String getBookName() {
return BookName;
}
public void setBookName(String BookName) {
this.BookName = BookName;
}
public int getBookPrice() {
return BookPrice;
}
public void setBookPrice(int BookPrice) {
this.BookPrice = BookPrice;
}
@Override
public String toString() {
return "Books{" + "BookID=" + BookID + ", BookName=" + BookName + ", BookPrice=" + BookPrice + ", BookDiscription=" + BookDiscription + '}';
}
}
<file_sep># OnlineShop.java
It's a basic swing java project with a login and a product page with a checkout.
<file_sep>//<NAME>
/*
* 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 View;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
/**
*
* @author Klopp
*/
public class LogMeInForm extends javax.swing.JFrame {
/**
* Creates new form LogMeInForm
*/
public LogMeInForm() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
PasswordLabel = new javax.swing.JLabel();
UsernameLabel = new javax.swing.JLabel();
UsernameLogInText = new javax.swing.JTextField();
PasswordLogInText = new javax.swing.JPasswordField();
LogInCancelButton = new javax.swing.JButton();
LogInConfrimButton = new javax.swing.JButton();
CreateAccLabelClickable = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(52, 86, 239));
jPanel1.setLayout(null);
jLabel2.setFont(new java.awt.Font("Arial", 0, 48)); // NOI18N
jLabel2.setText("LogMeIn:");
jPanel1.add(jLabel2);
jLabel2.setBounds(0, 0, 230, 80);
jPanel2.setBackground(new java.awt.Color(255, 255, 102));
jPanel2.setLayout(null);
PasswordLabel.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
PasswordLabel.setText("Password:");
jPanel2.add(PasswordLabel);
PasswordLabel.setBounds(80, 150, 140, 29);
UsernameLabel.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
UsernameLabel.setText("Username:");
jPanel2.add(UsernameLabel);
UsernameLabel.setBounds(70, 80, 140, 29);
UsernameLogInText.setToolTipText("Please enter you Username.");
UsernameLogInText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
UsernameLogInTextActionPerformed(evt);
}
});
UsernameLogInText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
UsernameLogInTextKeyPressed(evt);
}
});
jPanel2.add(UsernameLogInText);
UsernameLogInText.setBounds(220, 80, 310, 30);
PasswordLogInText.setToolTipText("Please enter you Password.");
PasswordLogInText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
PasswordLogInTextKeyPressed(evt);
}
});
jPanel2.add(PasswordLogInText);
PasswordLogInText.setBounds(220, 150, 310, 30);
LogInCancelButton.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
LogInCancelButton.setText("Cancel");
LogInCancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LogInCancelButtonActionPerformed(evt);
}
});
jPanel2.add(LogInCancelButton);
LogInCancelButton.setBounds(220, 220, 100, 40);
LogInConfrimButton.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
LogInConfrimButton.setText("Log in");
LogInConfrimButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
LogInConfrimButtonMouseClicked(evt);
}
});
LogInConfrimButton.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
LogInConfrimButtonKeyPressed(evt);
}
});
jPanel2.add(LogInConfrimButton);
LogInConfrimButton.setBounds(430, 220, 100, 40);
CreateAccLabelClickable.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
CreateAccLabelClickable.setText("I don't have an account?");
CreateAccLabelClickable.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
CreateAccLabelClickable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
CreateAccLabelClickableMouseClicked(evt);
}
});
jPanel2.add(CreateAccLabelClickable);
CreateAccLabelClickable.setBounds(280, 290, 180, 20);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 673, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void UsernameLogInTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UsernameLogInTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_UsernameLogInTextActionPerformed
private void LogInCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogInCancelButtonActionPerformed
this.dispose();
}//GEN-LAST:event_LogInCancelButtonActionPerformed
private void LogInConfrimButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_LogInConfrimButtonMouseClicked
File file = new File("LoginDetails.txt");
boolean UsernameFound = false;
boolean PasswordFound = false;
String username = this.UsernameLogInText.getText();
String password = new String(this.PasswordLogInText.getPassword());
String tempUsername;
String tempPassword;
String Line;
if (this.UsernameLogInText.getText().isEmpty() == true || this.PasswordLogInText.getPassword().length == 0) {
JOptionPane.showMessageDialog(rootPane, "Please fill in you Username/Password in the fields!");
this.UsernameLogInText.setText("");
this.PasswordLogInText.setText("");
return;
}
try {
Scanner scFile = new Scanner(file);
while (scFile.hasNext()) {
Line = scFile.nextLine();
Scanner inLine = new Scanner(Line).useDelimiter("#");
tempUsername = inLine.next();
tempPassword = inLine.next();
if (username.compareTo(tempUsername) == 0) {
UsernameFound = true;
}
if (password.compareTo(tempPassword) == 0) {
PasswordFound = true;
}
}
if (!UsernameFound && !PasswordFound) {
JOptionPane.showMessageDialog(rootPane, "Username And Password is invalid!");
this.UsernameLogInText.setText("");
this.PasswordLogInText.setText("");
return;
}
if (!UsernameFound) {
JOptionPane.showMessageDialog(rootPane, "Username is invalid!");
this.UsernameLogInText.setText("");
return;
}
if (!PasswordFound) {
JOptionPane.showMessageDialog(rootPane, "Password is invalid!");
this.PasswordLogInText.setText("");
return;
}
if (UsernameFound && PasswordFound) {
JOptionPane.showMessageDialog(rootPane, "You have succesfully logged in!");
MainScreen Screen = new MainScreen();
Screen.setVisible(true);
Screen.setLocationRelativeTo(null);
this.dispose();
}
} catch (FileNotFoundException e) {
System.out.println("File not found!!!" + e);
}
}//GEN-LAST:event_LogInConfrimButtonMouseClicked
private void CreateAccLabelClickableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CreateAccLabelClickableMouseClicked
CreateAccountLogMeIn Acc = new CreateAccountLogMeIn();
Acc.setVisible(true);
Acc.setLocationRelativeTo(null);
this.dispose();
}//GEN-LAST:event_CreateAccLabelClickableMouseClicked
private void LogInConfrimButtonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LogInConfrimButtonKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
File file = new File("LoginDetails.txt");
boolean UsernameFound = false;
boolean PasswordFound = false;
String username = this.UsernameLogInText.getText();
String password = new String(this.PasswordLogInText.getPassword());
String tempUsername;
String tempPassword;
String Line;
if (this.UsernameLogInText.getText().isEmpty() == true || this.PasswordLogInText.getPassword().length == 0) {
JOptionPane.showMessageDialog(rootPane, "Please fill in you Username/Password in the fields!");
this.UsernameLogInText.setText("");
this.PasswordLogInText.setText("");
return;
}
try {
Scanner scFile = new Scanner(file);
while (scFile.hasNext()) {
Line = scFile.nextLine();
Scanner inLine = new Scanner(Line).useDelimiter("#");
tempUsername = inLine.next();
tempPassword = inLine.next();
if (username.compareTo(tempUsername) == 0) {
UsernameFound = true;
}
if (password.compareTo(tempPassword) == 0) {
PasswordFound = true;
}
}
if (!UsernameFound) {
JOptionPane.showMessageDialog(rootPane, "Username is invalid!");
this.UsernameLogInText.setText("");
return;
}
if (!PasswordFound) {
JOptionPane.showMessageDialog(rootPane, "Password is invalid!");
this.PasswordLogInText.setText("");
return;
}
if (UsernameFound && PasswordFound) {
JOptionPane.showMessageDialog(rootPane, "You have succesfully logged in!");
MainScreen Screen = new MainScreen();
Screen.setVisible(true);
Screen.setLocationRelativeTo(null);
this.dispose();
}
} catch (FileNotFoundException e) {
System.out.println("File not found!!!" + e);
}
}
if (evt.getKeyCode() == KeyEvent.VK_F1) {
JOptionPane.showMessageDialog(rootPane, "• This is the Login screen.\n• Please enter you Username and Password.\n• If you don't have an account please create one.");
}
}//GEN-LAST:event_LogInConfrimButtonKeyPressed
private void PasswordLogInTextKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_PasswordLogInTextKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
File file = new File("LoginDetails.txt");
boolean UsernameFound = false;
boolean PasswordFound = false;
String username = this.UsernameLogInText.getText();
String password = new String(this.PasswordLogInText.getPassword());
String tempUsername;
String tempPassword;
String Line;
if (this.UsernameLogInText.getText().isEmpty() == true || this.PasswordLogInText.getPassword().length == 0) {
JOptionPane.showMessageDialog(rootPane, "Please fill in you Username/Password in the fields!");
this.UsernameLogInText.setText("");
this.PasswordLogInText.setText("");
return;
}
try {
Scanner scFile = new Scanner(file);
while (scFile.hasNext()) {
Line = scFile.nextLine();
Scanner inLine = new Scanner(Line).useDelimiter("#");
tempUsername = inLine.next();
tempPassword = inLine.next();
if (username.compareTo(tempUsername) == 0) {
UsernameFound = true;
}
if (password.compareTo(tempPassword) == 0) {
PasswordFound = true;
}
}
if (!UsernameFound) {
JOptionPane.showMessageDialog(rootPane, "Username is invalid!");
this.UsernameLogInText.setText("");
return;
}
if (!PasswordFound) {
JOptionPane.showMessageDialog(rootPane, "Password is invalid!");
this.PasswordLogInText.setText("");
return;
}
if (UsernameFound && PasswordFound) {
JOptionPane.showMessageDialog(rootPane, "You have succesfully logged in!");
MainScreen Screen = new MainScreen();
Screen.setVisible(true);
Screen.setLocationRelativeTo(null);
this.dispose();
}
} catch (FileNotFoundException e) {
System.out.println("File not found!!!" + e);
}
}
if (evt.getKeyCode() == KeyEvent.VK_F1) {
JOptionPane.showMessageDialog(rootPane, "• This is the Login screen.\n• Please enter you Username and Password.\n• If you don't have an account please create one.");
}
}//GEN-LAST:event_PasswordLogInTextKeyPressed
private void UsernameLogInTextKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_UsernameLogInTextKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_F1) {
JOptionPane.showMessageDialog(rootPane, "• This is the Login screen.\n• Please enter you Username and Password.\n• If you don't have an account please create one.");
}
}//GEN-LAST:event_UsernameLogInTextKeyPressed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LogMeInForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LogMeInForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LogMeInForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LogMeInForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
LogMeInForm MyLogMeInForm = new LogMeInForm();
MyLogMeInForm.setVisible(true);
MyLogMeInForm.setLocationRelativeTo(null);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel CreateAccLabelClickable;
private javax.swing.JButton LogInCancelButton;
private javax.swing.JButton LogInConfrimButton;
private javax.swing.JLabel PasswordLabel;
private javax.swing.JPasswordField PasswordLogInText;
private javax.swing.JLabel UsernameLabel;
private javax.swing.JTextField UsernameLogInText;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
// End of variables declaration//GEN-END:variables
}
<file_sep>package Controller;
import Model.Products;
import Model.Books;
import Model.DigitalItems;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
/**
* The Shopping class is the controller class of the project. Shopping class is
* used to retrieve data from persistent storage (.txt) and assign that data to
* the objects in the model package.
*
* @author <NAME>
* @version 1.15.0 8/12/2020
* @see java.lang.System
*
*/
public class Shopping {
/**
* Shopping class uses ArrayList<> to make an Array to allow storage of
* scanned data. This data is added using Arr.add and adding that data
* through params to object characteristics using constructor.
*
* @param args Constructor in object classes.
* @return Data from persistent storage, and assigns to object
* characteristics.
*
*
*/
int counter = 0;
ArrayList<Products> ProductArr = new ArrayList<>();
// ArrayList created too store data read by scanner from .txt file
public ArrayList<Products> ShoppingProducts() {
// Try Catch used to catch potential errors like Exceptions
try {
File scFile = new File("Product list.txt");
String ProductID;
String ProductName;
String ProductDescription;
int ProductPrice;
String Line = "";
String PrintLine;
// Scanner created to scan .txt file
Scanner scLine = new Scanner(scFile);
while (scLine.hasNext()) {
Line = scLine.nextLine();
Scanner InLine = new Scanner(Line).useDelimiter("#");
ProductID = InLine.next();
ProductName = InLine.next();
ProductPrice = Integer.parseInt(InLine.next());
ProductDescription = InLine.next();
ProductArr.add(new Products(ProductID, ProductName, ProductPrice, ProductDescription)); // Scanned items are added to the (Product)attribute characteristics
counter++;
}
} catch (Exception e) {
System.out.println("Error" + e);
}
return ProductArr;
}
ArrayList<Books> BookArr = new ArrayList<>();
public ArrayList<Books> ShoppingBooks() {
try {
File scFile = new File("BookList.txt");
String BookID;
String BookName;
String BookDescription;
int BookPrice;
String Line = "";
String PrintLine;
Scanner scLine = new Scanner(scFile);
while (scLine.hasNext()) {
Line = scLine.nextLine();
Scanner InLine = new Scanner(Line).useDelimiter("#");
BookID = InLine.next();
BookName = InLine.next();
BookPrice = Integer.parseInt(InLine.next());
BookDescription = InLine.next();
BookArr.add(new Books(BookID, BookName, BookPrice, BookDescription));
counter++;
}
} catch (Exception e) {
System.out.println("Error" + e);
}
return BookArr;
}
ArrayList<DigitalItems> DigitalItemsArr = new ArrayList<>();
public ArrayList<DigitalItems> ShoppingDigitalItems() {
try {
File scFile = new File("DigitalItems.txt");
String DigitalItemID;
String DigitalItemName;
String DigitalItemDescription;
int DigitalItemPrice;
String Line = "";
String PrintLine;
Scanner scLine = new Scanner(scFile);
while (scLine.hasNext()) {
Line = scLine.nextLine();
Scanner InLine = new Scanner(Line).useDelimiter("#");
DigitalItemID = InLine.next();
DigitalItemName = InLine.next();
DigitalItemPrice = Integer.parseInt(InLine.next());
DigitalItemDescription = InLine.next();
DigitalItemsArr.add(new DigitalItems(DigitalItemID, DigitalItemName, DigitalItemPrice, DigitalItemDescription));
counter++;
}
} catch (Exception e) {
System.out.println("Error" + e);
}
return DigitalItemsArr;
}
@Override
public String toString() {
String temp = "";
for (int i = 0; i < counter; i++) {
temp = temp + ProductArr.get(i) + " ";
}
return temp;
}
}
| d5308f25735fd1624f4c87a4475bf075339b1148 | [
"Markdown",
"Java"
]
| 5 | Java | CanadianMapleFarmer/OnlineShop.java | ba3e338e7a4d1041b7b500f5d12f45447c044b7c | 17582a40a8b7afc13ab5253ff46308f38748ba4c |
refs/heads/master | <file_sep>const pronoun = ['the','our'];
const adj = ['great', 'big' ];
const noun = ['jogger','racoon'];
const extend = [".com", ".us"]
for(let x of pronoun){
for(let j of adj){
for(let k of noun){
for(let h of extend){
console.log(x+j+k+h )
}
}
}
}
| 58cf6767eb0a23889b9c00f4c0478119125da133 | [
"JavaScript"
]
| 1 | JavaScript | michelle-sepulveda-lavin/domain-generator | 92472ad7f0960129b819046588b1aced595f2d5a | 742fde280c0f0d0fc190ad7bcccba6dbbc9b97b6 |
refs/heads/main | <repo_name>tonytw1/grid<file_sep>/s3watcher/scripts/properties.js
const fs = require('fs');
const ini = require('ini');
const parseHocon = require('hocon-parser');
function load(app) {
const propertiesFile = `/etc/gu/${app}.properties`;
const configFile = `/etc/grid/${app}.conf`;
if (fs.existsSync(configFile)) {
return {
type: "hocon",
data: parseHocon(fs.readFileSync(configFile).toString())
};
}
if (fs.existsSync(propertiesFile)) {
return {
type: "properties",
data: ini.parse(fs.readFileSync(propertiesFile).toString())
};
}
console.error(`Neither ${configFile} nor ${propertiesFile} exist`);
return {};
}
function get(config, field) {
if (config.type === "properties") {
return config.data[field];
} else if (config.type === "hocon") {
const fieldElements = field.split(".")
function getField(obj, fields) {
if (fields.length === 0) return obj;
getField(obj[fields[0]], fields.slice(1))
}
return getField(field.data, fieldElements);
} else {
console.error("Unknown config type")
return undefined;
}
}
module.exports = {
load: load,
get: get
};
<file_sep>/kahuna/public/js/util/crop.js
import angular from 'angular';
const CROP_TYPE_STORAGE_KEY = 'cropType';
const CUSTOM_CROP_STORAGE_KEY = 'customCrop';
// `ratioString` is sent to the server, being `undefined` for `freeform` is expected 🙈
const landscape = {key: 'landscape', ratio: 5 / 3, ratioString: '5:3'};
const portrait = {key: 'portrait', ratio: 4 / 5, ratioString: '4:5'};
const video = {key: 'video', ratio: 16 / 9, ratioString: '16:9'};
const square = {key: 'square', ratio: 1, ratioString: '1:1'};
const freeform = {key: 'freeform', ratio: null};
const customCrop = (label, xRatio, yRatio) => {
return { key:label, ratio: xRatio / yRatio, ratioString: `${xRatio}:${yRatio}`};
};
const cropOptions = [landscape, portrait, video, square, freeform];
export const cropUtil = angular.module('util.crop', ['util.storage']);
cropUtil.constant('landscape', landscape);
cropUtil.constant('portrait', portrait);
cropUtil.constant('video', video);
cropUtil.constant('square', square);
cropUtil.constant('freeform', freeform);
cropUtil.constant('cropOptions', cropOptions);
cropUtil.constant('defaultCrop', landscape);
cropUtil.factory('cropSettings', ['storage', function(storage) {
function getCropOptions() {
const customCrop = storage.getJs(CUSTOM_CROP_STORAGE_KEY, true);
return customCrop ? cropOptions.concat(customCrop) : cropOptions;
}
const isValidCropType = cropType => getCropOptions().some(_ => _.key === cropType);
const isValidRatio = ratio => {
const [label, x, y] = ratio.split(',');
return label && !isNaN(x) && !isNaN(y);
};
const parseRatio = ratio => {
// example ratio 'longcrop,1,5'
if (isValidRatio(ratio)) {
const [label, x, y] = ratio.split(',');
return {
label,
x: parseInt(x, 10),
y: parseInt(y, 10)
};
}
};
const setCropType = (cropType) => {
if (isValidCropType(cropType)) {
storage.setJs(CROP_TYPE_STORAGE_KEY, cropType, true);
} else {
storage.clearJs(CROP_TYPE_STORAGE_KEY);
}
};
const setCustomCrop = customRatio => {
const parsedRatio = parseRatio(customRatio);
if (parsedRatio) {
storage.setJs(CUSTOM_CROP_STORAGE_KEY, customCrop(parsedRatio.label, parsedRatio.x, parsedRatio.y), true);
} else {
storage.clearJs(CUSTOM_CROP_STORAGE_KEY);
}
};
function set({cropType, customRatio}) {
// set customRatio first in case cropType relies on a custom crop
if (customRatio) {
setCustomCrop(customRatio);
}
if (cropType) {
setCropType(cropType);
}
}
function getCropType() {
const cropType = storage.getJs(CROP_TYPE_STORAGE_KEY, true);
if (isValidCropType(cropType)) {
return cropType;
}
}
return { set, getCropType, getCropOptions };
}]);
cropUtil.filter('asCropType', function() {
return ratioString => {
const cropSpec = cropOptions.find(_ => _.ratioString === ratioString) || freeform;
return cropSpec.key;
};
});
| c42e91d9c413706164dfa0c5f95fff6a6b1c4530 | [
"JavaScript"
]
| 2 | JavaScript | tonytw1/grid | 04444f334ea82316cd892bc5ef23554bc6a25cd3 | b028a92f8a91105c1c290855122b6c2cc83c1a73 |
refs/heads/master | <file_sep>#include "olc6502.h"
olc6502::olc6502() {
using a = olc6502;
}
olc6502::~olc6502() {
}
// Calling the bus's read method
uint8_t olc6502::read(uint16_t a) {
return bus->read(a, false);
}
// Calling the bus's write method
void olc6502::write(uint16_t a, uint8_t d) {
bus->write(a, d);
}
void olc6502::clock() {
if ()
}
<file_sep>#pragma once
#include <cstdint>
#include <array>
#include "olc6502.h"
class Bus {
public:
Bus() {
}
~Bus() {
}
/* Devices connected to the bus */
// The CPU
olc6502 cpu;
// "Fake" RAM
std::array<uint8_t, 64 * 1024> ram;
/* Read and Write from CPU: */
// Takes a 16-bit address (to write to) and 8-bit data (to write) as arguments
void write(uint16_t address, uint8_t data);
// Why is the return value an 8-bit integer?
// Takes a 16-bit address to read from
// The second flag can be ignored
uint8_t read(uint16_t address, bool bReadOnly = false);
}<file_sep>#include "bus.h"
// Default constructor
Bus::Bus() {
// Clears RAM contents when initialized
for(auto &i : ram) i = 0x00;
// Connect CPU to bus
cpu.connectBus(this);
}
// Kamehameha
Bus::~Bus() {
}
// Writing to memory
// Using a safeguard to make sure we don't go out of bounds
void Bus::write(uint16_t address, uint8_t data) {
if (address >= 0x0000 && address <= 0xFFFF)
ram[addr] = data;
}
// Reading from an address
uint8_t Bus::read(uint16_t address, bool bReadOnly) {
if (address >= 0x0000 && address <= 0xFFFF)
return ram[addr];
// If outside range
return 0x00;
}
| 8a27afa1919b141a0bb3b22efe1650a107e04670 | [
"C++"
]
| 3 | C++ | nehalparimi/nes-emulator | 0a2a727e7a0ec4db7c6c0561fbe1c4ecd7e6610c | ce8974431612854507f771e4ab3106ac14d61e5d |
refs/heads/master | <repo_name>Martijho/alias_scripts<file_sep>/setup.py
from pathlib import Path
LOCAL_BASHRC = '.bashrc_autogen_alias'
def to_alias_line(name, script):
return f'alias {name}=\"python {script}\"'
def get_alias_name(script):
lines = Path(script).open('r').read().split('\n')
override = None
alias_name = None
for l in lines:
if l.startswith('ALIAS_NAME = '):
alias_name = l.replace('ALIAS_NAME = ', '').strip()
if l.startswith('ALIAS_OVERRIDE = '):
override = l.replace('ALIAS_OVERRIDE = ', '').strip()
if alias_name is None:
raise ValueError(f'{script} does not have ALIAS_NAME')
return alias_name, override
if __name__ == '__main__':
scripts = Path('scripts').glob('*.py')
root = Path.cwd()
lines = []
for script in scripts:
script = root / script
name, override = get_alias_name(script)
print(f'\t-> Adding {script.name} as {name}')
if override is not None:
print(f'\t\t -> over riding alias with {override}')
lines.append(override.replace('<PATH>', str(script)).replace('\'', ''))
else:
lines.append(to_alias_line(name, script))
Path(LOCAL_BASHRC).open('w').write('\n'.join(lines))
(Path.home() / '.bashrc_alias').open('a').write(f'\n# Autogen alias\nsource {root / LOCAL_BASHRC}\n')<file_sep>/scripts/load_container_in_interactive_shell.py
from bbox import AnnotationContainer
import cv2
import numpy as np
import argparse
from pathlib import Path
ALIAS_NAME = 'contload'
ALIAS_OVERRIDE = 'alias "contload"="ipython -i <PATH>"'
parser = argparse.ArgumentParser(description='Load container interactively')
parser.add_argument('container', metavar='FILE', type=str, help='Container')
args = parser.parse_args()
if not Path(args.container).exists():
print('Container does not exists')
quit()
print('Imported:')
print('\t bbox.AnnotationContainer')
print('\t cv2')
print('\t numpy')
print('\t pathlib.Path')
print()
print('Loaded', args.container, 'as \"container\"')
print()
container = AnnotationContainer.from_file(args.container)<file_sep>/scripts/select_labels_from_container.py
import sys
from pathlib import Path
import argparse
from bbox import AnnotationContainer
ALIAS_NAME = 'contlabelselect'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Selects probided labels from container')
parser.add_argument('container', help='Container to select labels from')
parser.add_argument('-l', '--labels', type=str, nargs='*',
help='label(s) to select from container')
parser.add_argument('-o', '--out_container', type=str,
help='Output path to write trimmed container to. ' +
'If not provided, default filename will be ' +
'\'output_container_label1_label2_...bbox\'')
parser.add_argument('-r', '--remove_empty', action='store_true', help='Set to remove entries with no instances in trimmed container')
parser.add_argument('-c', '--clean', action='store_true', help='Remove all entries with invalid path to an image')
parser.add_argument('-f', '--file', type=str, help='Names or labelmap file. ' +
'Read as darknets names file if suffix == .txt, ' +
'read as labelmap if suffix == .pbtxt. This option ' +
'overwrites labels provided as positional arguments')
args = parser.parse_args()
if args.file is not None:
filename = Path(args.file)
if filename.suffix == '.txt':
labels = [l.strip() for l in filename.open('r').readlines() if l.strip() != '']
elif filename.suffix == '.pbtxt':
raise NotImplementedError('Parsing labelmap.pbtx files is not implemented yet')
else:
raise ValueError(f'{args.file} not recognized as valid label file')
else:
assert args.labels is not None, 'Some labels must be provided if no labelmap is given with -f'
labels = args.labels
if args.container == args.out_container:
if input('Are you sure you want to overwrite container? (y/n): ') != 'y':
quit()
print('Selected labels:')
print(labels)
print('Remove empty entries from trimmed container:', args.remove_empty)
print('Clean container of entries with non-valid paths to images:', args.clean)
if args.out_container is None:
out = 'trimmed_container_{}.bbox'.format('_'.join(args.labels))
else:
out = args.out_container
container = AnnotationContainer.from_file(args.container)
container.with_selected_labels(labels, in_place=True)
if args.remove_empty:
for e in list(container.entries.keys()):
if len(container.entries[e]) == 0:
del container.entries[e]
if args.clean:
for e in list(container.entries.keys()):
if container.entries[e].get_image_full_path() is None or not Path(container.entries[e].get_image_full_path()).exists():
del container.entries[e]
container.summary()
container.to_file(out)
<file_sep>/scripts/create_label_heatmap.py
from pathlib import Path
import argparse
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from bbox import AnnotationContainer
ALIAS_NAME = 'contheatmap'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Plot heatmap for labels in dataset')
parser.add_argument('container', help='Container to select labels from')
parser.add_argument('labels', type=str, nargs='*', help='label(s) to select from container')
parser.add_argument('-s', '--store', action='store_true', help='Store heatmaps')
args = parser.parse_args()
container = AnnotationContainer.from_file(args.container)
analytic = container.analytic()
heatmaps = {l: analytic.get_label_heatmap(l) for l in tqdm(args.labels)}
for label, hm in heatmaps.items():
plt.title('Label: '+label)
plt.imshow(hm)
plt.show()
if args.store:
np.save(f'{Path(args.container).stem}_{label}_heatmap', hm)
<file_sep>/scripts/show_annotation_container_summary.py
import sys
from pathlib import Path
from bbox import AnnotationContainer
ALIAS_NAME = 'contsum'
if __name__ == '__main__':
if len(sys.argv) == 1:
print('use with arguments <full path to container> or $PWD <container>')
quit()
container = sys.argv[1]
suffix = container.split('.')[-1]
if suffix != 'bbox' and suffix != 'json':
if len(sys.argv) < 2:
print('if not using 2 arguments, first must be absolute path to container')
quit()
container = Path(container) / sys.argv[2]
AnnotationContainer.from_file(container).summary()
<file_sep>/scripts/merge_annotation_contianers.py
import argparse
from bbox import AnnotationContainer
import gc
ALIAS_NAME = 'contmerge'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Merge two or more annotationcontainers')
parser.add_argument('containers', metavar='FILE', type=str, nargs='*',
help='File(s) to merge')
parser.add_argument('-n', '--nms', type=float,
help='If specified, non-maximum suppression is applied with ' +
'the given IoU threshold whenever there same entry is mentioned in both containers.')
parser.add_argument('-o', '--output', type=str, help='Output filename. If not set, user will be ' +
'prompted by request for output filename during runtime.')
args = parser.parse_args()
if args.output is None:
output_file_name = input('Write file to: ')
else:
output_file_name = args.output
cnt = None
for to_merge in args.containers:
print(f'Merging container {to_merge} ...'.ljust(70), end='')
try:
new_cont = AnnotationContainer.from_file(to_merge)
if cnt is None:
cnt = new_cont
else:
cnt.merge(new_cont, merge_instance_iou=args.nms, destructively=True)
del new_cont
gc.collect()
except Exception as e:
print('\tFailed!')
print(e)
continue
print('\tOK')
cnt.to_file(output_file_name)
<file_sep>/scripts/predict.py
from bbox import AnnotationContainer, AnnotationInstance, AnnotationEntry, BBox, DatasetSourceProvider, ImageSize
from bbox.contrib.detection.darknet import DarknetObjectDetector
from bbox.contrib.detection.tensorflow import TensorflowObjectDetector
from pathlib import Path
import argparse
import numpy as np
from tqdm import tqdm
import cv2
from collections import defaultdict
ALIAS_NAME = 'predict'
def _get_detector_func(model_root):
files = list(Path(model_root).glob('*'))
suffix = [f.suffix for f in files]
# Darknet
if '.cfg' in suffix and '.weights' in suffix and '.data' in suffix:
return dn_detector
if '.pbtxt' in suffix and '.pb' in suffix:
return tf_detector
if '.prototxt' in suffix and '.caffemodel' in suffix:
return caffe_detector
raise ValueError('No model type recognized')
def caffe_detector(model_root, threshold=.01, box_blending=False, anchors=None):
from bbox.contrib.detection.caffe import CaffeYoloObjectDetector
model_root = Path(model_root)
model_name = model_root.name
prototxt = model_root / f'{model_name}.prototxt'
caffemodel = model_root / f'{model_name}.caffemodel'
if anchors is None:
anchors = np.array([0.72, 1.67, 1.86, 4.27, 2.83, 8.66, 5.53, 10.47, 10.83, 12.45]).reshape((5, 2))
if type(anchors) == list:
anchors = np.array(anchors).reshape(len(anchors)//2, 2)
names = [l for l in (model_root / 'names.txt').open('r').read().split('\n') if l != '']
cd = CaffeYoloObjectDetector(
prototxt,
caffemodel,
anchors=anchors,
labelmap=names,
detection_score_threshold=threshold,
nms_iou_threshold=.0 if box_blending else 0.45,
detector_output_format='relative'
)
return cd
def dn_detector(model_root, threshold=.01, box_blending=False):
darknet_path = Path('/home/martin/repos/darknet_mirror')
model_root = Path(model_root)
model_name = model_root.name
data = model_root / f'{model_name}.data'
cfg = model_root / f'{model_name}.cfg'
weights = model_root / f'{model_name}.weights'
dnd = DarknetObjectDetector(
darknet_path,
cfg,
weights,
data,
detection_score_threshold=threshold,
nms_iou_threshold=.0 if box_blending else .45
)
return dnd
def tf_detector(model_root, threshold=.01, box_blending=False):
assert not box_blending, 'TensorflowObjectDetector does not support blending'
model_root = Path(model_root)
labelmap = model_root / 'label_map.pbtxt'
model = model_root / 'frozen_inference_graph.pb'
tfd = TensorflowObjectDetector(
model,
labelmap,
detection_score_threshold=threshold
)
return tfd
def _blend_boxes(pred):
def blend_boxes(group, label, coordinate_mode):
scores = np.array([i.score for i in group])
xmins = np.array([i.xmin for i in group])
ymins = np.array([i.ymin for i in group])
xmaxs = np.array([i.xmax for i in group])
ymaxs = np.array([i.ymax for i in group])
xmin = np.sum(xmins * scores) / np.sum(scores)
ymin = np.sum(ymins * scores) / np.sum(scores)
xmax = np.sum(xmaxs * scores) / np.sum(scores)
ymax = np.sum(ymaxs * scores) / np.sum(scores)
score = scores.max() # np.sum(scores * scores) / np.sum(scores)
return AnnotationInstance(bbox=BBox(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax,
label=label, score=score,
coordinate_mode=coordinate_mode))
for pred_entry in tqdm(pred, desc='blending'):
predictions = [i for i in pred_entry]
iou_map = pred_entry.compute_iou(pred_entry)
iou_map = {(a, b): val for (a, b), val in iou_map.items()
if a != b and val >= .45 and a.label == b.label}
predictions = list(sorted(predictions, key=lambda x: -x.score))
iou_groups = {a: [b for (a_, b), _ in iou_map.items() if a == a_] for a in predictions}
used = set()
output = []
for a, others in iou_groups.items():
if len(others) >= 1:
group = set(others)
group.add(a)
group = group.difference(used)
if len(group) == 0:
continue
used = used.union(group)
output.append(blend_boxes(group, a.label, a.bbox.coordinate_mode))
else:
output.append(a)
pred_entry.instances = []
for i in output:
pred_entry.add_instance(i)
return pred
def load_preview_image(path):
buffer = open(path, 'rb').read()
img = np.frombuffer(buffer, dtype=np.float16).astype(np.float32)
img = img.reshape((3, 480, 640)).transpose((1, 2, 0))
return (img*255).astype(np.uint8)
def detect_on_preview_dir(preview_data, detector):
dsp = DatasetSourceProvider()
dsp.add_source(preview_data, 'predicted')
container = AnnotationContainer(dataset_source_provider=dsp)
for image_path in Path(preview_data).glob('preview*'):
image = load_preview_image(str(image_path))
det = detector.detect_image(image)
e = AnnotationEntry(image_path.name, ImageSize.from_image(image), 'predicted', instances=det)
container.add_entry(e)
return container
def predict_on_video(video_file, detector):
def frame_generator():
vidcap = cv2.VideoCapture(str(video_file))
frame = 0
while True:
success, image = vidcap.read()
if success: # and frame < 500:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
yield frame, image
frame += 1
else:
break
name = Path(video_file).stem
colors = defaultdict(lambda: np.random.randint(0, 255, 3))
cv2.namedWindow(name, cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty(name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
for frame_nr, image in frame_generator():
for i in detector.detect_image(image):
image = i.bbox.overlaid_on_image(image, colors[i.label])
cv2.imshow(name, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))
if cv2.waitKey(10) == ord('q'):
break
def main(args):
thresh = .01 if args.box_blending else args.threshold
get_detector = _get_detector_func(args.model)
if get_detector == caffe_detector:
detector = get_detector(args.model, thresh, box_blending=args.box_blending, anchors=args.anchors)
else:
detector = _get_detector_func(args.model)(args.model, thresh, box_blending=args.box_blending)
with detector:
if args.container:
gt = AnnotationContainer.from_file(args.container)
pred = detector.detect_on_annotation_container(gt) # .with_selected_labels(['person'])
if args.box_blending and type(detector) == DarknetObjectDetector:
pred = _blend_boxes(pred)
pred.filter_all_instances_by_threshold(args.threshold, in_place=True)
pred.as_evaluated_against(gt).summary()
elif args.images:
pred = detector.detect_on_image_folder(args.images, dataset_name='predicted')
if args.box_blending and type(detector) == DarknetObjectDetector:
pred = _blend_boxes(pred)
pred.filter_all_instances_by_threshold(args.threshold, in_place=True)
elif args.preview:
pred = detect_on_preview_dir(args.preview, detector)
if args.box_blending and type(detector) == DarknetObjectDetector:
pred = _blend_boxes(pred)
pred.filter_all_instances_by_threshold(args.threshold, in_place=True)
elif args.video:
predict_on_video(args.video, detector)
if args.output:
pred.to_file(args.output)
def get_args():
parser = argparse.ArgumentParser(description='Predict on data with a model')
parser.add_argument('model', type=str, help='Model')
parser.add_argument('-o', '--output', type=str, help='Output container path')
parser.add_argument('-c', '--container', type=str, help='Predict on AnnotationContainer')
parser.add_argument('-i', '--images', type=str, help='Predict on images in directory')
parser.add_argument('-t', '--threshold', default=0.01, type=float, help='Confidence threshold')
parser.add_argument('-p', '--preview', type=str, help='Predict on directory of raw preview images')
parser.add_argument('-v', '--video', type=str, help='Predict on video file. Overlay results live')
parser.add_argument(
'-b', '--box_blending',
action='store_true',
help='Instead of NMS to select from overlapping boxes, use a weighted mean of overlaps'
)
parser.add_argument(
'-a', '--anchors',
type=float,
nargs='*',
default=[0.72, 1.67, 1.86, 4.27, 2.83, 8.66, 5.53, 10.47, 10.83, 12.45],
help='Anchors to use with yolo detection (caffe). '
'Defaults to [0.72, 1.67, 1.86, 4.27, 2.83, 8.66, 5.53, 10.47, 10.83, 12.45]'
)
args = parser.parse_args()
arg_data = [1 for d in [args.container, args.images, args.preview, args.video] if d is not None]
if sum(arg_data) != 1:
raise ValueError('One (and only one) data set to infer on has to be defined')
if args.output:
assert Path(args.output).parent.exists(), 'Path to output directory does not exists'
if Path(args.output).exists():
if input('Output path exists. Overwrite? [y/n]: ') != 'y':
quit()
return args
if __name__ == '__main__':
main(get_args())
<file_sep>/README.md
# Alias scripts
This repo is intended as a quality of life improvement for those that use BBox-annotationcontainers regularly.
### Setup
To setup, run
```bash
python setup.py
```
from the repo root-directory.
This script will create a `.bashrc_autogen_alias` file which will be sourced from `~/.bashrc_alias`.
Source either that file or `.bashrc_autoget_alias` from your `.bashrc`
### Scripts and their alias
#### `contpath`
Replaces the image directory path stored in a container. Run with `-a` to set a path for all (dataset, subset)
or `-i` to run interactively. You will be prompted with each (dataset, subset) and must provide a path for each.
Tip: `-a` allows you to use autocomplete
#### `contsum`
Outputs the container summary for a container.
#### `contthresh`
Filters annotations in a container by confidence threshold.
#### `contmerge`
Merges two or more containers. Run with `-n` to apply non-maximum suppression on each entry after merging
#### `predict`
Predicts with a model. Input can be a container (`-c <path>`), directory of images (`-i <path>`), video-file (`-i <path>`),
or a directory of preview-images from autozoom feedback (`-p <path>`). If input is a video file, the predictions will be shown
overlaid on the video. The option `-b` runs box-blending instead of NMS on the inferences, but implementation performes worse so NMS
is recommended.
#### `cont2tfrecord`
Takes a container and labelmap and outputs the annotations as a tf-record. Make sure that all images the container
reference is found by running `contsum`.
#### `cont2video`
Applies a container to all its images and writes it as a video.
All images must have a integer name (i.e: `1.jpg` or `0001.jpg`)
#### `contlabelselect`
Takes a container and some labels and outputs a new container with only annotations with the provided labels.
Labels can be provided as a manually entered list with `-l` (i.e: `-l person head face`) or as a path to a labelmap or
names file with `-f`. The option `-r` will remove all entries without annotations after filtering by labels, and
`-c` will remove all entries where the image was not found
#### `contload`
Takes a container path and opens a interactive ipython shell where the container is loaded as `container`. The script
also imports the packages cv2, numpy and Path along side AnnotationContainer
#### `totb`
Takes a frozen_inference_graph.pb file (or indeed any other protobuff model) and opens it in tensorboard for inspection.
All tensorboard options can be used, like `--port <nr>` to change the tensorboard port.
#### `contheatmap`
Takes a container and labels and creates a heatmap for each label to show what areas of an image is most likely to
contain each label. Use the option `-s` to store the heatmaps as numpy files next to the container with the
`_heatmap.npy` suffix.
#### `contshow`
Used to inspect annotations in a container. Navigate through images with `a` and `d` and use `q` to quit.
Some options are provided so the script can be used for different usecases.
* `-l <one or more labels>` will limit which annotations will be shown
* `-p` will remove not show entries without annotations
* `-b <one or more image names>` will show only selected images and their annotations
* `-s` will shuffle the entries before showing them
* `-t <threshold>` will filter annotations by a confidence threshold before showing
* `-m <max number of images>` will show only `-m` images before quiting.
### Create a new alias in this repo
To create a new alias-script, simply write your script (making sure it only operates on absolute paths) and add it to
the `scripts` directory and run `setup.py`. For your script to be indexed by setup.py, add a variable `ALIAS_NAME`
somewhere in the first lines of code, that contains the alias name you want. I.E: `ALIAS_NAME = contsum`
### TODO:
* Testing for all scripts
<file_sep>/scripts/filter_container_by_threshold.py
import argparse
from collections import defaultdict
from bbox import AnnotationContainer
from tqdm import tqdm
ALIAS_NAME = 'contthresh'
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Filter out instances in a container by confidence threshold. '
'Labels[i] is filtered using threshold[i]')
parser.add_argument('container', help='Container to threshold')
parser.add_argument('-l', '--labels', type=str, nargs='*', help='List of labels to threshold')
parser.add_argument('-t', '--threshold', type=float, nargs='*',
help='List of thresholds to use for provided labels.')
parser.add_argument('-r', '--rest', type=float, help='Threshold to use for all other labels. ' +
'If no labels provided, this is used for all labels. If no rest is provided, ' +
'all other labels is threshold with 0.0')
parser.add_argument('-c', '--cleanup', action='store_true', help='Remove all empty entries after thresholding')
args = parser.parse_args()
if args.labels and args.threshold:
assert len(args.labels) == len(args.threshold)
if args.threshold is None:
args.threshold = []
if args.labels is None:
args.labels = []
for t in args.threshold:
assert 0 <= t <= 1
cont = AnnotationContainer.from_file(args.container)
labels = cont.get_instance_labels()
threshold = {}
for l in labels:
if l in args.labels:
threshold[l] = args.threshold[args.labels.index(l)]
else:
threshold[l] = args.rest if args.rest else 0.0
current_threshold = defaultdict(lambda: 1.1)
for e in cont:
for i in e:
if current_threshold[i.label] > i.score:
current_threshold[i.label] = i.score
print('==== Current lowest score for each label: ====')
for l in sorted(list(current_threshold.keys())):
print('\t', l.ljust(15), current_threshold[l])
print()
print('==== Filtering instances with threshold: ====')
for l, t in threshold.items():
print('\t', l.ljust(15), t)
if input('\nContinue? [y/n]: ') != 'y':
quit()
for e in tqdm(cont):
e.instances = [i for i in e if i.score >= threshold[i.label]]
if args.cleanup:
print('==== Cleanup: Removing empty entries ====')
cont.without_empty_entries(in_place=True)
cont.summary()
cont.to_file(args.container)
<file_sep>/scripts/change_dataset_root.py
from pathlib import Path
from bbox import AnnotationContainer
import argparse
ALIAS_NAME = 'contpath'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Change root path to datasets in container.')
parser.add_argument('container', metavar='FILE', type=str, help='Container')
parser.add_argument('-a', '--all', type=str, help='Give all datasets this path as root')
parser.add_argument('-i', '--interactive', action='store_true', help='Sets script in interactive mode where you provide paths for all subsets')
args = parser.parse_args()
cont = AnnotationContainer.from_file(args.container)
dsp = cont.dataset_source_provider.dataset_sources
if args.interactive:
print('\tInteractive mode: provide path for each of the following subsets')
for dataset, subset in list(dsp.keys()):
root_path = Path(input(f'[({dataset}, {subset})] -> '))
if root_path.exists():
print('\033[32mOK\033[0m')
dsp[(dataset, subset)] = root_path
else:
print('\033[31mWarning: can not find this directory.\033[0m', end=' ')
if input('Add anyway? [y/n] ') == 'y':
dsp[(dataset, subset)] = root_path
elif args.all:
root_path = Path(args.all)
if not root_path.exists():
print('\033[31mWarning: can not find this directory.\033[0m', end=' ')
if input('Add anyway? [y/n] ') != 'y':
quit()
for k in list(dsp.keys()):
dsp[k] = root_path
else:
raise ValueError('Script must either be run in interactive mode, or --all must be set')
cont.summary()
cont.to_file(args.container)
<file_sep>/scripts/open_protobuff_model_in_tensorboard.py
import tensorflow as tf
import argparse
import os
ALIAS_NAME = 'totb'
def get_args():
parser = argparse.ArgumentParser(description='Export .pb files to tensorboard')
parser.add_argument('model', help='frozen_inference_graph.pb')
parser.add_argument('--out', help='log_dir: where event file is written')
parser.add_argument('--port', default='6006', help='Tensorboard port. Default 6006')
return parser.parse_args()
if __name__ == '__main__':
args = get_args()
model = args.model
out = args.out if args.out else 'event'
with tf.Session() as sess:
model_filename = str(model)
with tf.gfile.FastGFile(model_filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
g_in = tf.import_graph_def(graph_def)
train_writer = tf.summary.FileWriter(str(out))
train_writer.add_graph(sess.graph)
os.system(f'tensorboard --logdir {out} --port {args.port}')
<file_sep>/scripts/create_video_from_container.py
import cv2
from bbox import AnnotationContainer
import argparse
from pathlib import Path
from tqdm import tqdm
from collections import defaultdict
import numpy as np
ALIAS_NAME = 'cont2video'
def get_args():
parser = argparse.ArgumentParser(description='Create a video of all frames in container with their detections')
parser.add_argument('container', type=str, nargs='*', help='Containers')
parser.add_argument('-l', '--labels', type=str, nargs='*', help='Labels to use')
parser.add_argument('-f', '--fps', default=24, type=int, help='video FPS')
parser.add_argument('-w', '--watermark', action='store_true', help='Add container name as watermark')
args = parser.parse_args()
for c in args.container:
assert Path(c).exists(), f'{c} does not exists'
return args
if __name__ == '__main__':
args = get_args()
labels = args.labels
fps = args.fps
colors = defaultdict(lambda: np.random.randint(0, 255, 3))
output_files = []
for container_path in tqdm(args.container, desc='containers'):
name = Path(container_path).stem
container = AnnotationContainer.from_file(container_path)
container.label_to_colour = colors
video_writer = None
output_file_name = Path(container_path).parent / f'{Path(container_path).stem}.avi'
output_files.append(output_file_name)
if len(labels) > 0:
container.with_selected_labels(labels, prune_empty_entries=False, in_place=True)
keys = list(sorted(container.entries.keys(), key=lambda x: int(Path(x).stem)))
for k in tqdm(keys, desc='frames'):
e = container[k]
img = e.overlaid_on_image()
if video_writer is None:
h, w = img.shape[:2]
# 1
video_writer = cv2.VideoWriter(str(output_file_name), 0, fps, (w, h))
if args.watermark:
cv2.putText(img, name,
(50, 50), cv2.FONT_HERSHEY_DUPLEX,
2, (255, 255, 255), 2)
video_writer.write(cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
cv2.destroyAllWindows()
video_writer.release()
print('To stack videos on top of each other, use: ')
cmd = 'ffmpeg '
if len(output_files) > 1:
for o in output_files:
cmd += '-i ' + str(o) + ' '
else:
cmd += '-i a.avi -i b.avi <...> '
cmd += '-filter_complex vstack <output name>'
print(cmd)<file_sep>/scripts/convert_container_to_tfrecord.py
from bbox import AnnotationContainer
from bbox.contrib.detection.tensorflow import TensorflowObjectDetector
from bbox.converters.tfrecord import TFRecordConverter
from bbox.contrib.data_augmentation import get_random_fisheye_transform
from pathlib import Path
from tqdm import tqdm_notebook as tqdm
from matplotlib import pyplot as plt
import matplotlib
matplotlib.rc('figure', figsize=(16, 12))
import argparse
ALIAS_NAME = 'cont2tfrecord'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Converts annotationcontainer to tfrecord')
parser.add_argument('container', help='Container to select labels from')
parser.add_argument('labelmap', type=str, help='labelmap.txt to go alongside record')
parser.add_argument('output', help='Output .tfrecord file')
parser.add_argument('-d', '--dry_run', action='store_true', help='Perform a test run to view annotations to be converted')
parser.add_argument('-a', '--augment', action='store_true', help='Augment images with prob 0.5')
args = parser.parse_args()
augmentation = get_random_fisheye_transform(0.5) if args.augment else None
labelmap = {}
for k, v in TensorflowObjectDetector.load_labels_from_pbtxt(args.labelmap).items():
labelmap[v] = k
labels_to_record_list = list(labelmap.keys())
print(labels_to_record_list)
container = AnnotationContainer.from_file(args.container)
if args.dry_run:
container = container.with_selected_labels(labels_to_record_list)
for e in container:
if augmentation is not None:
new_e, new_img = augmentation(e)
new_e.parent = container
plt.subplot(121)
plt.title('Augmented')
plt.axis('off')
plt.imshow(new_e.overlaid_on_image(new_img))
plt.subplot(122)
plt.title('Annotation')
plt.axis('off')
plt.imshow(e.overlaid_on_image())
plt.show()
else:
TFRecordConverter().to_file(
args.output,
container,
labels=labels_to_record_list,
max_image_size=640,
augmentation_function=augmentation
)
<file_sep>/scripts/show_entries.py
from random import shuffle
from bbox import AnnotationContainer
import argparse
import cv2
ALIAS_NAME = 'contshow'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Show entries from annotation container.')
parser.add_argument('container', metavar='FILE', type=str, help='Container')
parser.add_argument('-l', '--labels', type=str, nargs='*', help='Only show these labels')
parser.add_argument('-p', '--prune', action='store_true', help='Prune empty entries')
parser.add_argument('-n', '--name', type=str, nargs='*', help='Names of images to show')
parser.add_argument('-s', '--shuffle', action='store_true', help='Shuffle images')
parser.add_argument('-t', '--threshold', type=float, help='Filter detections with confidence')
parser.add_argument('-m', '--max', type=int, default=None, help='Show only this amount of images')
args = parser.parse_args()
container = args.container
cont = AnnotationContainer.from_file(container)
if args.labels and len(args.labels) > 0:
cont = cont.with_selected_labels(args.labels, prune_empty_entries=args.prune, in_place=True)
if args.threshold is not None:
assert 0 <= args.threshold <= 1, 'Confidence threshold must be in [0, 1]'
cont = cont.filter_all_instances_by_threshold(args.threshold, in_place=True)
if args.name:
for n in args.name:
if n not in cont:
print(n, 'not in container')
print('Num instances:', len(cont[n].instances))
cont[n].show()
else:
entry_keys = list(cont.entries.keys())
if args.shuffle:
shuffle(entry_keys)
key = None
i = 0
not_found_counter = 0
successfully_shown = set()
while True:
if not cont.entries[entry_keys[i]].get_image_full_path().exists():
print('Entry:', entry_keys[i], 'is not found.')
not_found_counter += 1
if key == ord('a'):
i -= 1
else:
i += 1
continue
successfully_shown.add(i)
image = cont.entries[entry_keys[i]].overlaid_on_image()
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
name = cont.entries[entry_keys[i]].image_name
cv2.namedWindow(name, cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty(name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
cv2.imshow(name, image)
key = cv2.waitKey()
cv2.destroyAllWindows()
if key == ord('a'):
i -= 1
elif key == ord('d'):
i += 1
elif key == ord('q'):
break
if args.max is not None and args.max <= len(successfully_shown):
print(f'Max number ({args.max}) of images shown')
break
i = i % len(entry_keys)
cv2.destroyAllWindows()
if not_found_counter > 0:
print('\tNB:\t\tTried to show', not_found_counter, 'missing images.') | 1470e7d239bd09fb1686f47f488eeb28e1877ce6 | [
"Markdown",
"Python"
]
| 14 | Python | Martijho/alias_scripts | ac1b509c32e53d46c3803f316fa447b9690dda59 | 992b1c1d6a9c0112c1f697530817fef456280949 |
refs/heads/master | <repo_name>kmikage/nkjg-like-first-setup<file_sep>/Sakura-no-VPS/install_ansible_to_ubuntu16_04.sh
#!/bin/sh
# How to use
# ---
# <New Incetance>
# SAKURA Internet [Virtual Private Server SERVICE]
# $ wget -O - 'https://raw.githubusercontent.com/kmikage/nkjg-like-first-setup/master/Sakura-no-VPS/install_ansible_to_ubuntu16_04.sh' | /bin/sh
sudo sed -i "s/^PermitRootLogin .*$/PermitRootLogin no/g" /etc/ssh/sshd_config
sudo sed -i "s/^PasswordAuthentication .*$/PasswordAuthentication no/g" /etc/ssh/sshd_config
sudo systemctl reload sshd
sudo sed -i "s/ ALL$/ NOPASSWD:ALL/g" /etc/sudoers
mkdir -p ~/.ssh
chmod 700 ~/.ssh
ssh-keygen -t rsa
ssh-keygen -t rsa -f ~/.ssh/id_rsa -N ""
cp -prv ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys
touch ~/.ssh/config
chmod 600 ~/.ssh/config
cat <<_EOL | tee ~/.ssh/config
Host localhost
Hostname 127.0.0.1
Port 22
User ubuntu
IdentityFile ~/.ssh/id_rsa
Host *
ServerAliveInterval 10
ServerAliveCountMax 5
GatewayPorts yes
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
_EOL
sudo apt-add-repository ppa:ansible/ansible
sudo apt-get update -y
sudo apt-get install vim -y
sudo apt-get install ansible -y
sudo update-alternatives --config editor
sudo ln -sf /usr/share/zoneinfo/Asia/Tokyo /etc/localtime
sudo mkdir -p /etc/ansible
echo "127.0.0.1 ansible_connection=local" | sudo tee -a /etc/ansible/hosts
cat <<_EOL > ~/upgrade.yml
---
- hosts: localhost
user: ubuntu
become: yes
tasks:
- name: "upgrade"
apt:
upgrade: dist
_EOL
ansible-playbook -k ~/upgrade.yml
echo '--- your SSH secret key ---'
cat ~/.ssh/id_rsa
echo '--- your SSH secret key ---'
exit
| 346eb7288d31fb8a6eff2c7f4c955ed15574f241 | [
"Shell"
]
| 1 | Shell | kmikage/nkjg-like-first-setup | 9cf566f79b992658cff115b438c107ee4791d763 | 6921fcb1f22fb1fb98b09d9ebfb6b8e35ea1903c |
refs/heads/master | <repo_name>C0l0ch0/BPV_WAU<file_sep>/Billing/app/templates/header.php
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<head>
<meta charset="utf-8" />
<title><?php echo $Titulo;?></title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<meta content="" name="description" />
<meta content="" name="author" />
<!-- ================== BEGIN BASE CSS STYLE ================== -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">
<link href="<?=WEBROOT.DS;?>plugins/jquery-ui/themes/base/minified/jquery-ui.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>css/animate.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>css/style.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>css/style-responsive.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>css/theme/default.css" rel="stylesheet" id="theme" />
<!-- ================== END BASE CSS STYLE ================== -->
<!-- ================== BEGIN PAGE LEVEL CSS STYLE ================== -->
<link href="<?=WEBROOT.DS;?>plugins/jquery-jvectormap/jquery-jvectormap-1.2.2.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>plugins/bootstrap-calendar/css/bootstrap_calendar.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>plugins/bootstrap-combobox/css/bootstrap-combobox.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>plugins/bootstrap-select/bootstrap-select.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>plugins/gritter/css/jquery.gritter.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>plugins/morris/morris.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>plugins/DataTables/css/data-table.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>plugins/parsley/src/parsley.css" rel="stylesheet" />
<!-- ================== END PAGE LEVEL CSS STYLE ================== -->
<!-- ================== BEGIN BASE JS ================== -->
<script src="<?=WEBROOT.DS;?>plugins/pace/pace.min.js"></script>
<!-- ================== END BASE JS ================== -->
</head><file_sep>/Billing/core/script/test.php
<?php
/*---------------------------------Script de cobros por Hora-------------------------------*/
define('PATH',str_replace("\\","/",dirname(__FILE__)));
define('DS',"/");
define('LIB',PATH.DS.'lib');
define('LOGS',PATH.DS.'logs/producto');define('DS',"/");
define('LIB',PATH.DS.'lib');
define('LOGS',PATH.DS.'logs/producto');
echo LOGS;
?>
<file_sep>/Billing/app/modules/detalle/detalle.php
<?php
import::load('lib', 'Validate_Auth');
import::load('lib', 'Start_Page');
import::load('lib', 'Session');
import::load('lib', 'MySQL');
import::load('lib', 'view');
class detalle{
function __construct(){
$this->titulo = 'Billing Vas Pass';
$this->mensaje = '';
}
function samex($mensaje){
if(self::check()){
$data = self::GetArrayInfo("samex",$mensaje);
self::LoadTemplate("basic/carrierD.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function samexI($mensaje){
if(self::check()){
$data = self::GetArrayInfo("samex",$mensaje);
self::LoadTemplate("basic/CarrierD_I.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function samexP($mensaje){
if(self::check()){
$data = self::GetArrayInfo("samex",$mensaje);
self::LoadTemplate("basic/CarrierD_P.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function samexDetails($mensaje){
if(self::check()){
$data = self::GetArrayInfo("samex",$mensaje);
self::LoadTemplate("basic/CarrierD_P_D.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function BillingSamex($mensaje){
if(self::check()){
$data = self::GetArrayInfo("samex",$mensaje);
self::LoadTemplate("basic/CarrierD_Billing.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function notificacionessamex($mensaje){
if(self::check()){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
//self::LoadTemplate("dashboard/dash.php",$data);
self::LoadTemplate("samex/notificacionessamex.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function saper($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saper",$mensaje);
self::LoadTemplate("basic/carrierD.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function saperI($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saper",$mensaje);
self::LoadTemplate("basic/CarrierD_I.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function saperP($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saper",$mensaje);
self::LoadTemplate("basic/CarrierD_P.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function BillingSaper($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saper",$mensaje);
self::LoadTemplate("basic/CarrierD_Billing.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function notificacionessaper($mensaje){
if(self::check()){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
//self::LoadTemplate("dashboard/dash.php",$data);
self::LoadTemplate("saper/notificacionessaper.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function saecu($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saecu",$mensaje);
self::LoadTemplate("basic/carrierD.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function saecuI($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saecu",$mensaje);
self::LoadTemplate("basic/CarrierD_I.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function saecuP($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saecu",$mensaje);
self::LoadTemplate("basic/CarrierD_P.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function BillingSaecu($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saecu",$mensaje);
self::LoadTemplate("basic/CarrierD_Billing.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function notificacionessaecu($mensaje){
if(self::check()){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
//self::LoadTemplate("dashboard/dash.php",$data);
self::LoadTemplate("saecu/notificacionessaecu.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function sanic($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sanic",$mensaje);
self::LoadTemplate("basic/carrierD.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function sanicI($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sanic",$mensaje);
self::LoadTemplate("basic/CarrierD_I.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function sanicP($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sanic",$mensaje);
self::LoadTemplate("basic/CarrierD_P.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function BillingSanic($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sanic",$mensaje);
self::LoadTemplate("basic/CarrierD_Billing.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function sapan($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sapan",$mensaje);
self::LoadTemplate("basic/carrierD.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function sapanI($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sapan",$mensaje);
self::LoadTemplate("basic/CarrierD_I.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function sapanP($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sapan",$mensaje);
self::LoadTemplate("basic/CarrierD_P.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function BillingSapan($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sapan",$mensaje);
self::LoadTemplate("basic/CarrierD_Billing.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function saca($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saca",$mensaje);
self::LoadTemplate("basic/carrierD.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function sacaI($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saca",$mensaje);
self::LoadTemplate("basic/CarrierD_I.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function sacaP($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saca",$mensaje);
self::LoadTemplate("basic/CarrierD_P.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function BillingSaca($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saca",$mensaje);
self::LoadTemplate("basic/CarrierD_Billing.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function sasal($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sasal",$mensaje);
self::LoadTemplate("basic/carrierD.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function sasalI($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sasal",$mensaje);
self::LoadTemplate("basic/CarrierD_I.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function sasalP($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sasal",$mensaje);
self::LoadTemplate("basic/CarrierD_P.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function BillingSasal($mensaje){
if(self::check()){
$data = self::GetArrayInfo("sasal",$mensaje);
self::LoadTemplate("basic/CarrierD_Billing.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function saven($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saven",$mensaje);
self::LoadTemplate("basic/carrierD.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function savenI($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saven",$mensaje);
self::LoadTemplate("basic/CarrierD_I.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function savenP($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saven",$mensaje);
self::LoadTemplate("basic/CarrierD_P.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function BillingSaven($mensaje){
if(self::check()){
$data = self::GetArrayInfo("saven",$mensaje);
self::LoadTemplate("basic/CarrierD_Billing.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function notificacionessaven($mensaje){
if(self::check()){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
//self::LoadTemplate("dashboard/dash.php",$data);
self::LoadTemplate("saven/notificacionessamex.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
private function GetArrayInfo($option,$mensaje){
$conexion = new MySQL(0);
$query = "call GetDescriptionInfo('".$option."');";
$exec = $conexion->consulta($query);
$row2 = $conexion->fetch_row($exec);
$return = array( "Titulo" => "Billing Vas Pass",
"mensaje" => $mensaje,
"name1" => strtolower($row2[0]),
"data1" => "",
"pais" => $row2[1],
"schema" => $row2[2],
"bd_id" => $row2[3]);
$conexion->MySQLClose();
return $return;
}
private function check(){
return Validate_Auth::check();
}
private function LoadTemplate($template, $dataArr){
if (file_exists(TEMPLATE.DS.$template)){
Validate_Auth::start();
$view = new view($template);
if (!empty($dataArr)){
$view->render($dataArr);
}else{
$tempArr = array('NO' => 'DATA');
$view->render($tempArr);
}
}else{
echo 'Error!!! el template al que deseas accesar no existe. ';
echo $template;
}
}
}
?>
<file_sep>/Billing/app/modules/minimodules/guardia/Monitoring.php
<?php
$user = 'openalonzo';
$password = '<PASSWORD>';
$server = '192.168.2.101\SQLMercurio';
$database = 'SMSNET_ADMIN';
$conexión = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
odbc_exec($conexión,"USE SMSNET_ADMIN");
$body = '
<!-- begin row -->
<div class="row">
<!-- begin col-12 -->
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<div class="panel-heading-btn">
</div>
<h4 class="panel-title">Data Table - Default</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Nombre del Servicio</th>
<th>Detalle del servicio</th>
<th>Status</th>
</tr>
</thead>
<tbody>';
$result = odbc_exec($conexión," select *
FROM
OPENQUERY([192.168.3.11], 'EXEC WauReports.dbo.[GetMonitorService]')");
while ($r= odbc_fetch_object($result)){
$body = $body. "<tr><td>";
if(strlen($r->name)>30){
$body = $body. substr($r->name,0,30)."</td><td >".$r->current_message;
}else{
$body = $body.$r->name."</td><td >".$r->current_message;
}
$body = $body. "</td><td>
<span class=\"label-default label label-danger\">Error</span>
</td></tr>";
}
$body = $body.'
</tbody>
</table>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-12 -->
</div>
<!-- end row -->';
echo $body;
?><file_sep>/Billing/app/templates/dashboard/dashboard.php
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<div class="row">
<div id="ActiveMQ" ></div><br></br>
</div>
<div class="row">
<div id="DavidMod" ></div>
<!-- #modal-dialog -->
<div class="modal fade" id="modal-dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Detalle de Alarmas.</h4>
</div>
<div class="modal-body" id="alerta">
</div>
<div class="modal-footer">
<a href="javascript:;" class="btn btn-sm btn-white" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<script src="<?=WEBROOT.DS;?>js/ui-modal-notification.demo.min.js"></script>
</body>
</html>
<script src="<?=WEBROOT.DS;?>js/dashboard-v2.js"></script>
<?php include(TEMPLATE.DS.'footer.php');?>
<script>
$(document).ready(function() {
App.init();
Notification.init();
TableManageDefault.init();
<?php
$var1 = WEBROOT.DS.'img/users/'.$_SESSION['login'].'.jpg';
if (file_exists($var1)) {
$nombreimg = $_SESSION['login'];
$nombreDisplay = $_SESSION['login'];
} else {
$nombreimg = 'default';
$nombreDisplay = $_SESSION['login'];
}
?>
var name = "<?php echo $nombreimg; ?>";
var nameD = "<?php echo $nombreDisplay; ?>";
<?php
if(isset($_SESSION['start'])){
unset($_SESSION['start']);
?>
DashboardV2.init(name,nameD);
<?php }?>
});
</script>
<script>
var refreshId = setInterval(function()
{
var dir = "getDavidInfo2";
$('#DavidMod').fadeOut("slow").load(dir).fadeIn("slow");
}, 40000);
var refreshId2 = setInterval(function()
{
var dir = "getActiveMQInfo";
$('#ActiveMQ').fadeOut("slow").load(dir).fadeIn("slow");
}, 40000);
</script>
<script>
$( document ).ready(function() {
dir = "getDavidInfo2";
$('#DavidMod').fadeOut("slow").load(dir).fadeIn("slow");
dir = "getActiveMQInfo";
$('#ActiveMQ').fadeOut("slow").load(dir).fadeIn("slow");
});
</script>
<script>
function clickButton(valor)
{
var resultado = "";
switch (valor){
case 1:
var div = document.getElementById('alerta');
div.innerHTML ="";
$.get("getTXRX",function(data){
resultado = data;
div.innerHTML = data;
});
break;
case 2:
var div = document.getElementById('alerta');
div.innerHTML ="";
$.get("getGateway",function(data){
resultado = data;
div.innerHTML = data;
});
break;
case 3:
var div = document.getElementById('alerta');
div.innerHTML ="";
$.get("getBD",function(data){
resultado = data;
div.innerHTML = data;
});
break;
case 4:
var div = document.getElementById('alerta');
div.innerHTML ="<h4>Cargando la información solicitada......</h4>";
$.get("getServers",function(data){
resultado = data;
div.innerHTML = data;
});
break;
case 5:
var div = document.getElementById('alerta');
div.innerHTML ="<h4>Cargando la información solicitada......</h4>";
$.get("getServiocios",function(data){
resultado = data;
div.innerHTML = data;
});
break;
case 6:
var div = document.getElementById('alerta');
div.innerHTML ="<h4>Cargando la información solicitada......</h4>";
$.get("getKeyTransactions",function(data){
resultado = data;
div.innerHTML = data;
});
break;
case 7:
var div = document.getElementById('alerta');
div.innerHTML ="<h4>Cargando la información solicitada......</h4>";
$.get("getMonitoring",function(data){
resultado = data;
div.innerHTML = data;
});
break;
}
}
</script><file_sep>/Billing/app/templates/basic/CarrierD_P_D.php
<!--Begin Grafica CarrierD_I-->
<?php
require_once LIB.DS."MySQL.php";
//include(MINMODULES.DS.'detalle/metricas_prod.php');
?>
<!--End Grafica CarrierD_I -->
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin page-header -->
<h1 class="page-header"><?php echo strtoupper($name1);?> <small>Detalle General de Productos <?php echo $pais;?></small></h1>
<!-- end page-header -->
<div class="row">
<div class="col-md-12">
<div class="panel panel-inverse" data-sortable-id="ui-buttons-1"->
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
</div>
<h4 class="panel-title">Integradores</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table69" class="table table-striped table-bordered">
<thead>
<tr>
<th>ID Producto</th>
<th>Detalle del Servicio</th>
<th>Tarifa</th>
<th >Cobros Hoy</th>
<th>Cobros Exitoso</th>
<th>Cobros Exitoso DCO</th>
<th>Cobros Semana Pasada</th>
<th>Cobros Exitosos Semana Pasada</th>
<th>Cobros Exitosos Semana DCO</th>
<th>Diferencia Transacciones</th>
<th>Diferencia Exitosos</th>
<th>Diferencia dco</th>
<!-- <th>Cobros</th> -->
</tr>
</thead>
<tbody>
<?php
$conexion = new MySQL($bd_id);
$query = 'call '.$schema.'.Billing_monitor_data(5);';
$exec = $conexion->consulta($query);
while ($row2= $conexion->fetch_row($exec)){
echo "<tr>
<td>".$row2[0]."</td>
<td>".$row2[1]."</td>
<td>".$row2[2]."</td>
<td>".$row2[3]."</td>
<td>".$row2[4]."</td>
<td>".$row2[5]."</td>
<td>".$row2[6]."</td>
<td>".$row2[7]."</td>
<td>".$row2[8]."</td>
<td>".$row2[9]."</td>
<td>".$row2[10]."</td>
<td>".$row2[11]."</td>
</tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- end row -->
</div><br>
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<?php include(TEMPLATE.DS.'footer.php');?>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-combobox/js/bootstrap-combobox.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-select/bootstrap-select.min.js"></script>
<script>
$(document).ready(function() {
App.init();
TableManageDefault.init();
FormPlugins.init();
});
</script>
</body>
</html>
<file_sep>/Billing/app/modules/minimodules/guardia/Gateway.php
<?php
/*require_once($_SERVER['DOCUMENT_ROOT'].'/core/import.php');
import::load('lib', 'MySQL');
$conexion = new MySQL();*/
$user = 'openalonzo';
$password = '<PASSWORD>';
$server = '192.168.2.101\SQLMercurio';
$database = 'SMSNET_ADMIN';
$conexión = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
odbc_exec($conexión,"USE SMSNET_ADMIN");
$body = '
<!-- begin row -->
<div class="row">
<!-- begin col-12 -->
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<div class="panel-heading-btn">
</div>
<h4 class="panel-title">Data Table - Default</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Servicio</th>
<th>Descripcion</th>
<th>Last OK Status</th>
</tr>
</thead>
<tbody>';
$result = odbc_exec($conexión,"exec ServiceMonitor_GetGatewayClients");
while ($r= odbc_fetch_object($result)){
$body = $body."<tr><td>";
$body = $body.$r->GatewayDescription.'</td><td>'.$r->Description."</td><td>";
$body = $body.'<span class="label-warning label label-default">'.$r->LastOkStatus.'</span>';
$body = $body."</td></tr>";
}
$body = $body.'
</tbody>
</table>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-12 -->
</div>
<!-- end row -->';
odbc_close($conexión);
echo $body;
//24A7FF
?><file_sep>/Billing/app/modules/minimodules/detalle/metricas_prod.php
<?php
if (isset($_POST['combo1'])){
if(isset($integrador)){
//echo "test->".$integrador . " ".$_POST['combo1']." " ;
}else{
$integrador = $_POST['combo1'];
$producto = 0;
if(isset($_POST['combo2'])){
if($integrador == $_POST['combo1']){
$producto = $_POST['combo2'];
//echo $producto."PP \n";
}else{
$integrador = $_POST['combo1'];
$producto = 0;
}
}
}
}else{
$integrador = 0;
$producto = 0;
}
if(($integrador!=0)&&($producto != 0)){
unset($_POST['combo2']);
unset($_POST['combo1']);
$data1 = getData($name1,$name1,$integrador,$producto);
}else{
$data1 = '';
}
function getData($name,$nombre1,$integrador,$producto){
$dataArray = "";
$fecha = date('H');
$dia = date('d', (strtotime ("+1 day")));
try{
$conexion = new MySQL(0);
$query0 = ' select hour(date_add(NOW(), INTERVAL -'.HOURDB.' hour));';
$result0 = $conexion->consulta($query0);
$exec0 = $conexion->fetch_row($result0);
$fecha = $exec0[0];
$query = 'CALL GetProductChargeToday("'.strtolower($name).'",'.HOURDB.",".$integrador.','.$producto.');';
$result = $conexion->consulta($query);
$conexion->prepareNextResult();
$query1 = 'CALL GetProductChargeYesterday("'.strtolower($name).'",'.HOURDB.",".$integrador.','.$producto.');';
$result1 = $conexion->consulta($query1);
$conexion->prepareNextResult();
$query2 = 'CALL GetProductChargeProm("'.strtolower($name).'",'.HOURDB.",".$integrador.','.$producto.');';
$result2 = $conexion->consulta($query2);
$conexion->prepareNextResult();
if ((! $result) or (! $result1) or (! $result2)){
throw new Exception ("No se logro obtener informacion de cobros....\n");
}else{
$cont=0;
$hoy= $conexion->fetch_row($result);
$ayer= $conexion->fetch_row($result1);
$prom= $conexion->fetch_row($result2);
while ($cont <= $fecha){
if($ayer[1] == $cont){
$valor = $ayer[0];
$ayer= $conexion->fetch_row($result1);
}else{
$valor = 0;
}
if($hoy[1] == $cont){
$valor1 = $hoy[0];
$hoy= $conexion->fetch_row($result);
}else{
$valor1 = 0;
}
if($prom[0] == $cont){
$valor2 = $prom[1];
$prom= $conexion->fetch_row($result2);
}else{
$valor2 = 0;
}
$dataArray = $dataArray."data1.addRow([".$cont.", ".$valor2.",".$valor.", ".$valor1."]);\n";
$cont++;
}
}
$conexion->MySQLClose();
}catch(Exception $e){
echo 'Excepcion capturada: ', $e->getMessage(), "\n";
}
return $dataArray;
}
?>
<file_sep>/Billing/app/modules/minimodules/detalle/metricas.php
<?php
$data1 = getData($name1,1);
function getData($name,$num){
$dataArray = "";
$fecha = date('H', (strtotime ("+1 Hours")));
$dia = date('d', (strtotime ("+1 day")));
try{
$conexion = new MySQL(0);
$query0 = ' select hour(date_add(NOW(), INTERVAL -'.HOURDB.' hour));';
$result0 = $conexion->consulta($query0);
$exec0 = $conexion->fetch_row($result0);
$fecha = $exec0[0];
$query = 'CALL GetCarrierChargeToday("'.strtolower($name).'",'.HOURDB.');';
$result = $conexion->consulta($query);
$conexion->prepareNextResult();
$query1 = 'CALL GetCarrierChargeYesterday("'.strtolower($name).'",'.HOURDB.');';
$result1 = $conexion->consulta($query1);
$conexion->prepareNextResult();
$query2 = 'CALL GetCarrierChargeProm("'.strtolower($name).'",'.HOURDB.');';
$result2 = $conexion->consulta($query2);
$conexion->prepareNextResult();
if ((! $result) or (! $result1) or (! $result2)){
throw new Exception ("No se logro obtener informacion de cobros....\n");
}else{
$cont = 0;
@$hoy = $conexion->fetch_row($result);
@$ayer = $conexion->fetch_row($result1);
@$prom = $conexion->fetch_row($result2);
while ($cont <= $fecha){
if(($ayer[1] == $cont) and ($ayer[1] != '')){
@$valor = $ayer[0];
@$ayer = $conexion->fetch_row($result1);
}else{
$valor = 0;
}
if(($hoy[1] == $cont) and ($hoy[1] != '')){
@$valor1 = $hoy[0];
@$hoy = $conexion->fetch_row($result);
}else{
$valor1 = 0;
}
if(($prom[1] == $cont) and ($prom[1] != '')){
@$valor2 = $prom[0];
@$prom = $conexion->fetch_row($result2);
}else{
$valor2 = 0;
}
$dataArray = $dataArray."data".$num.".addRow([".$cont.", ".number_format($valor2,0,'','').", ".$valor." , ".$valor1."]);\n";
//$dataArray = $dataArray."data1.addRow([".$cont.", ".$valor2.",".$valor.", ".$valor1."]);\n";
$cont++;
}
/*while ($hoy = $conexion->fetch_row($result)){
if( @$ayer = $conexion->fetch_row($result1) and
@$prom1 = $conexion->fetch_row($result2)){
if($hoy[0] == ''){$hoy[0] = 0;}
if($ayer[0] == ''){$ayer[0] = 0;}
if($prom1[0] == ''){$prom1[0] = 0;}
$dataArray = $dataArray."data".$num.".addRow([".$hoy[1].", ".number_format($prom1[0],0,'','').", ".$ayer[0]." , ".$hoy[0]."]);\n";
}
}*/
}
$conexion->MySQLClose();
}catch(Exception $e){
echo 'Excepcion capturada: ', $e->getMessage(), "\n";
}
return $dataArray;
}
?><file_sep>/Billing/app/modules/minimodules/guardia/metricas_BK.php
<html lang="en">
<head>
<!-- start: Meta -->
<meta charset="utf-8">
<title>Cobros DAVID</title>
<meta name="description" content="Bootstrap Metro Dashboard">
<meta name="author" content="<NAME>">
<meta name="keyword" content="Metro, Metro UI, Dashboard, Bootstrap, Admin, Template, Theme, Responsive, Fluid, Retina">
<!-- end: Meta -->
<!-- start: Mobile Specific -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- end: Mobile Specific -->
<!-- start: CSS -->
<link id="bootstrap-style" href="<?=MODULE.DS;?>minimodules/guardia/PETARDO/css/bootstrap.min.css" rel="stylesheet">
<link href="<?=MODULE.DS;?>minimodules/guardia/PETARDO/css/bootstrap-responsive.min.css" rel="stylesheet">
<link id="base-style" href="<?=MODULE.DS;?>minimodules/guardia/PETARDO/css/style.css" rel="stylesheet">
<link id="base-style-responsive" href="<?=MODULE.DS;?>minimodules/guardia/PETARDO/css/style-responsive.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-ext' rel='stylesheet' type='text/css'>
<!-- end: CSS -->
<!-- The HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<link id="ie-style" href="css/ie.css" rel="stylesheet">
<![endif]-->
<!--[if IE 9]>
<link id="ie9style" href="css/ie9.css" rel="stylesheet">
<![endif]-->
<!-- start: Favicon -->
<link rel="shortcut icon" href="<?=MODULE.DS;?>minimodules/guardia/PETARDO/img/favicon.ico">
<!-- end: Favicon -->
</head>
<?php
$name = "SAPER";
$data = "";
$data = getData($name,$name);
//echo getData($name,$name). "<br></br>";
$name1 = "SAMEX";
$data1 = "";
$data1 = getData($name1,$name1);
//echo getData($name1,$name1);
$name2 = "SANIC";
$data2 = "";
$data2 = getData($name2,$name2);
$name3 = "SAECU";
$data3 = "";
$data3 = getData($name3,$name3);
$name4 = "SAPAN";
$data4 = "";
$data4 = getData($name4,$name4);
$data5 = "";
$data5 = getDataTable();
$data6 = "";
$data6 = getDataTableSACA();
//@odbc_close($conexión);
function getData($name,$nombre1){
$keyAccess = getAccess();
$dataArray = "";
try{
$conexión = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$keyAccess[2];Database=$keyAccess[3];", $keyAccess[0], $keyAccess[1]);
$result = odbc_exec($conexión,"USE WauReports");
@$result = odbc_exec($conexión," select ".$name." ,HORA
from cobros_SA
where FECHA between (GETDATE()-2) and (GETDATE()-1)
and HORA <= DATEPART(HOUR, GETDATE())-1
order by FECHA,HORA");
@$result1 = odbc_exec($conexión," select ".$name.",HORA
from cobros_SA
where FECHA between (GETDATE()-1) and (GETDATE())
order by FECHA,HORA");
if ((! $result) or (! $result1)){
throw new Exception ("No se logro obtener informacion de cobros....\n");
}else{
while ($r= odbc_fetch_object($result)){
$r1=odbc_fetch_object($result1);
if($nombre1 == "SAPER"){
if($r->$name == ''){$r->$name=0;}
if($r1->$name == ''){$r1->$name=0;}
$dataArray = $dataArray."data.addRow([".$r->HORA.", ".$r->$name.", ".$r1->$name."]);\n";
}
if($nombre1 == "SAMEX"){
if(@$r->$name == ''){$r->$name=0;}
if(@$r1->$name == ''){$r1->$name=0;}
$dataArray = $dataArray."data1.addRow([".$r->HORA.", ".$r->$name.", ".$r1->$name."]);\n";
}
if($nombre1 == "SANIC"){
if(@$r->$name == ''){$r->$name=0;}
if(@$r1->$name == ''){$r1->$name=0;}
$dataArray = $dataArray."data2.addRow([".$r->HORA.", ".$r->$name.", ".$r1->$name."]);\n";
}
if($nombre1 == "SAECU"){
if(@$r->$name == ''){$r->$name=0;}
if(@$r1->$name == ''){$r1->$name=0;}
$dataArray = $dataArray."data3.addRow([".$r->HORA.", ".$r->$name.", ".$r1->$name."]);\n";
}
if($nombre1 == "SAPAN"){
if(@$r->$name == ''){$r->$name=0;}
if(@$r1->$name == ''){$r1->$name=0;}
$dataArray = $dataArray."data4.addRow([".$r->HORA.", ".$r->$name.", ".$r1->$name."]);\n";
}
}
}
}catch(Exception $e){
echo 'Excepcion capturada: ', $e->getMessage(), "\n";
}
return $dataArray;
}
function getDataTable(){
$keyAccess = getAccess();
$conexion = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$keyAccess[2];Database=$keyAccess[3];", $keyAccess[0], $keyAccess[1]);
$result = odbc_exec($conexion,"USE WauReports");
$result = odbc_exec($conexion,"EXEC GetChargesSA");
$r= odbc_fetch_object($result);
$result2 = odbc_exec($conexion,"GetpercentageSA");
$r2= odbc_fetch_object($result2);
$body = "<tr><td align=\"center\"> SAMEX </td><td align=\"right\">".number_format($r->SAMEX)."</td><td align=\"right\">".number_format($r2->SAMEX)."</td><td align=\"right\"> ".number_format((($r->SAMEX*100)/$r2->SAMEX));
$body = $body. "%</td></tr>";
$body = $body. "<tr><td align=\"center\"> SAPER </td><td align=\"right\">".number_format($r->SAPER)."</td><td align=\"right\">".number_format($r2->SAPER)."</td><td align=\"right\"> ".number_format((($r->SAPER*100)/$r2->SAPER));
$body = $body. "%</td></tr>";
$body = $body. "<tr><td align=\"center\"> SAECU </td><td align=\"right\">".number_format($r->SAECU)."</td><td align=\"right\">".number_format($r2->SAECU)."</td><td align=\"right\"> ".number_format((($r->SAECU*100)/$r2->SAECU));
$body = $body. "%</td></tr>";
return $body;
}
function getDataTableSACA(){
$keyAccess = getAccess();
$conexion = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$keyAccess[2];Database=$keyAccess[3];", $keyAccess[0], $keyAccess[1]);
$result = odbc_exec($conexion,"USE WauReports");
$result = odbc_exec($conexion,"EXEC GetChargesSA");
$r= odbc_fetch_object($result);
$result2 = odbc_exec($conexion,"GetpercentageSA");
$r2= odbc_fetch_object($result2);
$body = "<tr><td align=\"center\"> SANIC </td><td align=\"right\">".number_format($r->SANIC)."</td><td align=\"right\">".number_format($r2->SANIC)."</td><td align=\"right\"> ".number_format((($r->SANIC*100)/$r2->SANIC));
$body = $body. "%</td></tr>";
$body = $body. "<tr><td align=\"center\"> SAPAN </td><td align=\"right\">".number_format($r->SAPAN)."</td><td align=\"right\">".number_format($r2->SAPAN)."</td><td align=\"right\"> "/*.number_format((($r->SAPAN*100)/$r2->SAPAN))*/;
$body = $body. "%</td></tr>";
return $body;
}
function getAccess(){
$keyAccess = array("openalonzo","wau123","192.168.3.11","WauReports");
return $keyAccess;
}
?>
<body>
<div class="navbar">
<div class="navbar-inner">
<H4>WAU MOVIL COBROS <H4>
</div>
</div>
<!-- Begin: Content -->
<br>
<div style="display:inline-block; align: center; margin-left: 25px;">
<p><?php echo date("F j, Y");?>
<?php echo date("H:i:s");?></p>
</div><br></br>
<style type="text/css">
.CSSTableGenerator {
margin:0px;padding:0px;
width:30%;
border:1px solid #bababa;
-moz-border-radius-bottomleft:9px;
-webkit-border-bottom-left-radius:9px;
border-bottom-left-radius:9px;
-moz-border-radius-bottomright:9px;
-webkit-border-bottom-right-radius:9px;
border-bottom-right-radius:9px;
-moz-border-radius-topright:9px;
-webkit-border-top-right-radius:9px;
border-top-right-radius:9px;
-moz-border-radius-topleft:9px;
-webkit-border-top-left-radius:9px;
border-top-left-radius:9px; }
.CSSTableGenerator table{
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:20%;
margin:0px;padding:0px;
}.CSSTableGenerator tr:last-child td:last-child {
-moz-border-radius-bottomright:9px;
-webkit-border-bottom-right-radius:9px;
border-bottom-right-radius:9px;
}
.CSSTableGenerator table tr:first-child td:first-child {
-moz-border-radius-topleft:9px;
-webkit-border-top-left-radius:9px;
border-top-left-radius:9px;
}
.CSSTableGenerator table tr:first-child td:last-child {
-moz-border-radius-topright:9px;
-webkit-border-top-right-radius:9px;
border-top-right-radius:9px;
}.CSSTableGenerator tr:last-child td:first-child{
-moz-border-radius-bottomleft:9px;
-webkit-border-bottom-left-radius:9px;
border-bottom-left-radius:9px;
}.CSSTableGenerator tr:hover td{
}
.CSSTableGenerator tr:nth-child(odd){ background-color:#e5e5e5; }
.CSSTableGenerator tr:nth-child(even) { background-color:#ffffff; }
.CSSTableGenerator td{
vertical-align:middle;
border:1px solid #bababa;
border-width:0px 1px 1px 0px;
text-align:left;
padding:8px;
font-size:13px;
font-family:Arial;
font-weight:normal;
color:#000000;
}.CSSTableGenerator tr:last-child td{
border-width:0px 1px 0px 0px;
}.CSSTableGenerator tr td:last-child{
border-width:0px 0px 1px 0px;
}.CSSTableGenerator tr:last-child td:last-child{
border-width:0px 0px 0px 0px;
}
.CSSTableGenerator tr:first-child td{
background:-o-linear-gradient(bottom, #cccccc 5%, #777777 100%);
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #777777) );
background:-moz-linear-gradient( center top, #cccccc 5%, #777777 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#777777"); background: -o-linear-gradient(top,#cccccc,777777);
background-color:#cccccc;
border:0px solid #bababa;
text-align:center;
border-width:0px 0px 1px 1px;
font-size:14px;
font-family:Trebuchet MS;
font-weight:bold;
color:#ffffff;
}
.CSSTableGenerator tr:first-child:hover td{
background:-o-linear-gradient(bottom, #cccccc 5%, #777777 100%);
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #777777) );
background:-moz-linear-gradient( center top, #cccccc 5%, #777777 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#777777"); background: -o-linear-gradient(top,#cccccc,777777);
background-color:#cccccc;
}
.CSSTableGenerator tr:first-child td:first-child{
border-width:0px 0px 1px 0px;
}
.CSSTableGenerator tr:first-child td:last-child{
border-width:0px 0px 1px 1px;
}
.displayed {
display: block;
margin-left: auto;
margin-right: auto
float: left; }
</style>
<!--::::::::::::Empieza el otro estilo:::::::::::::::::-->
<style type="text/css">
.CSSTableGenerator2 {
margin:0px;padding:0px;
width:30%;
border:1px solid #bababa;
-moz-border-radius-bottomleft:9px;
-webkit-border-bottom-left-radius:9px;
border-bottom-left-radius:9px;
-moz-border-radius-bottomright:9px;
-webkit-border-bottom-right-radius:9px;
border-bottom-right-radius:9px;
-moz-border-radius-topright:9px;
-webkit-border-top-right-radius:9px;
border-top-right-radius:9px;
-moz-border-radius-topleft:9px;
-webkit-border-top-left-radius:9px;
border-top-left-radius:9px; }
.CSSTableGenerator2 table{
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:15%;
margin:0px;padding:0px;
}.CSSTableGenerator2 tr:last-child td:last-child {
-moz-border-radius-bottomright:9px;
-webkit-border-bottom-right-radius:9px;
border-bottom-right-radius:9px;
}
.CSSTableGenerator2 table tr:first-child td:first-child {
-moz-border-radius-topleft:9px;
-webkit-border-top-left-radius:9px;
border-top-left-radius:9px;
}
.CSSTableGenerator2 table tr:first-child td:last-child {
-moz-border-radius-topright:9px;
-webkit-border-top-right-radius:9px;
border-top-right-radius:9px;
}.CSSTableGenerator2 tr:last-child td:first-child{
-moz-border-radius-bottomleft:9px;
-webkit-border-bottom-left-radius:9px;
border-bottom-left-radius:9px;
}.CSSTableGenerator2 tr:hover td{
}
.CSSTableGenerator2 tr:nth-child(odd){ background-color:#e5e5e5; }
.CSSTableGenerator2 tr:nth-child(even) { background-color:#ffffff; }
.CSSTableGenerator2 td{
/*vertical-align:middle; */
border:1px solid #bababa;
border-width:0px 1px 1px 0px;
text-align:left;
padding:8px;
font-size:13px;
font-family:Arial;
font-weight:normal;
color:#000000;
}.CSSTableGenerator2 tr:last-child td{
border-width:0px 1px 0px 0px;
}.CSSTableGenerator2 tr td:last-child{
border-width:0px 0px 1px 0px;
}.CSSTableGenerator2 tr:last-child td:last-child{
border-width:0px 0px 0px 0px;
}
.CSSTableGenerator2 tr:first-child td{
background:-o-linear-gradient(bottom, #cccccc 5%, #777777 100%);
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #777777) );
background:-moz-linear-gradient( center top, #cccccc 5%, #777777 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#777777"); background: -o-linear-gradient(top,#cccccc,777777);
background-color:#cccccc;
border:0px solid #bababa;
text-align:center;
border-width:0px 0px 1px 1px;
font-size:14px;
font-family:Trebuchet MS;
font-weight:bold;
color:#ffffff;
}
.CSSTableGenerator2 tr:first-child:hover td{
background:-o-linear-gradient(bottom, #cccccc 5%, #777777 100%);
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #777777) );
background:-moz-linear-gradient( center top, #cccccc 5%, #777777 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#777777"); background: -o-linear-gradient(top,#cccccc,777777);
background-color:#cccccc;
}
.CSSTableGenerator2 tr:first-child td:first-child{
border-width:0px 0px 1px 0px;
}
.CSSTableGenerator2 tr:first-child td:last-child{
border-width:0px 0px 1px 1px;
}
displayed {
margin: 0 auto;
}
</style>
<center> <div class="CSSTableGenerator" style="display:inline-block;">
<table >
<tr>
<td >Super Agregador</td>
<td >Cobros Hoy</td>
<td >Promedio</td>
<td >Porcentaje</td>
</tr>
<?php echo $data5;?>
</table>
</div>
<div class="CSSTableGenerator2 " style="display:inline-block; vertical-align: top;">
<table >
<tr>
<td >Super Agregador</td>
<td >Cobros Hoy</td>
<td >Promedio</td>
<td >Porcentaje</td>
</tr>
<?php echo $data6;?>
</table>
</div>
</center>
<br>
<br>
<center><table class="table-responsive">
<tr>
<td>
<div class="box span4" onTablet="span6" onDesktop="span4">
<div class="box-header">
<h2><i class="halflings-icon white check"></i><span class="break"></span>SAMEX</h2>
<div class="box-icon">
<a href="#" class="btn-minimize"><i class="halflings-icon white chevron-up"></i></a>
</div>
</div>
<div class="box-content">
<div id="SAMEX" style="width: 400px; height: 250px; display:inline-block;"></div>
</div>
</div><!--/span-->
</td>
<td>
<div class="box span4" onTablet="span6" onDesktop="span4">
<div class="box-header">
<h2><i class="halflings-icon white check"></i><span class="break"></span>SAPER</h2>
<div class="box-icon">
<a href="#" class="btn-minimize"><i class="halflings-icon white chevron-up"></i></a>
</div>
</div>
<div class="box-content">
<div id="SAPER" style="width: 400px; height: 250px; display:inline-block;"></div>
</div>
</div><!--/span-->
</td>
<td>
<div class="box span4" onTablet="span6" onDesktop="span4">
<div class="box-header">
<h2><i class="halflings-icon white check"></i><span class="break"></span>SAECU</h2>
<div class="box-icon">
<a href="#" class="btn-minimize"><i class="halflings-icon white chevron-up"></i></a>
</div>
</div>
<div class="box-content">
<div id="SAECU" style="width: 400px; height: 250px; display:inline-block;"></div>
</div>
</div><!--/span-->
</td>
</tr>
</table>
</center>
<center><table class="table-responsive">
<tr>
<td>
<div class="box span4" onTablet="span6" onDesktop="span4">
<div class="box-header">
<h2><i class="halflings-icon white check"></i><span class="break"></span>SANIC</h2>
<div class="box-icon">
<a href="#" class="btn-minimize"><i class="halflings-icon white chevron-up"></i></a>
</div>
</div>
<div class="box-content">
<div id="SANIC" style="width: 400px; height: 250px; display:inline-block;"></div>
</div>
</div><!--/span-->
</td>
<td>
<div class="box span4" onTablet="span6" onDesktop="span4">
<div class="box-header">
<h2><i class="halflings-icon white check"></i><span class="break"></span>SAPAN</h2>
<div class="box-icon">
<a href="#" class="btn-minimize"><i class="halflings-icon white chevron-up"></i></a>
</div>
</div>
<div class="box-content">
<div id="SAPAN" style="width: 400px; height: 250px; display:inline-block;"></div>
</div>
</div><!--/span-->
</td>
<td>
<div class="box span4" onTablet="span6" onDesktop="span4">
<div class="box-header">
<h2><i class="halflings-icon white check"></i><span class="break"></span>SAGT</h2>
<div class="box-icon">
<a href="#" class="btn-minimize"><i class="halflings-icon white chevron-up"></i></a>
</div>
</div>
<div class="box-content">
<div id="SAPAN" style="width: 400px; height: 250px; display:inline-block;"></div>
</div>
</div><!--/span-->
</td>
</tr>
</table>
</center>
<footer>
<p>
<span style="text-align:left;float:left">© 2014-2015 <a href="http://192.168.64.54/paseguardia/getmetricas" alt="Bootstrap_Metro_Dashboard">By NO<NAME></a></span>
</p>
</footer>
<!-- end: Content -->
<!-- start: JavaScript-->
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery-1.9.1.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery-migrate-1.0.0.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery-ui-1.10.0.custom.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.ui.touch-punch.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/modernizr.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/bootstrap.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.cookie.js"></script>
<script src='<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/fullcalendar.min.js'></script>
<script src='<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.dataTables.min.js'></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/excanvas.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.flot.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.flot.pie.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.flot.stack.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.flot.resize.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.chosen.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.uniform.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.cleditor.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.noty.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.elfinder.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.raty.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.iphone.toggle.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.uploadify-3.1.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.gritter.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.imagesloaded.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.masonry.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.knob.modified.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/jquery.sparkline.min.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/counter.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/retina.js"></script>
<script src="<?=MODULE.DS;?>minimodules/guardia/PETARDO/js/custom.js"></script>
<!-- end: JavaScript-->
</body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Hora');
data.addColumn('number', 'Cobros Ayer');
data.addColumn('number', 'Cobros Hoy');
<?php
echo $data;
?>
/*0fd43a
9EABB4
*/
var options = {
title: '<?php echo 'Cobros '.$name;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {color: '#9EABB4'},
1: {color: '#0fd43a'}
}
};
var formatter = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
var formatterH = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, sufrix: '00', pattern: '##:'});
formatter.format(data, 1);
formatter.format(data, 2);
formatterH.format(data, 0);
var chart = new google.visualization.AreaChart(document.getElementById('SAPER'));
/*var my_div = document.getElementById('SAPER');
google.visualization.events.addListener(chart, 'ready', function () {
var imgUri = chart.getImageURI();
my_div.innerHTML = '<img src="' + imgUri + '">';
// do something with the image URI, like:
//window.open(imgUri);
});*/
chart.draw(data, options);
/*----------------------*/
var data1 = new google.visualization.DataTable();
data1.addColumn('number', 'Hora');
data1.addColumn('number', 'Cobros Ayer');
data1.addColumn('number', 'Cobros Hoy');
<?php
echo $data1;
?>
var options1 = {
title: '<?php echo 'Cobros '.$name1;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data1.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {color: '#9EABB4'},
1: {color: '#0fd43a'}
}
};
var formatter1 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter1.format(data1, 1);
formatter1.format(data1, 2);
var chart1 = new google.visualization.AreaChart(document.getElementById('SAMEX'));
chart1.draw(data1, options1);
/*----------------------*/
var data2 = new google.visualization.DataTable();
data2.addColumn('number', 'Hora');
data2.addColumn('number', 'Cobros Ayer');
data2.addColumn('number', 'Cobros Hoy');
<?php
echo $data2;
?>
var options2 = {
title: '<?php echo 'Cobros '.$name2;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data2.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {color: '#9EABB4'},
1: {color: '#0fd43a'}
}
};
var formatter2 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter2.format(data2, 1);
formatter2.format(data2, 2);
var chart2 = new google.visualization.AreaChart(document.getElementById('SANIC'));
chart2.draw(data2, options2);
/*----------------------*/
var data3 = new google.visualization.DataTable();
data3.addColumn('number', 'Hora');
data3.addColumn('number', 'Cobros Ayer');
data3.addColumn('number', 'Cobros Hoy');
<?php
echo $data3;
?>
var options3 = {
title: '<?php echo 'Cobros '.$name3;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data3.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {color: '#9EABB4'},
1: {color: '#0fd43a'}
}
};
var formatter3 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter3.format(data3, 1);
formatter3.format(data3, 2);
var chart3 = new google.visualization.AreaChart(document.getElementById('SAECU'));
chart3.draw(data3, options3);
/*----------------------*/
var data4 = new google.visualization.DataTable();
data4.addColumn('number', 'Hora');
data4.addColumn('number', 'Cobros Ayer');
data4.addColumn('number', 'Cobros Hoy');
<?php
echo $data4;
?>
var options4 = {
title: '<?php echo 'Cobros '.$name4;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data4.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {color: '#9EABB4'},
1: {color: '#0fd43a'}
}
};
var formatter4 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter4.format(data4, 1);
formatter4.format(data4, 2);
var chart4 = new google.visualization.AreaChart(document.getElementById('SAPAN'));
chart4.draw(data4, options4);
}
</script>
</html><file_sep>/Billing/core/lib/ActiveMQ.php
<?php
class ActiveMQ{
var $fp;
var $Q_Name;
var $Q_Zize;
var $AMQ_name;
var $AMQ_url;
var $Q_ConsumerCount;
var $Q_EnqueueCount;
var $Q_DequeueCount;
var $conectorLocal;
function __construct(){
$this->Q_Name = "";
$this->Q_Size = "";
$this->AMQ_name = "";
$this->AMQ_url = "";
$this->Q_ConsumerCount = "";
$this->Q_EnqueueCount = "";
$this->Q_DequeueCount = "";
$this->conectorLocal = new MySQL(0);
}
function StartProcess($data,$SaveAction){
while ($row = $this->conectorLocal->fetch_row($data)){
try {
$this->AMQ_name = $row[0];
$this->AMQ_url = $row[1];
self::WriteLog( "**************************Realizando llamado a GetActiveMQData para ".$this->AMQ_name."**************************");
self::GivemeSomeSpace();
self::ParseJsonData(self::GetActiveMQData());
self::WriteLog( "**************************finalizacion de generacion de Info**************************");
} catch (Exception $e) {
self::WriteLog("No se logro obtener la informacion de ".$this->AMQ_name." Validar conexion a Base de datos!!!!!!!!!!!!!!!");
}
}
}
function ParseJsonData($resp){
$servers = json_decode($resp,true);
for($i=0;$i<count($servers['queue']);$i++){
$this->Q_Name = '';
$this->Q_Size = '';
$this->Q_ConsumerCount = '';
$this->Q_EnqueueCount = '';
$this->Q_DequeueCount = '';
$cont = 0;
if (($servers["queue"][$i]["stats"]["@attributes"]["size"] > 1) or ($servers["queue"][$i]["stats"]["@attributes"]["consumerCount"] < 1)){
try {
$this->Q_Name = (isset($servers["queue"][$i]["@attributes"]["name"])) ? $servers["queue"][$i]["@attributes"]["name"] : "No Data";
$this->Q_Size = (isset($servers["queue"][$i]["stats"]["@attributes"]["size"])) ? $servers["queue"][$i]["stats"]["@attributes"]["size"] : "No Data";
$this->Q_ConsumerCount = (isset($servers["queue"][$i]["stats"]["@attributes"]["consumerCount"])) ? $servers["queue"][$i]["stats"]["@attributes"]["consumerCount"] : "No Data";
$this->Q_EnqueueCount = (isset($servers["queue"][$i]["stats"]["@attributes"]["enqueueCount"])) ? $servers["queue"][$i]["stats"]["@attributes"]["enqueueCount"] : "No Data";
$this->Q_DequeueCount = (isset($servers["queue1"][$i]["stats"]["@attributes"]["dequeueCount"])) ? $servers["queue"][$i]["stats"]["@attributes"]["dequeueCount"] : "No Data";
self::WriteLog("name: ". $this->Q_Name);
self::WriteLog("size: ". $this->Q_Size);
self::WriteLog("consumerCount: ". $this->Q_ConsumerCount);
self::WriteLog("enqueueCount: ". $this->Q_EnqueueCount);
self::WriteLog("dequeueCount: ". $this->Q_DequeueCount);
self::SaveData();
} catch (Exception $e) {
self::WriteLog("error ->".$e);
}
}
}
}
function SaveData(){
$query = 'CALL SaveMonitorQueue("'.$this->AMQ_name.'","'.$this->Q_Name.'",'.$this->Q_Size.','.$this->Q_ConsumerCount.');';
$result = $this->conectorLocal->consulta($query);
$this->conectorLocal->prepareNextResult();
}
function GivemeSomeSpace(){
$query = 'truncate table monitor_queue;';
$result = $this->conectorLocal->consulta($query);
$this->conectorLocal->prepareNextResult();
self::WriteLog("Realizando limpieza.......");
}
function GetActiveMQData(){
$resp = '';
if ((@$response_xml_data = file_get_contents($this->AMQ_url))===false){
self::WriteLog("Error fetching XML\n");
} else {
libxml_use_internal_errors(true);
$data = simplexml_load_string($response_xml_data);
if (!$data) {
self::WriteLog("Error loading XML\n");
foreach(libxml_get_errors() as $error) {
self::WriteLog("\t", $error->message);
}
}else{
$resp = json_encode($data);
}
return $resp;
}
}
function LoadActiveMQ(){
$query = "call GetActiveMQInfo;";
$result = $this->conectorLocal->consulta($query);
$this->conectorLocal->prepareNextResult();
self::WriteLog("Servicios a ejecutar: ".$this->conectorLocal->num_rows($result));
return $result;
}
function StartLog($log){
$this->fp = fopen(LOGS.DS.$log.date('Y_m_d').".txt", "a");
}
function WriteLog($comment){
fputs($this->fp, "[".date('Y-m-d H:i:s')."] ".$comment."\n");
}
}
?>
<file_sep>/Billing/app/templates/usuario/crear.php
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin breadcrumb -->
<!-- end breadcrumb -->
<!-- begin page-header -->
<h1 class="page-header">Registro de nuevo Usuario<small></small></h1>
<!-- end page-header -->
<div class="row">
<div id="DavidMod"></div>
<!-- #modal-dialog -->
<div class="modal fade" id="modal-dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Detalle de Alarmas.</h4>
</div>
<div class="modal-footer">
<a href="javascript:;" class="btn btn-sm btn-white" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
</div>
<!-- begin col-6 -->
<div class="col-md-6">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="form-validation-1">
<div class="panel-heading">
<div class="panel-heading-btn">
</div>
<h4 class="panel-title">Agregar Usuario</h4>
</div>
<div class="panel-body">
<form class="form-horizontal form-bordered" data-parsley-validate="true" name="demo-form" method="post" autocomplete="off">
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Nombre * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="nombre" name="nombre" placeholder="Required" data-parsley-required="true" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Alias * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="alias1" name="alias1" placeholder="Required" data-parsley-required="true" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Password * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="<PASSWORD>" id="pass1" name="pass1" placeholder="Required" data-parsley-required="true" autocomplete="off"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="email">Email * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="email" name="email" data-parsley-type="email" placeholder="Email" data-parsley-required="true" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Pais * :</label>
<div class="col-md-6 col-sm-6">
<select class="form-control selectpicker" data-size="10" data-live-search="true" data-style="btn-white" name="pais" id="pais";>
<?php
import::load('lib', 'MySQL');
$query = " select id_pais,descripcion
from pais
where estado = 1;";
$conexion = new MySQL(0);
$exec = $conexion->consulta($query);
while ($row2= $conexion->fetch_row($exec)){
echo "<option value= ".$row2[0]." >".$row2[1]."</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Rol * :</label>
<div class="col-md-6 col-sm-6">
<select class="form-control selectpicker" data-size="10" data-live-search="true" data-style="btn-white" name="rol" id="rol";>
<?php
import::load('lib', 'MySQL');
$query = " select id_rol,descripcion
from rol;";
$conexion = new MySQL(0);
$exec = $conexion->consulta($query);
while ($row2= $conexion->fetch_row($exec)){
echo "<option value= ".$row2[0]." >".$row2[1]."</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4"></label>
<div class="col-md-6 col-sm-6">
<button type="submit" class="btn btn-primary" onclick = "this.form.action = 'http://<?=URL.DS;?>usuario/save'">Submit</button>
</div>
</div>
</form>
<?php if (isset($_SESSION['value']) and ($_SESSION['value'] == "ok")) {unset($_SESSION['value']);?>
<div class="alert alert-success fade in m-b-15">
<strong>Success!</strong>
Usuario creado correctamente.
<span class="close" data-dismiss="alert">×</span>
</div>
<?php }?>
<?php if (isset($_SESSION['value']) and ($_SESSION['value'] == "error")) {unset($_SESSION['value']);?>
<div class="alert alert-danger fade in m-b-15">
<strong>error!</strong>
campos vacios!!!.
<span class="close" data-dismiss="alert">×</span>
</div>
<?php }?>
<?php if (isset($_SESSION['value']) and ($_SESSION['value'] == "error2")) {unset($_SESSION['value']);?>
<div class="alert alert-danger fade in m-b-15">
<strong>error!</strong>
El Alias que decea crear ya existe.
<span class="close" data-dismiss="alert">×</span>
</div>
<?php }?>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-6 -->
<!-- begin row -->
<div class="row">
<!-- begin col-12 -->
<div class="col-md-6">
<!-- begin panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-success" data-click="panel-reload"><i class="fa fa-repeat"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-warning" data-click="panel-collapse"><i class="fa fa-minus"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-danger" data-click="panel-remove"><i class="fa fa-times"></i></a>
</div>
<h4 class="panel-title">Detalle de Usuarios</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Usuario</th>
<th>Correo</th>
<th>Estado</th>
</tr>
</thead>
<tbody>
<?php
import::load('lib', 'MySQL');
$query = " Select usuario,email,status
from usuario;";
$conexion = new MySQL(0);
$exec = $conexion->consulta($query);
while ($row2= $conexion->fetch_row($exec)){
if ($row2[2] == "Activo"){$value = "Activo";}else{$value = "Baja";}
echo "<tr><td>$row2[0]</td><td>$row2[1]</td><td>".$value."</td></tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-12 -->
</div>
<!-- end row -->
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<script src="<?=WEBROOT.DS;?>js/ui-modal-notification.demo.min.js"></script>
</body>
</html>
<script src="<?=WEBROOT.DS;?>js/dashboard-v2.js"></script>
<?php include(TEMPLATE.DS.'footer.php');?>
<script>
$(document).ready(function() {
App.init();
TableManageDefault.init();
});
</script>
<file_sep>/Billing/app/modules/minimodules/guardia/guardiaL2.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/core/import.php');
import::load('lib', 'MySQL');
$conexion = new MySQL();
/*$user = 'openalonzo';
$password = '<PASSWORD>';
$server = '192.168.2.101\SQLMercurio';
$database = 'SMSNET_ADMIN';
$conexión = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
odbc_exec($conexión,"USE SMSNET_ADMIN");*/
//24A7FF
?>
<!-- ****************************** Inicio de reporte de colas ************************************* -->
<div class="box col-md-3">
<?php
$strConsulta = "select cantidad from monitor where id_servicio =1";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
/*$result = odbc_exec($conexión," select count(1) cont
from SMSNET_ADMIN..ServiceMonitor
where TelcoID != 0 and Severity != 0");
$var=odbc_fetch_object($result);*/
if($row['cantidad'] > 0){
?>
<span class="notification red">Alarmas <?=$row['cantidad']?></span>
<?php }else{?>
<span class="notification green">OK</span>
<?php }
//odbc_free_result($result);
?>
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>RX/TX Legacy</h2>
<div class="box-icon">
<a class="btn btn-setting btn-round btn-default" onclick="clickButton(1);"><i
class="glyphicon glyphicon-tasks"></i></a>
</div>
</div>
<div class="box-content" align="center">
<img src="<?=ROOT.DS?>img/RXTX.png" class="animated rubberBand" alt="Sample Image 1">
</div>
</div>
</div>
<!-- ****************************** Gateway ******************************************* -->
<div class="box col-md-3">
<?php
/*odbc_exec($conexión,"USE SMSNET_ADMIN;");
$result1 = odbc_exec($conexión,"exec ServiceMonitor_GetGatewayClients;");
$var= odbc_num_fields($result1);*/
$strConsulta = "select cantidad from monitor where id_servicio =2";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){
?>
<span class="notification red">Alarmas <?=$row['cantidad']?></span>
<?php }else{?>
<span class="notification green">OK</span>
<?php }
//odbc_free_result($result1);
?>
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Status Gateways</h2>
<div class="box-icon">
<a class="btn btn-setting btn-round btn-default" onclick="clickButton(2);"><i
class="glyphicon glyphicon-tasks"></i></a>
</div>
</div>
<div class="box-content" align="center">
<img src="<?=ROOT.DS?>img/gateway1.png" class="animated rubberBand" alt="Sample Image 1">
</div>
</div>
</div>
<!-- ****************************** Bae de datos Legacy ******************************************* -->
<div class="box col-md-3">
<?php
/*$result = odbc_exec($conexión," exec GetDatabaseStatus");
$var=0;
while ($r= odbc_fetch_object($result)){
if ($r->DatabaseStatus != 'ONLINE'){
$var++;
}
}
odbc_close($conexión);
if($var > 0){*/
$strConsulta = "select cantidad from monitor where id_servicio =3";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){
?>
<span class="notification red">Alarmas <?=$row['cantidad']?></span>
<?php }else{?>
<span class="notification green">OK</span>
<?php }?>
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Status DB Legacy</h2>
<div class="box-icon">
<a class="btn btn-setting btn-round btn-default" onclick="clickButton(3);"><i
class="glyphicon glyphicon-tasks"></i></a>
</div>
</div>
<div class="box-content" align="center">
<img src="<?=ROOT.DS?>img/database1.png" class="animated rubberBand" alt="Sample Image 1">
</div>
</div>
</div>
<file_sep>/Billing/app/templates/dashboard/dashboardMetricas.php
<?php
include(TEMPLATE.DS.'header.php');
include(MINMODULES.DS.'dashboard/metricas.php');
// TableMetricas.css
?>
<link href="<?=WEBROOT.DS;?>css/TableMetricas.css" rel="stylesheet" />
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin page-header -->
<h1 class="page-header">Metricas David <small>Detalle de transacciones por país</small></h1>
<!-- end page-header -->
<br></br>
<center >
<?php echo $IhaveSomeChargeInfo;?>
</center>
<br>
<br>
<div class="row">
<?php echo $HtmlCode;?>
</div>
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
</body>
</html>
<script src="<?=WEBROOT.DS;?>js/dashboard-v2.js"></script>
<?php include(TEMPLATE.DS.'footer.php');?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
<?php echo $JSCode;?>
}
$(window).resize(function(){
drawChart();
});
</script>
<script>
$(document).ready(function() {
App.init();
<?php
$var1 = WEBROOT.DS.'img/users/'.$_SESSION['login'].'.jpg';
if (file_exists($var1)) {
$nombreimg = $_SESSION['login'];
$nombreDisplay = $_SESSION['login'];
} else {
$nombreimg = 'default';
$nombreDisplay = $_SESSION['login'];
}
?>
var name = "<?php echo $nombreimg; ?>";
var nameD = "<?php echo $nombreDisplay; ?>";
<?php
if(isset($_SESSION['start'])){
unset($_SESSION['start']);
?>
DashboardV2.init(name,nameD);
<?php }?>
});
</script>
<file_sep>/Billing/app/templates/saecu/notificacionessaecu.php
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!-- begin #content -->
<div id="content" class="content">
<!-- begin page-header -->
<h1 class="page-header">Notificaciones <small>Busqueda de Notificaciones</small></h1>
<!-- end page-header -->
<!-- begin row -->
<div class="row">
<!-- begin col-6 -->
<div class="col-md-6">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="form-validation-1">
<div class="panel-heading">
<h4 class="panel-title">Ingrese Datos</h4>
</div>
<div class="panel-body panel-form">
<form method="POST" action="http://<?=URL.DS;?>detalle/notificacionessaecu" class="form-horizontal form-bordered" data-parsley-validate="true" name="demo-form">
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Productid* :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="fullname" name="username" placeholder="Required" data-parsley-required="true" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4">Seleccione Evento:</label>
<div class="col-md-6 col-sm-6">
<select class="form-control" id="select-required" name="supera" data-parsley-required="true">
<option value="">-- Eventos --</option>
<option value="renew">Renew</option>
<option value="active">Active</option>
<option value="active">OptOut</option>
<option value="cancelled">Cancelled</option>
<option value="pendingcharge">Pending Charge</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4"></label>
<div class="col-md-6 col-sm-6">
<button type="submit" class="btn btn-primary">Buscar</button>
</div>
</div>
</form>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-6 -->
<!-- begin col-6 -->
<div class="col-md-6">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="table-basic-7">
<div class="panel-heading">
<h4 class="panel-title">Detalle del Producto</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>ProductId</th>
<th>Nombre</th>
<th>Integrador</th>
<th>Estado</th>
<th>Pais</th>
</tr>
</thead>
<tbody>
<?php
require_once LIB.DS."MySQL.php";
if (isset($_POST["username"])) {
$busca = $_POST["username"];
} else {
$busca = "";
};
if (isset($_POST["supera"])) {
$evento=$_POST["supera"];
} else {
$evento = "";
};
$conexion = new MySQL(3);
$super="ecu_david";
if ($busca!=""){
$query ="select a.product_id , a.product_name, c.name,b.description,d.carrier_name
from $super.product_master a
join $super.product_status_master b on a.product_status_id = b.product_status_id
join $super.integratordetails c on a.integror_id =c.integrator_id
join $super.carrier_master d on d.carrier_id = c.carrier_id
where product_id = $busca";
$result= $conexion->consulta($query);
$row = $conexion->fetch_row($result);
echo "<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td><td>$row[4]</td>";
echo"</tbody>";};
?>
</table>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-6 -->
<!-- begin col-12 -->
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
</div>
<h4 class="panel-title">Detalle Notificaciones</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Url Integrador</th>
<th>Fecha</th>
<th>Event_Status</th>
<th>Notificaciones</th>
</tr>
</thead>
<?php
echo "<tbody>";
if ($busca!=""){
$query2 = "select * from $super.notification_retry_success
where event_status= \"$evento\" and created_date_time >= DATE_SUB(now(),INTERVAL 1 HOUR) and sample_data like \"%product_id=$busca%\" order by
created_date_time desc limit 25";
$result2= $conexion->consulta($query2);
while($row2= $conexion->fetch_row($result2)){
echo "<tr><td>$row2[2]</td><td>$row2[8]</td><td>$row2[5]</td><td>$row2[3]</td>";
};
echo"</tbody>";
} else {
echo "Ingrese Datos";};
?>
</table>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-12 -->
</div>
<!-- end row -->
</div>
<!-- end #content -->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<?php include(TEMPLATE.DS.'footer.php');?>
<script>
$(document).ready(function() {
App.init();
TableManageDefault.init();
});
</script>
</body>
</html>
<file_sep>/Billing/app/templates/usuario/usuario.php
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin breadcrumb -->
<!-- end breadcrumb -->
<!-- begin page-header -->
<h1 class="page-header">Altas De Usuarios<small></small></h1>
<!-- end page-header -->
<div class="row">
<div id="DavidMod"></div>
<!-- #modal-dialog -->
<div class="modal fade" id="modal-dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Detalle de Alarmas.</h4>
</div>
<div class="modal-footer">
<a href="javascript:;" class="btn btn-sm btn-white" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
</div>
<!-- begin col-6 -->
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="form-validation-1">
<div class="panel-heading">
<div class="panel-heading-btn">
</div>
<h4 class="panel-title">Creacion de usuarios</h4>
</div>
<div class="panel-body">
<form class="form-horizontal form-bordered" data-parsley-validate="true" name="demo-form">
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Nombre * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="fullname" name="fullname" placeholder="Required" data-parsley-required="true" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="website">Website :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="url" id="website" name="website" data-parsley-type="url" placeholder="url" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="email">Email * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="email" name="email" data-parsley-type="email" placeholder="Email" data-parsley-required="true" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Pais * :</label>
<div class="col-md-6 col-sm-6">
<select class="form-control selectpicker" data-size="10" data-live-search="true" data-style="btn-white" name="pais" id="pais";>
<?php
import::load('lib', 'MySQL');
$query = " select id_pais,nombre
from pais
where id_pais not in (
select id_pais
from super_agregador) and id_pais <> 1 and estado = 1;";
$conexion = new MySQL(0);
$exec = $conexion->consulta($query);
while ($row2= $conexion->fetch_row($exec)){
echo "<option value= ".$row2[0]." >".$row2[1]."</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="message">Message (20 chars min, 200 max) :</label>
<div class="col-md-6 col-sm-6">
<textarea class="form-control" id="message" name="message" rows="4" data-parsley-range="[20,200]" placeholder="Range from 20 - 200"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="message">Digits :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="digits" name="digits" data-parsley-type="digits" placeholder="Digits" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="message">Number :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="number" name="number" data-parsley-type="number" placeholder="Number" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="message">Phone :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="data-phone" data-parsley-type="number" placeholder="(XXX) XXXX XXX" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4"></label>
<div class="col-md-6 col-sm-6">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-6 -->
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<script src="<?=WEBROOT.DS;?>js/ui-modal-notification.demo.min.js"></script>
</body>
</html>
<script src="<?=WEBROOT.DS;?>js/dashboard-v2.js"></script>
<?php include(TEMPLATE.DS.'footer.php');?>
<script>
$(document).ready(function() {
App.init();
TableManageDefault.init();
});
</script>
<file_sep>/Billing/app/modules/minimodules/guardia/Monitoring2.php
<?php
$user = 'openalonzo';
$password = '<PASSWORD>';
$server = '192.168.2.101\SQLMercurio';
$database = 'SMSNET_ADMIN';
$conexión = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
odbc_exec($conexión,"USE SMSNET_ADMIN");
$body = "<div id='dashboard-clients' class='row' style='visibility: hidden; position: absolute;'>
<div class='row one-list-message'>
<div class='col-xs-1'><i class='fa fa-users'></i></div>
<div class='col-xs-2'><b>Serviciosasss</b></div>
<div class='col-xs-2'>Detalle del servicio</div>
<div class='col-xs-2'>Status</div>
</div>";
$result = odbc_exec($conexión," select *
FROM
OPENQUERY([192.168.3.11], 'EXEC WauReports.dbo.[GetMonitorService]')");
while ($r= odbc_fetch_object($result)){
$body = $body. "<div class='row one-list-message'>
<div class='col-xs-1'><i class='fa fa-user'></i></div>";
if(strlen($r->name)>30){
$body = $body. "<div class='col-xs-2'><b>".substr($r->name,0,30)."</b></div>";
$body = $body. "<div class='col-xs-2'>".$r->current_message."</div>";
$body = $body. "<div class='col-xs-2'>ERROR!!!</div>";
}else{
$body = $body. "<div class='col-xs-2'><b>".$r->name."</b></div>";
$body = $body. "<div class='col-xs-2'>".$r->current_message."</div>";
$body = $body. "<div class='col-xs-2'>ERROR!!!</div>";
}
}
$body = $body."</div>";
echo $body;
?>
<file_sep>/Billing/app/modules/database/database.php
<?php
import::load('lib', 'MySQL');
class database{
function __construct(){
$this->titulo = 'Billing Vas Pass';
$this->mensaje = '';
}
function start($mensaje){
if(self::check()){
if($_SESSION['access'] == 1){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("database/crear.php",$data);
}else{
$_SESSION['value'] = 'Acceso denegado';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function edit($mensaje){
if(self::check()){
if($_SESSION['access'] == 1){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("database/editar.php",$data);
}else{
$_SESSION['value'] = 'Acceso denegado';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function delete($mensaje){
if(self::check()){
if($_SESSION['access'] == 1){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("database/baja.php",$data);
}else{
$_SESSION['value'] = 'Acceso denegado';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function create_sa($mensaje){
if(self::check()){
if($_SESSION['access'] == 1){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("database/crear_sa.php",$data);
}else{
$_SESSION['value'] = 'Acceso denegado';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function generate($mensaje){
if(self::check()){
if($_SESSION['access'] == 1){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("database/generate.php",$data);
}else{
$_SESSION['value'] = 'Acceso denegado';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function down($mensaje){
if(self::check()){
if($_SESSION['access'] == 1){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("database/baja_g.php",$data);
}else{
$_SESSION['value'] = 'Acceso denegado';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'down'));
}
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function profile($mensaje){
if(self::check()){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("login/profile.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function save(){
if( (isset($_POST["descripcion"])) and (isset($_POST["host"])) and (isset($_POST["user"])) and (isset($_POST["pass"]))
and ($_POST["descripcion"] != '') and ($_POST["host"] != '') and ($_POST["user"] != '') and ($_POST["pass"] != '')){
$conexion = new MySQL(0);
$strIngreso = " insert into billing.bases_cobro (id_base,descripcion,host_conexion,user,pass)
values(null,'".$_POST["descripcion"]."','".$_POST["host"]."','".$_POST["user"]."','".$_POST["pass"]."');";
$value = $conexion->consulta($strIngreso);
$conexion->MySQLClose();
$_SESSION['value'] = "ok";
session_write_close();
exit(header( 'Location: http://'.URL.DS.'database'.DS.'start'));
}else{
exit(header( 'Location: http://'.URL.DS.'database'.DS.'start'));
}
}
function refresh(){
if( (isset($_POST["descripcion"])) and (isset($_POST["host"])) and (isset($_POST["user"])) and (isset($_POST["pass"]))
and ($_POST["descripcion"] != '') and ($_POST["host"] != '') and ($_POST["user"] != '') and ($_POST["pass"] != '')){
$conexion = new MySQL(0);
$strIngreso = ' update billing.bases_cobro
set descripcion = "'.$_POST["descripcion"].'", host_conexion = "'.$_POST["host"].'", user = "'.$_POST["user"].'", pass = "'.$_POST["pass"].'"
where id_base = '.$_POST["combo"].';' ;
//echo "\n\n".$strIngreso."\n\n";
$value1 = $conexion->consulta($strIngreso);
$conexion->MySQLClose();
$_SESSION['value'] = 'ok';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'database'.DS.'edit'));
}else{
//$_SESSION['value'] = 'error';
//session_write_close();
exit(header( 'Location: http://'.URL.DS.'database'.DS.'edit'));
}
}
function disable(){
if ( (isset($_POST["key"])) and (isset($_POST["key2"])) ){
$conexion = new MySQL(0);
$strIngreso = "update servicio set estado = ".$_POST["key2"]." where Id_servicio = '".$_POST["key"]."';" ;
$value = $conexion->consulta($strIngreso);
$conexion->MySQLClose();
$_SESSION['value'] = 'El usuario fue dado de baja.';
session_write_close();
echo 'http://'.URL.DS.'servicio'.DS.'delete';
//exit(header( 'Location: http://'.URL.DS.'servicio'.DS.'delete'));
}else{
$_SESSION['value'] = "error";
session_write_close();
echo 'http://'.URL.DS.'servicio'.DS.'delete';
//exit(header( 'Location: http://'.URL.DS.'servicio'.DS.'delete'));
}
}
function save_sa(){
if( (isset($_POST["descripcion"])) and (isset($_POST["pais"]))
and ($_POST["descripcion"] != '') and ($_POST["pais"] != '')){
$conexion = new MySQL(0);
$strIngreso = "call CheckIfTableExist('".strtolower($_POST["descripcion"])."');";
$execute = $conexion->consulta($strIngreso);
$exist = $conexion->fetch_row($execute);
$conexion->MySQLClose();
echo "1";
if ($exist[0] == 0){
$conexion = new MySQL(0);
$strIngreso = "call CheckIfTableExist('".strtolower($_POST["descripcion"])."_i');";
$execute2 = $conexion->consulta($strIngreso);
$exist2 = $conexion->fetch_row($execute2);
$conexion->MySQLClose();
echo "2";
if ($exist2[0] == 0){
$conexion = new MySQL(0);
$strIngreso = "call CreateTables('".strtolower($_POST["descripcion"])."');";
$execute = $conexion->consulta($strIngreso);
$conexion->MySQLClose();
echo "3";
$conexion = new MySQL(0);
$strIngreso = "insert into billing.carrier (id_carrier,descripcion, nombre) values(null,'".strtoupper($_POST["descripcion"])."','".strtoupper($_POST["pais"])."');";
$execute = $conexion->consulta($strIngreso);
$conexion->MySQLClose();
echo "4";
$_SESSION['value'] = "ok";
}else{$_SESSION['value'] = "error1";}
}else{$_SESSION['value'] = "error1";}
session_write_close();
exit(header( 'Location: http://'.URL.DS.'database'.DS.'create_sa'));
}else{
exit(header( 'Location: http://'.URL.DS.'database'.DS.'create_sa'));
}
}
function disable_sa(){
if ( (isset($_POST["key"])) and (isset($_POST["key2"])) ){
$conexion = new MySQL(0);
$strIngreso = "update cobro_carrier set estatus = ".$_POST["key2"]." where id_cobro_carrier = '".$_POST["key"]."';" ;
$value = $conexion->consulta($strIngreso);
$conexion->MySQLClose();
$_SESSION['value'] = 'El servicio fue dado de baja.';
session_write_close();
echo 'http://'.URL.DS.'database'.DS.'down';
//exit(header( 'Location: http://'.URL.DS.'servicio'.DS.'delete'));
}else{
$_SESSION['value'] = "error";
session_write_close();
echo 'http://'.URL.DS.'database'.DS.'down';
//exit(header( 'Location: http://'.URL.DS.'servicio'.DS.'delete'));
}
}
function display_sa(){
if ( (isset($_POST["key3"])) and (isset($_POST["key4"])) ){
$conexion = new MySQL(0);
$strIngreso = "update cobro_carrier set display_graph = ".$_POST["key4"]." where id_cobro_carrier = '".$_POST["key3"]."';" ;
$value = $conexion->consulta($strIngreso);
$conexion->MySQLClose();
$_SESSION['value'] = 'El servicio fue dado de baja.';
session_write_close();
echo 'http://'.URL.DS.'database'.DS.'down';
//exit(header( 'Location: http://'.URL.DS.'servicio'.DS.'delete'));
}else{
$_SESSION['value'] = "error";
session_write_close();
echo 'http://'.URL.DS.'database'.DS.'down';
//exit(header( 'Location: http://'.URL.DS.'servicio'.DS.'delete'));
}
}
function save_g(){
if( (isset($_POST["carrier"])) and (isset($_POST["host"])) and (isset($_POST["esquema"])) and (isset($_POST["tabla"])) and (isset($_POST["campo"])) and (isset($_POST["cond"]))
and ($_POST["carrier"] != '') and ($_POST["host"] != '') and ($_POST["esquema"] != '') and ($_POST["tabla"] != '') and ($_POST["campo"] != '') and ($_POST["cond"] != '')){
$conexion = new MySQL(0);
$strIngreso = " insert into billing.cobro_carrier (id_cobro_carrier,id_carrier,id_base,esquema,tabla,condicion,estatus,field_sum)
values (null,".$_POST["carrier"].",".$_POST["host"].",'".$_POST["esquema"]."','".$_POST["tabla"]."','".$_POST["cond"]."',1,'".$_POST["campo"]."');";
$value = $conexion->consulta($strIngreso);
$conexion->MySQLClose();
$_SESSION['value'] = "ok";
session_write_close();
exit(header( 'Location: http://'.URL.DS.'database'.DS.'generate'));
}else{
exit(header( 'Location: http://'.URL.DS.'database'.DS.'generate'));
}
}
private function check(){
return Validate_Auth::check();
}
private function LoadTemplate($template, $dataArr){
if (file_exists(TEMPLATE.DS.$template)){
Validate_Auth::start();
$view = new view($template);
if (!empty($dataArr)){
$view->render($dataArr);
}else{
$tempArr = array('NO' => 'DATA');
$view->render($tempArr);
}
}else{
echo 'Error!!! el template al que deseas accesar no existe. ';
echo $template;
}
}
}
?><file_sep>/Billing/app/templates/basic/CarrierD_Billing (copy).php
<!--Begin Grafica CarrierD_Billing-->
<?php
require_once LIB.DS."MySQL.php";
//include(MINMODULES.DS.'detalle/metricas_int.php');
?>
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin breadcrumb -->
<ol class="breadcrumb hidden-print pull-right">
<li><a href="javascript:;">Home</a></li>
<li class="active">Billing</li>
</ol>
<!-- end breadcrumb -->
<!-- begin page-header -->
<h1 class="page-header hidden-print">Billing <small>Detalle de cobros...</small></h1>
<!-- end page-header -->
<!-- begin invoice -->
<div class="invoice">
<div class="invoice-company">
<span class="pull-right hidden-print">
<a href="javascript:;" onclick="window.print()" class="btn btn-sm btn-success m-b-10"><i class="fa fa-print m-r-5"></i> Print</a>
</span>
Super Agregador: <?php echo strtoupper($name1);?>
</div>
<div class="invoice-header">
<div class="invoice-from">
<address class="m-t-5 m-b-5">
<strong><NAME> S.A.</strong><br />
Diagonal 6, 12-42, Edificio Design Center Z-10<br />
Guatemala/Guatemala<br />
Phone: (502) 2503-0000<br />
</address>
</div>
<div class="invoice-date">
<small>Billing / <?php echo date("M");?></small>
<div class="date m-t-5"><?php echo date('l jS \of F Y');?></div>
<div class="invoice-detail">
Detalle cobro
</div>
</div>
</div>
<div class="invoice-content">
<div class="table-responsive">
<table class="table table-invoice">
<thead>
<tr>
<th>Nombre del Integrador</th>
<th style="text-align: right;">Gross</th>
<th style="text-align: right;">Earning</th>
</tr>
</thead>
<tbody>
<?php
$totalE = 0;
$totalG = 0;
$conexion = new MySQL(0);
$query = ' select name,sum(gross)
from '.$name1.'_billing
where created_date = date(date_add(now(), interval -30 hour))
group by name
order by sum(gross) desc;';
$exec = $conexion->consulta($query);
while ($row2= $conexion->fetch_row($exec)){
$totalG = $totalG + $row2[1];
echo "<tr><td> Integrador".strtoupper($row2[0]).'</td><td style="text-align: right;">$'.number_format($row2[1],2,'.','').'</td><td style="text-align: right;">$'.number_format(($row2[1]*0.01349999116),2,'.','')."</td></tr>";
$totalE = $totalE + ($row2[1]*0.01349999116);
}
?>
</tbody>
</table>
</div>
<div class="invoice-price">
<div class="invoice-price-left">
<div class="invoice-price-row">
<div class="sub-price">
<small>Gross USD</small>
<?php echo "$".number_format($totalG,2,'.','');?>
</div>
</div>
</div>
<div class="invoice-price-right">
<small>TOTAL Earning</small> <?php echo "$".number_format($totalE,2,'.','');?>
</div>
</div>
</div>
<div class="invoice-note">
* Los valores de cobros son referenciales.<br />
* El Gross es generado en base a la tarifa sin IVA<br />
</div>
<div class="invoice-footer text-muted">
<p class="text-center m-b-5">
THANK YOU FOR YOUR BUSINESS
</p>
<p class="text-center">
<span class="m-r-10"><i class="fa fa-globe"></i> www.waumovil.com</span>
<span class="m-r-10"><i class="fa fa-phone"></i> T:(502) 2503-0000</span>
<span class="m-r-10"><i class="fa fa-envelope"></i> <EMAIL></span>
</p>
</div>
</div>
<!-- end invoice -->
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<?php include(TEMPLATE.DS.'footer.php');?>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/ionRangeSlider/js/ion-rangeSlider/ion.rangeSlider.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-colorpicker/js/bootstrap-colorpicker.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/masked-input/masked-input.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-timepicker/js/bootstrap-timepicker.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/password-indicator/js/password-indicator.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-combobox/js/bootstrap-combobox.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-select/bootstrap-select.min.js"></script>
<script>
$(document).ready(function() {
App.init();
});
</script>
</body>
</html><file_sep>/Billing/app/modules/login/login.php
<?php
import::load('lib', 'Validate_Auth');
import::load('lib', 'Start_Page');
import::load('lib', 'Session');
import::load('lib', 'MySQL');
import::load('lib', 'view');
class Login{
function __construct(){
$this->titulo = 'Billing Vas Pass';
$this->mensaje = '';
}
function start($mensaje){
if(self::check()){
exit(header( 'Location: '.self::GoHome()));
//exit(header( 'Location: '.$_SESSION['home']));
}else{
$data = array("Titulo" => "Billing Vas-Pass", "mensaje" => $mensaje);
self::LoadTemplate("login/login.php",$data);
}
}
function Error404($mensaje){
if(self::check()){
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}else{
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("404/404.php",$data);
}
}
function check(){
return Validate_Auth::check();
}
function enter(){
import::load('lib', 'Validar');
}
function login($user,$pass){
return Validate_Auth::login($user, $pass);
}
function logout(){
Validate_Auth::logout();
exit(header( 'Location: http://'.URL.DS));
}
function islogged($user){
return Validate_Auth::getlogged($user);
}
function GoHome(){
$conexion = new MySQL(0);
$query = 'call GetHomeURL('.$_SESSION['pais'].');';
$result1 = $conexion->consulta($query);
$row = $conexion->fetch_row($result1);
$conexion->MySQLClose();
switch ($_SESSION['access']) {
case 1:
case 2:
case 3:
$home = 'http://'.URL.DS.'dashboard'.DS.'metricas';
break;
default:
$home = 'http://'.URL.DS.$row[0];
break;
}
return $home;
}
function LoadTemplate($template, $dataArr){
if (file_exists(TEMPLATE.DS.$template)){
Validate_Auth::start();
$view = new view($template);
if (!empty($dataArr)){
$view->render($dataArr);
}else{
$tempArr = array('NO' => 'DATA');
$view->render($tempArr);
}
}else{
echo 'Error!!! el template al que deseas accesar no existe. ';
echo $template;
}
}
}
?><file_sep>/Billing/app/modules/minimodules/guardia/Servicios.php
<?php
$body = '
<!-- begin row -->
<div class="row">
<!-- begin col-12 -->
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<div class="panel-heading-btn">
</div>
<h4 class="panel-title">Data Table - Default</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Nombre del Servido</th>
<th>App Server</th>
<th>Throughput</th>
<th>Error %</th>
</tr>
</thead>
<tbody>';
$curl = curl_init('https://api.newrelic.com/v2/applications.json');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-Api-Key:7157dea6a415fe0c854831ef8b65f8adcdbd825ca5274e4",
"Content-Type: application/json"
)
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
$applications = json_decode($resp,true);
curl_close($curl);
$var = 0;
for($i=0;$i<count($applications['applications']);$i++){
if($applications['applications'][$i]['health_status'] != 'green'){
$var++;
$body = $body. "<tr><td>";
switch ($applications['applications'][$i]['health_status']) {
case 'green':
$body = $body. '<span class="label label-success">'.$applications['applications'][$i]['name'].'</span></td>';
break;
case 'orange':
$body = $body. '<span class="label label-warning">'.$applications['applications'][$i]['name'].'</span></td>';
break;
case 'red':
$body = $body. '<span class="label-default label label-danger">'.$applications['applications'][$i]['name'].'</span></td>';
break;
case "gray":
$body = $body. '<span class="label-default label">'.$applications['applications'][$i]['name'].'</span></td>';
break;
}
if (isset($applications['applications'][$i]['application_summary']['response_time'])){
$body = $body. '<td>';
$body = $body. $applications['applications'][$i]['application_summary']['response_time'].'ms </td>';
}else{$body = $body. '<td class="center">N/A</td>';}
if (isset($applications['applications'][$i]['application_summary']['throughput'])){
$body = $body. '<td >';
$body = $body. $applications['applications'][$i]['application_summary']['throughput'].'rpm </td>';
}else{$body = $body. '<td >N/A</td>';}
if (isset($applications['applications'][$i]['application_summary']['error_rate'])){
$body = $body. '<td>';
$body = $body. $applications['applications'][$i]['application_summary']['error_rate'].'% ';
}else{$body = $body. '<td >N/A';}
$body = $body. "</td></tr>";
}
}
$body = $body.'</tbody>
</table>';
if ($var < 1){
$body = $body. '<tr> <div align="center">
<h5>No hay servicios alarmados</h5>
<ul class="ajax-loaders">
<li><img src="'.ROOT.DS.'img/ajax-loaders/ajax-loader-9.gif"
title="img/ajax-loaders/ajax-loader-9.gif"></li>
</ul>
</div></tr>';
}
$body = $body.'
</tbody>
</table>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-12 -->
</div>
<!-- end row -->';
echo $body;
?><file_sep>/Billing/app/templates/database/baja.php
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');
if(isset($_POST['combo'])){$valor=$_POST['combo'];unset($_POST['combo']);}else{$valor = 0;}
?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin breadcrumb -->
<!-- end breadcrumb -->
<!-- begin page-header -->
<h1 class="page-header">Altas/Bajas Servicio<small></small></h1>
<!-- end page-header -->
<div class="row">
<div id="DavidMod"></div>
<!-- #modal-dialog -->
<div class="modal fade" id="modal-dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Detalle de Alarmas.</h4>
</div>
<div class="modal-footer">
<a href="javascript:;" class="btn btn-sm btn-white" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
</div>
<!-- begin row -->
<div class="row">
<!-- begin col-12 -->
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-success" data-click="panel-reload"><i class="fa fa-repeat"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-warning" data-click="panel-collapse"><i class="fa fa-minus"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-danger" data-click="panel-remove"><i class="fa fa-times"></i></a>
</div>
<h4 class="panel-title">Detalle de Servicios</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Descripcion</th>
<th>Ruta</th>
<th>Estado</th>
<th>Accion</th>
</tr>
</thead>
<tbody>
<?php
import::load('lib', 'MySQL');
$query = " Select descripcion,ruta,estado,id_servicio
from servicio;";
$conexion = new MySQL(0);
$exec = $conexion->consulta($query);
while ($row2= $conexion->fetch_row($exec)){
if ($row2[2] == 1){$value = "Activo"; $upd = 0;}else{$value = "Baja"; $upd = 1;}
echo "<tr><td>$row2[0]</td><td>$row2[1]</td><td>".$value.'</td><td align="center"><a onclick="seleccion('.$row2[3].','.$upd.')"class="btn btn-';
if ($row2[2] == 1){echo 'danger btn-icon btn-circle btn-xs"><i class="fa fa-times"></i></a></td></tr>';}
else{echo 'success btn-icon btn-circle btn-xs"><i class="fa fa-repeat"></i></a></td></tr>';}
}
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-12 -->
</div>
<!-- end row -->
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<script src="<?=WEBROOT.DS;?>js/ui-modal-notification.demo.min.js"></script>
</body>
</html>
<script src="<?=WEBROOT.DS;?>js/dashboard-v2.js"></script>
<?php include(TEMPLATE.DS.'footer.php');?>
<script>
$(document).ready(function() {
App.init();
TableManageDefault.init();
FormPlugins.init();
});
function seleccion(opcion,upd) {
$.post('disable', { key: opcion, key2: upd}).done(function(data) {
location.href=data;
});
}
</script>
<file_sep>/Billing/app/modules/menu/menuSA.php
<?php
$conexion = new MySQL(0);
if (($_SESSION['access'] == 4) or ($_SESSION['access'] == 5))
{
$query = 'CALL GetMenuListLimit('.$_SESSION['pais'].');';
}else{
$query = 'CALL GetMenuList();';
}
$result = $conexion->consulta($query);
$HtmlMenuCode = '';
$conexion->prepareNextResult();
if(! $result){
throw new Exception ("No se logro obtener informacion de cobros....\n");
}else{
while ($carrier = $conexion->fetch_row($result)){
$optionActive = (strpos(strtolower($actual_link),strtolower($carrier[1]))) ? 'class="has-sub active"' : 'class="has-sub "';
$HtmlMenuCode = $HtmlMenuCode."\n\t\t\t\t\t"."<li ".$optionActive.">"."\n";
$HtmlMenuCode = $HtmlMenuCode."\t\t\t\t\t\t".'<a href="javascript:;">'."\n";
$HtmlMenuCode = $HtmlMenuCode."\t\t\t\t\t\t\t".'<b class="caret pull-right"></b>'."\n";
$HtmlMenuCode = $HtmlMenuCode."\t\t\t\t\t\t\t".'<i class="fa fa-line-chart"></i>'."\n";
$HtmlMenuCode = $HtmlMenuCode."\t\t\t\t\t\t\t".'<span>'.$carrier[1].'</span>'."\n";
$HtmlMenuCode = $HtmlMenuCode."\t\t\t\t\t\t".'</a>'."\n";
$HtmlMenuCode = $HtmlMenuCode."\t\t\t\t\t\t".'<ul class="sub-menu">'."\n";
$Level = GetSecondLevel($carrier[0],$actual_link);
$HtmlMenuCode = $HtmlMenuCode.$Level;
$HtmlMenuCode = $HtmlMenuCode."\t\t\t\t\t\t".'</ul>'."\n";
$HtmlMenuCode = $HtmlMenuCode."\t\t\t\t\t"."</li>"."\n";
}
}
$conexion->MySQLClose();
echo $HtmlMenuCode;
function GetSecondLevel($carrier,$al){
$conexion1 = new MySQL(0);
if ($_SESSION['access'] == 5)
{
$query = 'call GetSubMenuLimits('.$carrier.');';
}else{
$query = 'call GetSubMenu('.$carrier.');';
}
$result = $conexion1->consulta($query);
$miniBody = '';
while ($link = $conexion1->fetch_row($result)){
$urlC = ($link[2] == 1) ? 'http://'.URL.DS.$link[0] : $link[0];
$IamHere = ($al == $urlC) ? 'class="active""': '';
if ($link[2] == 1){
$miniBody = $miniBody."\t\t\t\t\t\t\t".'<li '.$IamHere.'><a href="'.$urlC.'">'.$link[1].'</a></li>'."\n";
}else{
$miniBody = $miniBody."\t\t\t\t\t\t\t".'<li ><a href="'.$urlC.'" target="_blank">'.$link[1].'</a></li>'."\n";
}
}
$conexion1->MySQLClose();
return $miniBody;
}
?><file_sep>/Billing/app/modules/minimodules/guardia/Chargins.php
<?php
$user = 'openalonzo';
$password = '<PASSWORD>';
$server = '192.168.3.11';
$database = 'WauReports';
$conexión = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
odbc_exec($conexión,"USE WauReports");
$body = "<div class=\"box col-md-12\">
<div class=\"box-inner\">
<div class=\"box-header well\" data-original-title=\"\">
<h2>Servicios Monitoring</h2>
</div>
<div class=\"box-content\">
<table class=\"table table-striped table-bordered bootstrap-datatable datatable responsive\" style=\"width:100%\">
<thead>
<tr>
<th>Super Agregador</th>
<th>Cobros Hoy</th>
<th>Promedio</th>
<th>Porcentaje</th>
</thead>
</tr>
<tbody>";
$result = odbc_exec($conexión," EXEC [GetChargesSA]");
$r= odbc_fetch_object($result);
$result2 = odbc_exec($conexión," EXEC [GetpercentageSA]");
$r2= odbc_fetch_object($result2);
$body = $body. "<tr><td class=\"center\"> SAMEX </td><td class=\"center\">".$r->SAMEX."</td><td class=\"center\">".$r2->SAMEX."</td><td class=\"center\">".(($r->SAMEX*100)/$r2->SAMEX);
$body = $body. "%</td></tr>";
$body = $body. "<tr><td class=\"center\"> SAPER </td><td class=\"center\">".$r->SAPER."</td><td class=\"center\">".$r2->SAPER."</td><td class=\"center\">".(($r->SAPER*100)/$r2->SAPER);
$body = $body. "%</td></tr>";
$body = $body. "<tr><td class=\"center\"> SANIC </td><td class=\"center\">".$r->SANIC."</td><td class=\"center\">".$r2->SANIC."</td><td class=\"center\">".(($r->SANIC*100)/$r2->SANIC);
$body = $body. "%</td></tr>";
$body = $body. "<tr><td class=\"center\"> SAECU </td><td class=\"center\">".$r->SAECU."</td><td class=\"center\">".$r2->SAECU."</td><td class=\"center\">".(($r->SAECU*100)/$r2->SAECU);
$body = $body. "%</td></tr>";
$body = $body. "<tr><td class=\"center\"> SAPAN </td><td class=\"center\">0</td><td class=\"center\">0</td><td class=\"center\">0";
$body = $body. "%</td></tr>";
$body = $body."</tbody>
</table>
</div>
</div>
</div>";
echo $body;
?><file_sep>/Billing/app/webroot/img/crear.php
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin breadcrumb -->
<ol class="breadcrumb pull-right">
</ol>
<!-- end breadcrumb -->
<!-- begin page-header -->
<h1 class="page-header">Servicios <small>Detalle de servicios alarmados para Legacy y David</small></h1>
<!-- end page-header -->
<div class="row">
<div id="DavidMod"></div>
<!-- #modal-dialog -->
<div class="modal fade" id="modal-dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Detalle de Alarmas.</h4>
</div>
<div class="modal-body" id="alerta">
todavia no esta mongol!!!!
ya eran las 2am
sigo al rato,
fin del mensaje.....
pd: chupela XD
</div>
<div class="modal-footer">
<a href="javascript:;" class="btn btn-sm btn-white" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<script src="<?=ROOT.DS;?>js/ui-modal-notification.demo.min.js"></script>
</body>
</html>
<script src="<?=ROOT.DS;?>js/dashboard-v2.js"></script>
<?php include(TEMPLATE.DS.'footer.php');?>
<script>
$(document).ready(function() {
App.init();
Notification.init();
TableManageDefault.init();
var name = "<?php echo $_SESSION['login'];?>";
DashboardV2.init(name);
});
</script><file_sep>/Billing/app/templates/login/profile.php
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin breadcrumb -->
<ol class="breadcrumb pull-right">
</ol>
<!-- end breadcrumb -->
<!-- begin page-header -->
<h1 class="page-header">Perfil de Usuario <small></small></h1>
<!-- end page-header -->
<div class="row">
<div id="DavidMod"></div>
<div class="box col-md-12">
<div class="box-inner">
<div class="box-content">
<!--img class="media-object rounded-corner" alt="" src=<?php echo WEBROOT.DS.'img/users/'.$_SESSION['login'].'.jpg';?> /-->
<!-- begin col-6 -->
<?php
$conexion1 = new MySQL(0);
$u = $_SESSION['login'];
$strConsulta = "select usuario,nombre,email
FROM usuario
where usuario = '$u'";
$consulta1 = $conexion1->consulta($strConsulta);
$row= $conexion1->fetch_array($consulta1);
?>
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="form-stuff-1">
<div class="panel-heading">
<div class="panel-heading-btn">
</div>
<h4 class="panel-title">Datos de la cuenta</h4>
</div>
<div class="panel-body">
<form class="form-horizontal" method ='POST' autocomplete="off">
<ul class="chats">
<li class="left">
<a href="javascript:;" class="image"><img alt="" src=<?php echo WEBROOT.DS.'img/users/'.$_SESSION['login'].'.jpg';?> /></a>
</li>
</ul>
<div class="form-group">
<label class="col-md-3 control-label">Usuario</label>
<div class="col-md-9">
<input type="text" value=<?=$row[0]?> class="form-control" placeholder="Disabled input" disabled />
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Nombre del Usuario</label>
<div class="col-md-9">
<input type="text" value=<?=$row[1]?> class="form-control" placeholder="Disabled input" disabled />
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Correo</label>
<div class="col-md-9">
<input type="text" value=<?=$row[2]?> class="form-control" placeholder="Disabled input" disabled />
</div>
</div>
<h4>Cambio de contraseña</h4>
<div class="form-group">
<label class="col-md-3 control-label">Contraseña anterior</label>
<div class="col-md-9">
<input type="password" class="form-control" name="pass2" id="exampleInput<PASSWORD>" placeholder="<PASSWORD>" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Contraseña Nueva</label>
<div class="col-md-9">
<input type="password" class="form-control" name="pass" id="exampleInput<PASSWORD>" placeholder="<PASSWORD>" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Repetir Contraseña Nueva</label>
<div class="col-md-9">
<input type="password" class="form-control" name="pass1" id="exampleInput<PASSWORD>1" placeholder="<PASSWORD>" />
</div>
</div>
<?php
if(isset($_SESSION['value'])){$mensaje=$_SESSION['value']; unset($_SESSION['value']);}else{$mensaje=' ';}
switch ($mensaje){
case "error":
?>
<div class="box-content alerts">
<div class="alert alert-danger">
<center><strong>Error!</strong> Uno a varios campos se encuentran vacios.</center>
</div>
</div>
<?php
break;
case "error2":
?>
<div class="box-content alerts">
<div class="alert alert-danger">
<center><strong>Error!</strong> contraseñas ingresadas son distintas.</center>
</div>
</div>
<?php
break;
case "error3":
?>
<div class="box-content alerts">
<div class="alert alert-danger">
<center><strong>Error!</strong> La contraseña debe ser distinta a la actual</center>
</div>
</div>
<?php
break;
}
?>
<center><button type="submit" class="btn btn-sm btn-primary m-r-5" onclick = "this.form.action = 'http://<?=URL.DS;?>usuario/save1'">Guardar Cambios</button></center>
</form>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-6 -->
</div>
</div>
</div>
<!-- #modal-dialog -->
<div class="modal fade" id="modal-dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Detalle de Alarmas.</h4>
</div>
<div class="modal-body" id="alerta">
todavia no esta mongol!!!!
ya eran las 2am
sigo al rato,
fin del mensaje.....
pd: chupela XD
</div>
<div class="modal-footer">
<a href="javascript:;" class="btn btn-sm btn-white" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<script src="<?=WEBROOT.DS;?>js/ui-modal-notification.demo.min.js"></script>
</body>
</html>
<script src="<?=WEBROOT.DS;?>js/dashboard-v2.js"></script>
<?php include(TEMPLATE.DS.'footer.php');?>
<script>
$(document).ready(function() {
App.init();
Notification.init();
TableManageDefault.init();
var name = "<?php echo $_SESSION['login'];?>";
<?php if(isset($_SESSION['start'])){
unset($_SESSION['start']);
?>
DashboardV2.init(name);
<?php }?>
});
</script><file_sep>/Billing/app/templates/basic/carrierD.php
<!--Begin Grafica SAECU-->
<?php
require_once LIB.DS."MySQL.php";
include(MINMODULES.DS.'detalle/metricas.php');
?>
<!--End Grafica SAECU -->
<!-- BEGIN Chart2 SAECU -->
<?php
$meses= array('','Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sept','Oct','Nov','Dic');
for($x=1;$x<=12;$x=$x+1){
$dinero[$x]=0;
}
$anno=date('Y');
$conexion = new MySQL(0);
$query3 = 'select max(cantidad) as "total", fecha
from '.$name1.'
group by fecha';
$resultfox= $conexion->consulta($query3);
while($rfox= $conexion->fetch_row($resultfox)){
$y=date('Y', strtotime($rfox[1]));
$mes=(int)date('m', strtotime($rfox[1]));
if ($y==$anno){
$dinero[$mes]=$dinero[$mes]+$rfox[0];
}
};
?>
<!-- END Chart2 SAECU -->
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin page-header -->
<h1 class="page-header"><?php echo strtoupper($name1);?> <small>Detalle General Movistar <?php echo $pais;?></small></h1>
<!-- end page-header -->
<div class="row">
<!-- begin col-4 -->
<div class="col-md-4">
<!-- BEGIN CarrierD -->
<div class="panel panel-inverse" data-sortable-id="ui-buttons-2">
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
</div>
<h4 class="panel-title"><?php echo strtoupper($pais);?></h4>
</div>
<div class="panel-body">
<div id="CarrierD" class="height-sm"></div>
</div>
</div>
<!-- END CarrierD -->
<!-- BEGIN TOTALES POR MES -->
<div class="panel panel-inverse" data-sortable-id="ui-buttons-2">
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
</div>
<h4 class="panel-title">Cobros Mensuales</h4>
</div>
<div class="panel-body">
<div id="ex0" class="height-sm"></div>
</div>
</div>
<!-- END TOTALES POR MES -->
</div>
<!-- end col-4 -->
<!-- begin col-8 Integradores -->
<div class="col-md-8">
<!--Begin Panel Promedios-->
<div class="panel panel-inverse" data-sortable-id="table-basic-7">
<div class="panel-heading">
<h4 class="panel-title">Transacciones</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Plataforma</th>
<th>Cobros Hoy</th>
<th>Promedio de Cobros</th>
<th>Porcentaje del Dia</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo strtoupper($name1);?></td>
<?php
$conexion = new MySQL($bd_id);
$query = 'select sum(qty) Cobros
from '.$schema.'.resume_carrier
where created_date >= left(NOW() - INTERVAL 6 HOUR,10) and type in ("DB") and status = "Success"';
$exec = $conexion->consulta($query);
$row = $conexion->fetch_row($exec);
$value = $row[0];
$query = 'select sum(qty) Cobros_ECU
from '.$schema.'.resume_carrier
where created_date between left((CURDATE() - INTERVAL 168 HOUR),10) and left((CURDATE()) - INTERVAL 6 HOUR,10)
and type in ("DB") and status = "Success"';
$exec = $conexion->consulta($query);
$row = $conexion->fetch_row($exec);
$value2 = $row[0]/7;
$value3 = ($value2 == 0) ? 0 : (($value*100)/$value2);
echo"<td>".number_format($value)."</td><td align=\"center\">".number_format($value2)."</td>";
echo"<td align=\"left\">".number_format($value3)."%</td>";
?>
</tr>
</tbody>
</table>
</div>
<small>* Los valores de cobros son referenciales.</small>
</div>
</div>
<!-- End Panel Promedios-->
<!--Begin Panel Integradores-->
<div class="panel panel-inverse" data-sortable-id="ui-buttons-1"->
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
</div>
<h4 class="panel-title">Integradores</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table69" class="table table-striped table-bordered">
<thead>
<tr>
<th>Id_Integrador</th>
<th>Nombre</th>
<th>Productos</th>
<th>Cobros Hoy</th>
<!-- <th>Mensajes MT</th> -->
<!-- <th>Cobros</th> -->
</tr>
</thead>
<?php
$conexion = new MySQL($bd_id);
$query2 = 'select a.integrator_id, b.name, c.cuenta, sum(a.qty)as "total"
from '.$schema.'.resume_carrier a
join '.$schema.'.integratordetails b on a.integrator_id = b.integrator_id
join(select integror_id as integror_id, count(product_id) as "cuenta"
from '.$schema.'.product_master
group by integror_id ) c on a.integrator_id = c.integror_id
where a.created_date >= left(NOW() - INTERVAL 6 HOUR,10) and a.type in ("DB") and a.status = "Success"
group by a.integrator_id';
$resultfox2= $conexion->consulta($query2);
echo "<tbody>";
while($row2= $conexion->fetch_row($resultfox2)){
echo "<tr><td>$row2[0]</td><td><a onclick=\"GotoDetails($row2[0])\">$row2[1]<a></td><td>$row2[2]</td><td>".number_format($row2[3])."</td></tr>";
};
echo"</tbody>"?>
</table>
</div>
</div>
</div>
<!-- End Panel Integradores-->
</div>
<!-- end col-8 Integradores-->
<!-- Begin Panel Contactos MOVISTAR-->
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="table-basic-7">
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-warning" data-click="panel-collapse"><i class="fa fa-minus"></i></a>
</div>
<h4 class="panel-title">Contactos Movistar <?php echo $pais;?></h4>
</div>
<div class="panel-body" style="display: none;">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Organizacion</th>
<th>Nombre</th>
<th>Email</th>
<th>Telefono</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Helpdesk</td>
<td>Helpdesk</td>
<td><EMAIL></td>
<td> (+593) 2227700 ext. 2730</td>
</tr>
<tr>
<td>2</td>
<td>Jefe de Proyectos IT</td>
<td><NAME></td>
<td><EMAIL></td>
<td>+593 9 9920 0036</td>
</tr>
<tr>
<td>3</td>
<td>Jefe de Contenidos y Mensajería</td>
<td><NAME></td>
<td><EMAIL></td>
<td>+593 99 3645049</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end Panel Contactos MOVISTAR -->
</div><br>
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<?php include(TEMPLATE.DS.'footer.php');?>
<script>
$(document).ready(function() {
App.init();
TableManageDefault.init();
//Chart.init();
$('#data-table69').dataTable( {
"order": [[ 3, 'desc' ]]
} );
});
</script>
</body>
</html>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
<!--Comienza-->
var data1 = new google.visualization.DataTable();
data1.addColumn('number', 'Hora');
data1.addColumn('number', 'Promedio');
data1.addColumn('number', 'Ayer');
data1.addColumn('number', 'Hoy');
<?php
echo $data1;
?>
var options3 = {
title: '<?php echo 'Cobros '.$name1;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data1.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {lineDashStyle: [2, 2]},
1: {lineDashStyle: [2, 2]}
},
colors: ['#9EABB4','#01AEBF','#0fd43a'],
legend: { position: 'top' },
chartArea:{width:'70%',height:'60%'}
};
var formatter3 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter3.format(data1, 1);
formatter3.format(data1, 2);
formatter3.format(data1, 3);
var chart3 = new google.visualization.AreaChart(document.getElementById('CarrierD'));
chart3.draw(data1, options3);
/*----------------------*/
<!--comienza-->
var data = google.visualization.arrayToDataTable([
['Mes', 'Cobros'],
<?php
for($x=1;$x<=12;$x=$x+1){
?>
['<?php echo $meses[$x];?>', <?php echo $dinero[$x]?>],
<?php } ?>
]);
var options = {
title: 'Cobros totales por mes',
legend: { position: 'top' },
chartArea:{width:'70%',height:'60%'},
hAxis: {
title: 'Cobros',
minValue: 0
},
vAxis: {
title: 'Mes'
}
};
var formatter2 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter2.format(data, 1);
var chart = new google.visualization.BarChart(
document.getElementById('ex0'));
chart.draw(data, options);
}
$(window).resize(function(){
drawChart();
});
function GotoDetails(inte) {
var redirect = 'http://<?php echo URL; ?>/detalle/<?php echo $name1;?>I';
$.redirectPost(redirect, {combo: inte});
}
$.extend({
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="'+location+'" method="POST">'+form+'</form>').submit();
}
});
</script>
<file_sep>/Billing/app/modules/minimodules/dashboard/ActiveMQ.php
<?php
import::load('lib', 'MySQL');
$conexion = new MySQL(6);
$strConsulta = "select amq_name,descripcion,pendiente,consumidores from monitor_queue;";
$consulta = $conexion->consulta($strConsulta);
if($conexion->num_rows($consulta)>0){
echo '<h1 class="page-header">ActiveMQ <small>Detalle de colas Alarmadas</small></h1>
<div>';
while ($row2= $conexion->fetch_row($consulta)){
echo '
<div class="col-md-3 " >
<div class="widget widget-stats bg-black">
<div class="stats-icon stats-icon-lg"><i class="fa fa-globe fa-fw"></i></div>
<div class="stats-title">'.$row2[0].'<small> '.$row2[1].'</small></div>
<div class="stats-number"><small>Encolados:</small> '.$row2[2].'</div>
<div class="stats-progress progress">
<div class="progress-bar" style="width: 100%;"></div>
</div>
<div class="stats-desc">Consumidores: '.$row2[3].'</div>
</div>
</div>';
}
echo '</div>';
}
?><file_sep>/Billing/app/templates/login/login.php
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<head>
<meta charset="utf-8" />
<title><?php echo $Titulo;?></title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<meta content="" name="description" />
<meta content="" name="author" />
<!-- ================== BEGIN BASE CSS STYLE ================== -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">
<link href="<?=WEBROOT.DS;?>plugins/jquery-ui/themes/base/minified/jquery-ui.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>css/animate.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>css/style.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>css/style-responsive.min.css" rel="stylesheet" />
<link href="<?=WEBROOT.DS;?>css/theme/default.css" rel="stylesheet" id="theme" />
<!-- ================== END BASE CSS STYLE ================== -->
</head>
<body>
<!-- begin #page-loader -->
<div id="page-loader" class="fade in"><span class="spinner"></span></div>
<!-- end #page-loader -->
<div class="login-cover">
<div class="login-cover-image"><img src="<?=WEBROOT.DS;?>img/login-bg/bg-1.jpg" data-id="login-cover-image" alt="" /></div>
<div class="login-cover-bg"></div>
</div>
<!-- begin #page-container -->
<div id="page-container" class="fade">
<!-- begin login -->
<div class="login login-v2" data-pageload-addclass="animated flipInX">
<!-- begin brand -->
<div class="login-header">
<div class="brand">
<span class="logo"></span> Billing.Vas-Pass
<small style="padding: 0 40px;">Monetizing Mobile Services</small>
</div>
<div class="icon">
<i class="fa fa-sign-in"></i>
</div>
</div>
<!-- end brand -->
<div class="login-content">
<form action="http://<?=URL.DS;?>login/enter" method="post" autocomplete="off" class="margin-bottom-0">
<div class="form-group m-b-20">
<input type="text" class="form-control input-lg" name="login" placeholder="Usuario" />
</div>
<div class="form-group m-b-20">
<input type="password" class="form-control input-lg" name="password" placeholder="<PASSWORD>" />
</div>
<?php
switch ($mensaje){
case "error":
?>
<div class="alert alert-danger fade in m-b-15">
<strong>Error!</strong>
Usuario o Contraseña Incorrecta.
<span class="close" data-dismiss="alert">×</span>
</div>
<?php
break;
case "null":
?>
<div class="alert alert-danger fade in m-b-15">
<strong>Error!</strong>
Campos vacios, ingrese sus credenciales.
<span class="close" data-dismiss="alert">×</span>
</div>
<?php
break;
case "logged":
?>
<div class="alert alert-danger fade in m-b-15">
<strong>Error!</strong>
usuairo ya se encuantra con sesion iniciada.
<span class="close" data-dismiss="alert">×</span>
</div>
<?php
break;
case "notexist":
?>
<div class="alert alert-danger fade in m-b-15">
<strong>Error!</strong>
usuario no se encuentra registrado.
<span class="close" data-dismiss="alert">×</span>
</div>
<?php
break;
}
?>
<div class="login-buttons">
<button type="submit" class="btn btn-success btn-block btn-lg">Inicio de Sesión</button>
</div>
</form>
</div>
</div>
<!-- end login -->
</div>
<!-- end page container -->
<!-- ================== BEGIN BASE JS ================== -->
<script src="<?=WEBROOT.DS;?>plugins/jquery/jquery-1.9.1.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/jquery/jquery-migrate-1.1.0.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/jquery-ui/ui/minified/jquery-ui.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap/js/bootstrap.min.js"></script>
<!--[if lt IE 9]>
<script src="<?=WEBROOT.DS;?>crossbrowserjs/html5shiv.js"></script>
<script src="<?=WEBROOT.DS;?>crossbrowserjs/respond.min.js"></script>
<script src="<?=WEBROOT.DS;?>crossbrowserjs/excanvas.min.js"></script>
<![endif]-->
<script src="<?=WEBROOT.DS;?>plugins/slimscroll/jquery.slimscroll.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/jquery-cookie/jquery.cookie.js"></script>
<!-- ================== END BASE JS ================== -->
<!-- ================== BEGIN PAGE LEVEL JS ================== -->
<script src="<?=WEBROOT.DS;?>js/login-v2.demo.min.js"></script>
<script src="<?=WEBROOT.DS;?>js/apps.min.js"></script>
<!-- ================== END PAGE LEVEL JS ================== -->
<script>
$(document).ready(function() {
App.init();
LoginV2.init();
});
</script>
</body>
</html><file_sep>/Billing/app/modules/minimodules/guardia/guardiaD2.php
<?php
/*$user = 'openalonzo';
$password = '<PASSWORD>';
$server = '192.168.2.101\SQLMercurio';
$database = 'SMSNET_ADMIN';
$conexión = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
odbc_exec($conexión,"USE SMSNET_ADMIN");*/
require_once($_SERVER['DOCUMENT_ROOT'].'/core/import.php');
import::load('lib', 'MySQL');
$conexion = new MySQL();
?>
<!-- ****************************** Server Newrelic ******************************************* -->
<div class="box col-md-3">
<?php
/*$curl = curl_init('https://api.newrelic.com/v2/servers.json');
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Api-Key:7157dea6a415fe0c854831ef8b65f8adcdbd825ca5274e4","Content-Type: application/json"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
$servers = json_decode($resp,true);
echo $resp;
curl_close($curl);
if(count($servers['servers'])>0){
$var=0;
for($i=0;$i<count($servers['servers']);$i++){
if ($servers['servers'][$i]['health_status'] != 'green'){
$var++;
}
}
}*/
$strConsulta = "select cantidad from monitor where id_servicio =4";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){//if($var>0){
?>
<span class="notification red">Alarmas: <?= $row['cantidad'];?></span>
<?php
}else{
?>
<span class="notification green">OK</span>
<?php
}
?>
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Servidores NewRelic</h2>
<div class="box-icon">
<a class="btn btn-setting btn-round btn-default" onclick="clickButton(4);"><i
class="glyphicon glyphicon-tasks"></i></a>
</div>
</div>
<div class="box-content" align="center">
<img src="<?=ROOT.DS?>img/server1.png" class="animated rubberBand" alt="Sample Image 1">
</div>
</div>
</div>
<!-- ****************************** Servicios Newrelic ******************************************* -->
<div class="box col-md-3">
<?php
/*odbc_close($conexión);
$curl = curl_init('https://api.newrelic.com/v2/applications.json');
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Api-Key:7157dea6a415fe0c854831ef8b65f8adcdbd825ca5274e4","Content-Type: application/json"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
$servers = json_decode($resp,true);
curl_close($curl);
if(count($servers['applications'])>0){
$var=0;
for($i=0;$i<count($servers['applications']);$i++){
if ($servers['applications'][$i]['health_status'] != 'green'){
$var++;
}
}
}
if($var>0){*/
$strConsulta = "select cantidad from monitor where id_servicio =5";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){
?>
<span class="notification red">Alarmas: <?= $row['cantidad'];?></span>
<?php
}else{
?>
<span class="notification green">OK</span>
<?php
}
?>
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Apps NewRelic</h2>
<div class="box-icon">
<a class="btn btn-setting btn-round btn-default" onclick="clickButton(5);"><i
class="glyphicon glyphicon-tasks"></i></a>
</div>
</div>
<div class="box-content" align="center">
<img src="<?=ROOT.DS?>img/apps1.png" class="animated rubberBand" alt="Sample Image 1">
</div>
</div>
</div>
<!-- ****************************** Key Transactions Newrelic ******************************************* -->
<div class="box col-md-3">
<?php
/*$curl = curl_init('https://api.newrelic.com/v2/key_transactions.json');
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Api-Key:7157dea6a415fe0c854831ef8b65f8adcdbd825ca5274e4","Content-Type: application/json"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
//echo $resp;
$servers = json_decode($resp,true);
curl_close($curl);
if(count($servers['key_transactions'])>0){
$var=0;
for($i=0;$i<count($servers['key_transactions']);$i++){
//if ($servers['key_transactions'][$i]['health_status'] != 'green'){
$var++;
//}
}
}
if($var>0){*/
$strConsulta = "select cantidad from monitor where id_servicio =6";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){
?>
<span class="notification red">Alarmas: <?= $row['cantidad'];?></span>
<?php
}else{
?>
<span class="notification green">OK</span>
<?php
}
?>
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>KeyTransact NewRelic</h2>
<div class="box-icon">
<a class="btn btn-setting btn-round btn-default" onclick="clickButton(6);"><i
class="glyphicon glyphicon-tasks"></i></a>
</div>
</div>
<div class="box-content" align="center">
<img src="<?=ROOT.DS?>img/porcess1.png" class="animated rubberBand" alt="Sample Image 1">
</div>
</div>
</div>
<!-- ****************************** Monitoring ******************************************* -->
<div class="box col-md-3">
<?php
$strConsulta = "select cantidad from monitor where id_servicio =7";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){
?>
<span class="notification red">Alarmas: <?= $row['cantidad'];?></span>
<?php
}else{
?>
<span class="notification green">OK</span>
<?php
}
?>
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Monitoring David</h2>
<div class="box-icon">
<a class="btn btn-setting btn-round btn-default" onclick="clickButton(7);"><i
class="glyphicon glyphicon-tasks"></i></a>
</div>
</div>
<div class="box-content" align="center">
<img src="<?=ROOT.DS?>img/monitoring1.png" class="animated rubberBand" alt="Sample Image 1">
</div>
</div>
</div>
<!-- ****************************** Monitoring ******************************************* -->
<div class="box col-md-3">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2><NAME></h2>
<div class="box-icon">
<a class="btn btn-setting btn-round btn-default" onclick="clickButton(8);"><i
class="glyphicon glyphicon-tasks"></i></a>
</div>
</div>
<div class="box-content" align="center">
<img src="<?=ROOT.DS?>img/coin1.png" class="animated rubberBand" alt="Sample Image 1">
</div>
</div>
</div>
<!-- ****************************** Metricas ******************************************* -->
<div class="box col-md-3">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Metricas</h2>
<div class="box-icon">
<a class="btn btn-setting btn-round btn-default" onclick="clickButton(9);"><i
class="glyphicon glyphicon-tasks"></i></a>
</div>
</div>
<div class="box-content" align="center">
<img src="<?=ROOT.DS?>img/chart1.png" class="animated rubberBand" alt="Sample Image 1">
</div>
</div>
</div>
<!-- ****************************** Grafica ******************************************* -->
<file_sep>/Billing/app/modules/dashboard/dashboard.php
<?php
import::load('lib', 'Validate_Auth');
import::load('lib', 'Start_Page');
import::load('lib', 'Session');
import::load('lib', 'MySQL');
import::load('lib', 'view');
class dashboard{
function __construct(){
$this->titulo = 'Billing Vas Pass';
$this->mensaje = '';
}
function start($mensaje){
if(self::check()){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
//self::LoadTemplate("dashboard/dash.php",$data);
self::LoadTemplate("dashboard/dashboard.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function metricas($mensaje){
if(self::check()){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
//self::LoadTemplate("dashboard/dash.php",$data);
self::LoadTemplate("dashboard/dashboardMetricas.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function notificaciones($mensaje){
if(self::check()){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
//self::LoadTemplate("dashboard/dash.php",$data);
self::LoadTemplate("dashboard/notificaciones.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function start2($mensaje){
if(self::check()){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("dashboard/dashboardTest.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function content($mensaje){
if(self::check()){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
//self::LoadTemplate("dashboard/dash.php",$data);
self::LoadTemplate("dashboard/content.php",$data);
//require_once TEMPLATE.DS."dashboard/dashboard.php";
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function getLegacyInfo(){
include(MINMODULES.DS.'guardia/guardiaL2.php');
}
function getDavidInfo2(){
include(MINMODULES.DS.'dashboard/guardia.php');
}
function getActiveMQInfo(){
include(MINMODULES.DS.'dashboard/ActiveMQ.php');
}
function getTXRX(){
include(MINMODULES.DS.'guardia/TX_RX.php');
}
function getGateway(){
include(MINMODULES.DS.'guardia/Gateway.php');
}
function getBD(){
include(MINMODULES.DS.'guardia/BD.php');
}
function getServers(){
include(MINMODULES.DS.'guardia/Servers.php');
}
function getServiocios(){
include(MINMODULES.DS.'guardia/Servicios.php');
}
function getMonitoring(){
include(MINMODULES.DS.'guardia/Monitoring.php');
}
function getKeyTransactions(){
include(MINMODULES.DS.'guardia/KeyTransaction.php');
}
function getChargins(){
include(MINMODULES.DS.'guardia/Chargins.php');
}
function getMetricas(){
include(MINMODULES.DS.'guardia/metricas.php');
}
function cobros(){
include(MINMODULES.DS.'guardia/cobros.php');
}
private function check(){
return Validate_Auth::check();
}
private function LoadTemplate($template, $dataArr){
if (file_exists(TEMPLATE.DS.$template)){
Validate_Auth::start();
$view = new view($template);
if (!empty($dataArr)){
$view->render($dataArr);
}else{
$tempArr = array('NO' => 'DATA');
$view->render($tempArr);
}
}else{
echo 'Error!!! el template al que deseas accesar no existe. ';
echo $template;
}
}
}
?>
<file_sep>/Billing/app/templates/database/crear_sa.php
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin breadcrumb -->
<!-- end breadcrumb -->
<!-- begin page-header -->
<h1 class="page-header">Registro de nuevo Super Agregador<small></small></h1>
<!-- end page-header -->
<div class="row">
<div id="DavidMod"></div>
<!-- #modal-dialog -->
<div class="modal fade" id="modal-dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Detalle de Servicio.</h4>
</div>
<div class="modal-footer">
<a href="javascript:;" class="btn btn-sm btn-white" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
</div>
<!-- begin col-6 -->
<div class="col-md-6">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="form-validation-1">
<div class="panel-heading">
<div class="panel-heading-btn">
</div>
<h4 class="panel-title">Agregar Super Agregador</h4>
</div>
<div class="panel-body">
<form class="form-horizontal form-bordered" data-parsley-validate="true" name="demo-form" method="post">
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Nombre Pais * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="pais" name="pais" placeholder="Required" data-parsley-required="true" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Descripcion * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="descripcion" name="descripcion" placeholder="Required" data-parsley-required="true" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4"></label>
<div class="col-md-6 col-sm-6">
<button type="submit" class="btn btn-primary" onclick = "this.form.action = 'http://<?=URL.DS;?>database/save_sa'">Submit</button>
</div>
</div>
</form>
<?php if (isset($_SESSION['value']) and ($_SESSION['value'] == "ok")) {unset($_SESSION['value']);?>
<div class="alert alert-success fade in m-b-15">
<strong>Success!</strong>
Super Agregador creado correctamente.
<span class="close" data-dismiss="alert">×</span>
</div>
<?php }?>
<?php if (isset($_SESSION['value']) and ($_SESSION['value'] == "error1")) {unset($_SESSION['value']);?>
<div class="alert alert-success fade in m-b-15">
<strong>Error!</strong>
Ya existen tablas con el nombre a crear.
<span class="close" data-dismiss="alert">×</span>
</div>
<?php }?>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-6 -->
<!-- begin row -->
<div class="row">
<!-- begin col-12 -->
<div class="col-md-6">
<!-- begin panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<div class="panel-heading-btn">
</div>
<h4 class="panel-title">Detalle Super Agregador</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Descripcion</th>
</tr>
</thead>
<tbody>
<?php
import::load('lib', 'MySQL');
$query = " select id_carrier,descripcion
from billing.carrier
order by id_carrier;";
$conexion = new MySQL(0);
$exec = $conexion->consulta($query);
while ($row2= $conexion->fetch_row($exec)){
//if ($row2[2] == 1){$value = "Activo";}else{$value = "Baja";}
echo "<tr><td>$row2[0]</td><td>$row2[1]</td></tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-12 -->
</div>
<!-- end row -->
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<script src="<?=ROOT.DS;?>js/ui-modal-notification.demo.min.js"></script>
</body>
</html>
<script src="<?=ROOT.DS;?>js/dashboard-v2.js"></script>
<?php include(TEMPLATE.DS.'footer.php');?>
<script>
$(document).ready(function() {
App.init();
TableManageDefault.init();
});
</script>
<file_sep>/Billing/app/modules/minimodules/detalle/metricas_int.php
<?php
if(isset($_POST['combo'])){$integrador=$_POST['combo'];unset($_POST['combo']);}else{$integrador = 0;}
$data1 = getData($name1,$name1,$integrador);
function getData($name,$nombre1,$integrador){
$dataArray = "";
$fecha = date('H');
$dia = date('d', (strtotime ("+1 day")));
try{
$conexion = new MySQL(0);
$query0 = ' select hour(date_add(NOW(), INTERVAL -'.HOURDB.' hour));';
$result0 = $conexion->consulta($query0);
$exec0 = $conexion->fetch_row($result0);
$fecha = $exec0[0];
$query = 'CALL GetIntegratorChargeToday("'.strtolower($name).'",'.HOURDB.",".$integrador.');';
$result = $conexion->consulta($query);
$conexion->prepareNextResult();
$query1 = 'CALL GetIntegratorChargeYesterday("'.strtolower($name).'",'.HOURDB.",".$integrador.');';
$result1 = $conexion->consulta($query1);
$conexion->prepareNextResult();
$query2 = 'CALL GetIntegratorChargeProm("'.strtolower($name).'",'.HOURDB.",".$integrador.');';
$result2 = $conexion->consulta($query2);
$conexion->prepareNextResult();
if ((! $result) or (! $result1) or (! $result2)){
throw new Exception ("No se logro obtener informacion de cobros....\n");
}else{
$cont=0;
$hoy= $conexion->fetch_row($result);
$ayer= $conexion->fetch_row($result1);
$prom= $conexion->fetch_row($result2);
while ($cont <= $fecha){
if($ayer[1] == $cont){
$valor = $ayer[0];
$ayer= $conexion->fetch_row($result1);
}else{
$valor = 0;
}
if($hoy[1] == $cont){
$valor1 = $hoy[0];
$hoy= $conexion->fetch_row($result);
}else{
$valor1 = 0;
}
if($prom[0] == $cont){
$valor2 = $prom[1];
$prom= $conexion->fetch_row($result2);
}else{
$valor2 = 0;
}
$dataArray = $dataArray."data1.addRow([".$cont.", ".$valor2.",".$valor.", ".$valor1."]);\n";
$cont++;
}
}
$conexion->MySQLClose();
}catch(Exception $e){
echo 'Excepcion capturada: ', $e->getMessage(), "\n";
}
return $dataArray;
}
?>
<file_sep>/Billing/app/templates/menu.php
<?php $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";?>
<!-- begin #sidebar -->
<div id="sidebar" class="sidebar">
<!-- begin sidebar scrollbar -->
<div data-scrollbar="true" data-height="100%">
<!-- begin sidebar user -->
<ul class="nav">
<li class="nav-profile">
<div class="image">
<?php
$var1 = WEBROOT.DS.'img/users/'.$_SESSION['login'].'.jpg';
if (file_exists($var1)) {
$nombreimg = $_SESSION['login'];
$nombreDisplay = $_SESSION['login'];
} else {
$nombreimg = 'default';
$nombreDisplay = $_SESSION['login'];
}
?>
<a href="javascript:;"><img src=<?php echo WEBROOT.DS.'img/users/'.$nombreimg.'.jpg';?> alt="" /></a>
</div>
<div class="info">
<?php echo $_SESSION['login'];?>
<small><NAME></small>
</div>
</li>
</ul>
<!-- end sidebar user -->
<!-- begin sidebar nav -->
<ul class="nav">
<li class="nav-header">Navigation</li>
<?php if((($_SESSION['access']==1)or($_SESSION['access']==2)or($_SESSION['access']==3))and($_SESSION['pais']==1)){?>
<li <?php if(strpos($actual_link,'dashboard')){?>class="has-sub active"<?php }else{?>class="has-sub " <?php }?>>
<a href="javascript:;">
<b class="caret pull-right"></b>
<i class="fa fa-laptop"></i>
<span>Dashboard</span>
</a>
<ul class="sub-menu">
<li <?php if($actual_link == 'http://'.URL.DS.'dashboard/start'){?>class="active"<?php }?>><a href="http://<?=URL.DS;?>dashboard/start">Servicios</a></li>
<li <?php if($actual_link == 'http://'.URL.DS.'dashboard/Metricas'){?>class="active"<?php }?>><a href="http://<?=URL.DS;?>dashboard/Metricas">Metricas Generales</a></li>
<li <?php if($actual_link == 'http://'.URL.DS.'dashboard/notificaciones'){?>class="active"<?php }?>><a href="http://<?=URL.DS;?>dashboard/notificaciones">Notificaciones</a></li>
</ul>
</li>
<?php }?>
<?php
if ($_SESSION['access']!=3)
include(MODULES.DS.'menu/menuSA.php');
?>
<?php if((($_SESSION['access']==1))){?>
<li <?php if(strpos($actual_link,'usuario')){?>class="has-sub active"<?php }else{?>class="has-sub " <?php }?>>
<a href="javascript:;">
<b class="caret pull-right"></b>
<i class="fa fa-group"></i>
<span>Admin usuarios <span class="label label-theme m-l-5"></span></span>
</a>
<ul class="sub-menu">
<li <?php if($actual_link == 'http://'.URL.DS.'usuario/start'){?>class="active"<?php }?>><a href="http://<?=URL.DS;?>usuario/start">Creacion de Usuario</a></li>
<li <?php if($actual_link == 'http://'.URL.DS.'usuario/edit'){?>class="active"<?php }?>><a href="http://<?=URL.DS;?>usuario/edit">Edicion de usuarios</a></li>
<li <?php if($actual_link == 'http://'.URL.DS.'usuario/delete'){?>class="active"<?php }?>><a href="http://<?=URL.DS;?>usuario/delete">Altas/Bajas</a></li>
</ul>
</li>
<?php }?>
<?php if(($_SESSION['access']==1)){?>
<li <?php if(strpos($actual_link,'database')){?>class="has-sub active"<?php }else{?>class="has-sub " <?php }?>>
<a href="javascript:;">
<b class="caret pull-right"></b>
<i class="fa fa-cubes"></i>
<span>Admin cobros <span class="label label-theme m-l-5"></span></span>
</a>
<ul class="sub-menu">
<li <?php if($actual_link == 'http://'.URL.DS.'database/start'){?>class="active"<?php }?>><a href="http://<?=URL.DS;?>database/start">Creacion de Host</a></li>
<li <?php if($actual_link == 'http://'.URL.DS.'database/edit'){?>class="active"<?php }?>><a href="http://<?=URL.DS;?>database/edit">Modificacion Host</a></li>
<li <?php if($actual_link == 'http://'.URL.DS.'database/create_sa'){?>class="active"<?php }?>><a href="http://<?=URL.DS;?>database/create_sa">Creacion de SA</a></li>
<li <?php if($actual_link == 'http://'.URL.DS.'database/generate'){?>class="active"<?php }?>><a href="http://<?=URL.DS;?>database/generate">Generador de Cobros</a></li>
<li <?php if($actual_link == 'http://'.URL.DS.'database/down'){?>class="active"<?php }?>><a href="http://<?=URL.DS;?>database/down">Baja/Alta Cobros</a></li>
</ul>
</li>
<?php }?>
<!-- begin sidebar minify button -->
<li><a href="javascript:;" class="sidebar-minify-btn" data-click="sidebar-minify"><i class="fa fa-angle-double-left"></i></a></li>
<!-- end sidebar minify button -->
</ul>
<!-- end sidebar nav -->
</div>
<!-- end sidebar scrollbar -->
</div>
<div class="sidebar-bg"></div>
<!-- end #sidebar --><file_sep>/Billing/app/modules/minimodules/guardia/metricasMEX.php
<?php
$name = "SAPER";
$data = "";
$data = getData($name,$name);
//echo getData($name,$name). "<br></br>";
$name1 = "SAMEX";
$data1 = "";
$data1 = getData($name1,$name1);
//echo getData($name1,$name1);
$name2 = "SANIC";
$data2 = "";
$data2 = getData($name2,$name2);
$name3 = "SAECU";
$data3 = "";
$data3 = getData($name3,$name3);
$name4 = "SAPAN";
$data4 = "";
$data4 = getData($name4,$name4);
$data5 = "";
$data5 = getDataTable();
$data6 = "";
$data6 = getDataTableSACA();
//@odbc_close($conexión);
function getData($name,$nombre1){
$keyAccess = getAccess();
$dataArray = "";
$conexión = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$keyAccess[2];Database=$keyAccess[3];", $keyAccess[0], $keyAccess[1]);
$result = odbc_exec($conexión,"USE WauReports");
$result = odbc_exec($conexión," select ".$name." ,HORA
from cobros_SA
where FECHA between (GETDATE()-2) and (GETDATE()-1)
and HORA <= DATEPART(HOUR, GETDATE())-1
order by FECHA,HORA");
$result1 = odbc_exec($conexión," select ".$name.",HORA
from cobros_SA
where FECHA between (GETDATE()-1) and (GETDATE())
order by FECHA,HORA");
while ($r= odbc_fetch_object($result)){
if(@$r1=odbc_fetch_object($result1){
if($nombre1 == "SAPER"){
if($r->$name == ''){$r->$name=0;}
if($r1->$name == ''){$r1->$name=0;}
$dataArray = $dataArray."data.addRow([".$r->HORA.", ".$r->$name.", ".$r1->$name."]);\n";
}
if($nombre1 == "SAMEX"){
if($r->$name == ''){$r->$name=0;}
if($r1->$name == ''){$r1->$name=0;}
$dataArray = $dataArray."data1.addRow([".$r->HORA.", ".$r->$name.", ".$r1->$name."]);\n";
}
if($nombre1 == "SANIC"){
if($r->$name == ''){$r->$name=0;}
if($r1->$name == ''){$r1->$name=0;}
$dataArray = $dataArray."data2.addRow([".$r->HORA.", ".$r->$name.", ".$r1->$name."]);\n";
}
if($nombre1 == "SAECU"){
if($r->$name == ''){$r->$name=0;}
if($r1->$name == ''){$r1->$name=0;}
$dataArray = $dataArray."data3.addRow([".$r->HORA.", ".$r->$name.", ".$r1->$name."]);\n";
}
if($nombre1 == "SAPAN"){
if($r->$name == ''){$r->$name=0;}
if($r1->$name == ''){$r1->$name=0;}
$dataArray = $dataArray."data4.addRow([".$r->HORA.", ".$r->$name.", ".$r1->$name."]);\n";
}
}
}
return $dataArray;
}
function getDataTable(){
$keyAccess = getAccess();
$conexion = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$keyAccess[2];Database=$keyAccess[3];", $keyAccess[0], $keyAccess[1]);
$result = odbc_exec($conexion,"USE WauReports");
@$result = odbc_exec($conexion,"EXEC GetChargesSA");
$r= odbc_fetch_object($result);
@$result2 = odbc_exec($conexion,"GetpercentageSA");
if(@$r2= odbc_fetch_object($result2)){
$body = "<tr><td align=\"center\"> SAMEX </td><td align=\"right\">".number_format($r->SAMEX)."</td><td align=\"right\">".number_format($r2->SAMEX)."</td><td align=\"right\"> ".number_format((($r->SAMEX*100)/$r2->SAMEX));
$body = $body. "%</td></tr>";
$body = $body. "<tr><td align=\"center\"> SAPER </td><td align=\"right\">".number_format($r->SAPER)."</td><td align=\"right\">".number_format($r2->SAPER)."</td><td align=\"right\"> ".number_format((($r->SAPER*100)/$r2->SAPER));
$body = $body. "%</td></tr>";
$body = $body. "<tr><td align=\"center\"> SAECU </td><td align=\"right\">".number_format($r->SAECU)."</td><td align=\"right\">".number_format($r2->SAECU)."</td><td align=\"right\"> ".number_format((($r->SAECU*100)/$r2->SAECU));
$body = $body. "%</td></tr>";
}
return $body;
}
function getDataTableSACA(){
$keyAccess = getAccess();
$conexion = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$keyAccess[2];Database=$keyAccess[3];", $keyAccess[0], $keyAccess[1]);
$result = odbc_exec($conexion,"USE WauReports");
$result = odbc_exec($conexion,"EXEC GetChargesSA");
$r= odbc_fetch_object($result);
$result2 = odbc_exec($conexion,"GetpercentageSA");
$r2= odbc_fetch_object($result2);
$body = "<tr><td align=\"center\"> SANIC </td><td align=\"right\">".number_format($r->SANIC)."</td><td align=\"right\">".number_format($r2->SANIC)."</td><td align=\"right\"> ".number_format((($r->SANIC*100)/$r2->SANIC));
$body = $body. "%</td></tr>";
$body = $body. "<tr><td align=\"center\"> SAPAN </td><td align=\"right\">".number_format($r->SAPAN)."</td><td align=\"right\">".number_format($r2->SAPAN)."</td><td align=\"right\"> ".number_format((($r->SAPAN*100)/$r2->SAPAN));
$body = $body. "%</td></tr>";
return $body;
}
function getAccess(){
$keyAccess = array("openalonzo","wau123","192.168.3.11","WauReports");
return $keyAccess;
}
?>
<body>
<div>
<div id="SAMEX" style="width: 440px; height: 250px; display:inline-block;"></div>
<div id="SAPER" style="width: 440px; height: 250px; display:inline-block;"></div>
<div id="SAECU" style="width: 440px; height: 250px; display:inline-block;"></div>
<div id="SANIC" style="width: 440px; height: 250px; display:inline-block;"></div>
<div id="SAPAN" style="width: 440px; height: 250px; display:inline-block;"></div>
</div>
</body>
<?php //include_once "metricasMEX.php"; ?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
var body = "";
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Hora');
data.addColumn('number', 'Cobros Ayer');
data.addColumn('number', 'Cobros Hoy');
<?php
echo $data;
?>
var options = {
title: '<?php echo 'Cobros '.$name;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {color: '#9EABB4'},
1: {color: '#0fd43a'}
}
};
var formatter = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
var formatterH = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, sufrix: '00', pattern: '##:'});
formatter.format(data, 1);
formatter.format(data, 2);
formatterH.format(data, 0);
var chart = new google.visualization.AreaChart(document.getElementById('SAPER'));
google.visualization.events.addListener(chart, 'ready', function () {
var imgUri = chart.getImageURI();
body = body+imgUri+"\n";
});
chart.draw(data, options);
/*----------------------*/
var data1 = new google.visualization.DataTable();
data1.addColumn('number', 'Hora');
data1.addColumn('number', 'Cobros Ayer');
data1.addColumn('number', 'Cobros Hoy');
<?php
echo $data1;
?>
var options1 = {
title: '<?php echo 'Cobros '.$name1;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data1.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {color: '#9EABB4'},
1: {color: '#0fd43a'}
}
};
var formatter1 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter1.format(data1, 1);
formatter1.format(data1, 2);
var chart1 = new google.visualization.AreaChart(document.getElementById('SAMEX'));
google.visualization.events.addListener(chart1, 'ready', function () {
var imgUri1 = chart1.getImageURI();
body = body+" <img alt='Embedded Image' src='"+imgUri1+"'/>";
});
chart1.draw(data1, options1);
/*----------------------*/
var data3 = new google.visualization.DataTable();
data3.addColumn('number', 'Hora');
data3.addColumn('number', 'Cobros Ayer');
data3.addColumn('number', 'Cobros Hoy');
<?php
echo $data3;
?>
var options3 = {
title: '<?php echo 'Cobros '.$name3;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data3.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {color: '#9EABB4'},
1: {color: '#0fd43a'}
}
};
var formatter3 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter3.format(data3, 1);
formatter3.format(data3, 2);
var chart3 = new google.visualization.AreaChart(document.getElementById('SAECU'));
google.visualization.events.addListener(chart3, 'ready', function () {
var imgUri3 = chart3.getImageURI();
body = body+" <img alt='Embedded Image' src='"+imgUri3+"'/>";
});
chart3.draw(data3, options3);
/*----------------------*/
var data2 = new google.visualization.DataTable();
data2.addColumn('number', 'Hora');
data2.addColumn('number', 'Cobros Ayer');
data2.addColumn('number', 'Cobros Hoy');
<?php
echo $data2;
?>
var options2 = {
title: '<?php echo 'Cobros '.$name2;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data2.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {color: '#9EABB4'},
1: {color: '#0fd43a'}
}
};
var formatter2 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter2.format(data2, 1);
formatter2.format(data2, 2);
var chart2 = new google.visualization.AreaChart(document.getElementById('SANIC'));
google.visualization.events.addListener(chart2, 'ready', function () {
var imgUri2 = chart2.getImageURI();
body = body+" <img alt='Embedded Image' src='"+imgUri2+"'/>";
});
chart2.draw(data2, options2);
/*----------------------*/
var data4 = new google.visualization.DataTable();
data4.addColumn('number', 'Hora');
data4.addColumn('number', 'Cobros Ayer');
data4.addColumn('number', 'Cobros Hoy');
<?php
echo $data4;
?>
var options4 = {
title: '<?php echo 'Cobros '.$name4;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data4.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {color: '#9EABB4'},
1: {color: '#0fd43a'}
}
};
var formatter4 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter4.format(data4, 1);
formatter4.format(data4, 2);
var chart4 = new google.visualization.AreaChart(document.getElementById('SAPAN'));
google.visualization.events.addListener(chart4, 'ready', function () {
var imgUri4 = chart4.getImageURI();
body = body+" <img alt='Embedded Image' src='"+imgUri4+"'/>";
});
chart4.draw(data4, options4);
console.log(body);
document.write(body);
}
</script>
<file_sep>/Billing/app/templates/footer.php
<!-- ================== BEGIN BASE JS ================== -->
<script src="<?=WEBROOT.DS;?>plugins/jquery/jquery-1.9.1.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/jquery/jquery-migrate-1.1.0.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/jquery-ui/ui/minified/jquery-ui.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap/js/bootstrap.min.js"></script>
<!--[if lt IE 9]>
<script src="<?=WEBROOT.DS;?>crossbrowserjs/html5shiv.js"></script>
<script src="<?=WEBROOT.DS;?>crossbrowserjs/respond.min.js"></script>
<script src="<?=WEBROOT.DS;?>crossbrowserjs/excanvas.min.js"></script>
<![endif]-->
<script src="<?=WEBROOT.DS;?>plugins/slimscroll/jquery.slimscroll.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/jquery-cookie/jquery.cookie.js"></script>
<!-- ================== END BASE JS ================== -->
<!-- ================== BEGIN PAGE LEVEL JS ================== -->
<!--script src="<?=WEBROOT.DS;?>plugins/jquery-jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/jquery-jvectormap/jquery-jvectormap-world-merc-en.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-calendar/js/bootstrap_calendar.min.js"></script-->
<script src="<?=WEBROOT.DS;?>plugins/DataTables/js/jquery.dataTables.js"></script>
<script src="<?=WEBROOT.DS;?>js/table-manage-default.demo.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-combobox/js/bootstrap-combobox.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/gritter/js/jquery.gritter.js"></script>
<script src="<?=WEBROOT.DS;?>js/form-plugins.demo.js"></script>
<script src="<?=WEBROOT.DS;?>js/apps.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/parsley/dist/parsley.js"></script>
<!-- ================== END PAGE LEVEL JS ================== -->
<!-- ================== BEGIN BASE JS ================== -->
<script src="<?=WEBROOT.DS;?>plugins/pace/pace.min.js"></script>
<!-- ================== END BASE JS ================== --><file_sep>/Billing/app/templates/top.php
<!-- begin #page-loader -->
<div id="page-loader" class="fade in"><span class="spinner"></span></div>
<!-- end #page-loader -->
<!-- begin #page-container -->
<div id="page-container" class="fade page-sidebar-fixed page-header-fixed">
<!-- begin #header -->
<div id="header" class="header navbar navbar-default navbar-fixed-top">
<!-- begin container-fluid -->
<div class="container-fluid">
<!-- begin mobile sidebar expand / collapse button -->
<div class="navbar-header">
<a href="http://<?=URL.DS;?>" class="navbar-brand"> <span class="navbar-logo"></span> Billing.Vas-Pass <span style="font-size:9px;">V.2.1</span></a>
<button type="button" class="navbar-toggle" data-click="sidebar-toggled">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- end mobile sidebar expand / collapse button -->
<!-- begin header navigation right -->
<ul class="nav navbar-nav navbar-right">
<li class="dropdown navbar-user">
<?php
$var1 = WEBROOT.DS.'img/users/'.$_SESSION['login'].'.jpg';
if (file_exists($var1)) {
$nombreimg = $_SESSION['login'];
$nombreDisplay = $_SESSION['login'];
} else {
$nombreimg = 'default';
$nombreDisplay = $_SESSION['login'];
}
?>
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown">
<img src=<?php echo WEBROOT.DS.'img/users/'.$nombreimg.'.jpg';?> alt="" />
<span class="hidden-xs"><?php echo $_SESSION['login'];?></span> <b class="caret"></b>
</a>
<ul class="dropdown-menu animated fadeInLeft">
<li class="arrow"></li>
<li><a href="http://<?=URL.DS;?>usuario/profile">Edit Profile</a></li>
<li class="divider"></li>
<li><a href="http://<?=URL.DS;?>login/logout">Log Out</a></li>
</ul>
</li>
</ul>
<!-- end header navigation right -->
</div>
<!-- end container-fluid -->
</div>
<!-- end #header --><file_sep>/Billing/app/modules/minimodules/guardia/BD.php
<?php
/*require_once($_SERVER['DOCUMENT_ROOT'].'/core/import.php');
import::load('lib', 'MySQL');
$conexion = new MySQL();*/
$user = 'openalonzo';
$password = '<PASSWORD>';
$server = '192.168.2.101\SQL<PASSWORD>io';
$database = 'SMSNET_ADMIN';
$conexión = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
odbc_exec($conexión,"USE SMSNET_ADMIN");
$body = '
<!-- ****************************** Inicio Alarmas Gateway ******************************************* -->
<div class="box col-md-12">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Servicios Alarmados</h2>
</div>
<div class="box-content">
<table class="table table-condensed">
<thead>
<tr>
<th>Servicio</th>
<th>Descripcion</th>
<th>Last OK Status</th>
</tr>
</thead>
<tbody>';
$result = odbc_exec($conexión," exec GetDatabaseStatus");
while ($r= odbc_fetch_object($result)){
$body = $body."<tr><td>";
$body = $body.$r->Base.'</td><td class="center">'.$r->Base_de_Datos."</td><td>";
if ($r->DatabaseStatus == 'ONLINE'){
$body = $body.'<span class="label-success label label-default">'.$r->DatabaseStatus.'</span>';
}else{
$body = $body.'<span class="label-default label label-danger">'.$r->DatabaseStatus.'</span>';
}
$body = $body."</td></tr>";
}
$body = $body.'</tbody>
</table>
</div>
</div>
</div>';
odbc_close($conexión);
echo $body;
//24A7FF
?><file_sep>/Billing/app/modules/minimodules/guardia/guardiaL.php
<?php
$user = 'openalonzo';
$password = '<PASSWORD>';
$server = '192.168.2.101\SQLMercurio';
$database = 'SMSNET_ADMIN';
$conexión = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
odbc_exec($conexión,"USE SMSNET_ADMIN");
/*$body='<!-- ****************************** Inicio de reporte de colas ************************************* -->
<div class="box col-md-12">
<div class="box col-md-6">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Queues</h2>
<div class="box-icon">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
<a href="#" class="btn btn-close btn-round btn-default"><i
class="glyphicon glyphicon-remove"></i></a>
</div>
</div>
<div class="box-content">
<table class="table table-condensed">
<thead>
<tr>
<th>QueueName</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>';
$result = odbc_exec($conexión,"exec GetTopQueues;");
while ($r= odbc_fetch_object($result)){
$body = $body."<tr><td>";
$body = $body. $r->QueueName.'</td><td class="center">';
if($r->Qty <= 65000){
$body = $body.'<span class="label-success label label-default">'.$r->Qty.'</span>';
}
if(($r->Qty > 65000) and ($r->Qty <= 85000)){
$body = $body.'<span class="label-warning label label-default">'.$r->Qty.'</span>';
}
if(($r->Qty > 85000)){
$body = $body.'<span class="label-default label label-danger">'.$r->Qty.'</span>';
}
$body = $body."</td></tr>";
}
$body = $body.'</tbody>
</table>
</div>
</div>
</div>*/
$body = '<!-- ****************************** Fin de reporte de colas ************************************* -->
<!-- ****************************** Inicio de top cobros **************************************** -->
<div class="box col-md-6">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Top cobros</h2>
<div class="box-icon">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
<a href="#" class="btn btn-close btn-round btn-default"><i
class="glyphicon glyphicon-remove"></i></a>
</div>
</div>
<div class="box-content">
<table class="table table-condensed">
<thead>
<tr>
<th>Carrier</th>
<th>Cantidad</th>
<th>Ultimo cobro</th>
</tr>
</thead>
<tbody>';
$result = odbc_exec($conexión,"select top 5 * FROM SMSNET_ADMIN.dbo.MessageLogSent_Monitoring order by registros desc");
while ($r= odbc_fetch_object($result)){
$body = $body. "<tr><td>";
$body = $body. $r->Pais.'</td><td class="center">'.$r->Registros."</td><td>".$r->Date;
$body = $body. "</td></tr>";
}
$body = $body.'</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- ****************************** Fin de top cobros ******************************************* -->
<div align="center"><h4>Status Fobos</h4></div>
<!-- ****************************** Inicio Alarmas Gateway ************************************** -->
<div class="box col-md-12">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Servicios Gateway Alarmados</h2>
<div class="box-icon">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
<a href="#" class="btn btn-close btn-round btn-default"><i
class="glyphicon glyphicon-remove"></i></a>
</div>
</div>
<div class="box-content">
<table class="table table-condensed">
<thead>
<tr>
<th>Gateway</th>
<th>Descripcion</th>
<th>Last OK Status</th>
</tr>
</thead>
<tbody>';
$result = odbc_exec($conexión,"exec ServiceMonitor_GetGatewayClients");
while ($r= odbc_fetch_object($result)){
$body = $body."<tr><td>";
$body = $body.$r->GatewayDescription.'</td><td class="center">'.$r->Description."</td><td>";
$body = $body.'<span class="label-warning label label-default">'.$r->LastOkStatus.'</span>';
$body = $body."</td></tr>";
}
$body = $body.'</tbody>
</table>
</div>
</div>
</div>
<!-- ****************************** Fin Alarmas Gateway ****************************************** -->
<!-- ****************************** Inicio Alarmas Beconected ************************************ -->
<div class="box col-md-12">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Servicios Beconected Alarmados</h2>
<div class="box-icon">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
<a href="#" class="btn btn-close btn-round btn-default"><i
class="glyphicon glyphicon-remove"></i></a>
</div>
</div>
<div class="box-content">
<table class="table table-condensed">
<thead>
<tr>
<th>Servicio</th>
<th>Descripcion</th>
<th>Last OK Status</th>
</tr>
</thead>
<tbody>';
$result = odbc_exec($conexión," select *
from SMSNET_ADMIN..ServiceMonitor
where servicename like '%beco%' and ServiceTypeID = 1 and Severity != 0");
while ($r= odbc_fetch_object($result)){
$body = $body."<tr><td>";
$body = $body.$r->ServiceName.'</td><td class="center">'.$r->Description."</td><td>";
$body = $body.'<span class="label-warning label label-default">'.$r->LastOKStatus.'</span>';
$body = $body."</td></tr>";
}
$body = $body.'</tbody>
</table>
</div>
</div>
</div>
<!-- ****************************** FIN Alarmas Beconected ***************************************** -->
<div align="center"><h4>Status Hermes/Ares</h4></div>
<!-- ****************************** Inicio Alarmas RX/TX ******************************************* -->
<div class="box col-md-12">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Servicios Alarmados</h2>
<div class="box-icon">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
<a href="#" class="btn btn-close btn-round btn-default"><i
class="glyphicon glyphicon-remove"></i></a>
</div>
</div>
<div class="box-content">
<table class="table table-condensed">
<thead>
<tr>
<th>Servicio</th>
<th>Descripcion</th>
<th>Last OK Status</th>
</tr>
</thead>
<tbody>';
$result = odbc_exec($conexión," select ServiceName,Description,LastOKStatus
from SMSNET_ADMIN..ServiceMonitor
where TelcoID != 0 and Severity != 0");
while ($r= odbc_fetch_object($result)){
$body = $body."<tr><td>";
$body = $body.$r->ServiceName.'</td><td class="center">'.$r->Description."</td><td>";
$body = $body.'<span class="label-warning label label-default">'.$r->LastOKStatus.'</span>';
$body = $body."</td></tr>";
}
$body = $body.'</tbody>
</table>
</div>
</div>
</div>
<!-- ****************************** Fin Alarmas RX/TX ********************************************* -->
<!-- ****************************** Inicio Alarmas Scheduler ************************************** -->
<div class="box col-md-6">
<div align="center"><h4>Status Kore</h4></div>
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Envios de Scheduler</h2>
<div class="box-icon">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
<a href="#" class="btn btn-close btn-round btn-default"><i
class="glyphicon glyphicon-remove"></i></a>
</div>
</div>
<div class="box-content">
<table class="table table-condensed">
<thead>
<tr>
<th>Ultimo Envio</th>
<th>Status</th>
</tr>
</thead>
<tbody>';
$result = odbc_exec($conexión," select top 1 UpdatedDate,StatusDescription
from SCHEDULELOGS.dbo.ScheduleActivity
where StatusDescription = 'Finalizado'
order by CreatedDate desc");
while ($r= odbc_fetch_object($result)){
$body = $body."<tr><td>";
$body = $body.$r->UpdatedDate.'</td><td class="center">';
if ($r->StatusDescription == 'Finalizado'){
$body = $body.'<span class="label-success label label-default">'.$r->StatusDescription.'</span>';
}else{
$body = $body.'<span class="label-warning label label-default">'.$r->StatusDescription.'</span>';
}
$body = $body."</td></tr>";
}
$body = $body.'</tbody>
</table>
</div>
</div>
</div>
<!-- ****************************** Fin Alarmas Scheduler ***************************************** -->
<!-- ****************************** Inicio Alarmas encolados ************************************** -->
<div class="box col-md-6">
<div align="center"><h4>Status Titan</h4></div>
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Encolados en Pending</h2>
<div class="box-icon">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
<a href="#" class="btn btn-close btn-round btn-default"><i
class="glyphicon glyphicon-remove"></i></a>
</div>
</div>
<div class="box-content">
<table class="table table-condensed">
<thead>
<tr>
<th>Descripcion</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>';
$result = odbc_exec($conexión," exec GetPendingQueue;");
while ($r= odbc_fetch_object($result)){
$body = $body."<tr><td> Cantidad Encolados";
$body = $body.'</td><td class="center">';
if($r->Encolados <= 65000){
$body = $body.'<span class="label-success label label-default">'.$r->Encolados.'</span>';
}
if(($r->Encolados > 65000) and ($r->Encolados <= 85000)){
$body = $body.'<span class="label-warning label label-default">'.$r->Encolados.'</span>';
}
if(($r->Encolados > 85000)){
$body = $body.'<span class="label-default label label-danger">'.$r->Encolados.'</span>';
}
$body = $body."</td></tr>";
}
$body = $body.'</tbody>
</table>
</div>
</div>
</div>
<!-- ****************************** Fin Alarmas encolados ***************************************** -->
<div align="center"><h4>Status Base de Datos Legacy</h4></div>
<!-- ****************************** Inicio Alarmas RX/TX ******************************************* -->
<div class="box col-md-12">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Servicios Alarmados</h2>
<div class="box-icon">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
<a href="#" class="btn btn-close btn-round btn-default"><i
class="glyphicon glyphicon-remove"></i></a>
</div>
</div>
<div class="box-content">
<table class="table table-condensed">
<thead>
<tr>
<th>Servicio</th>
<th>Descripcion</th>
<th>Status</th>
</tr>
</thead>
<tbody>';
$result = odbc_exec($conexión," exec GetDatabaseStatus");
while ($r= odbc_fetch_object($result)){
$body = $body."<tr><td>";
$body = $body.$r->Base.'</td><td class="center">'.$r->Base_de_Datos."</td><td>";
if ($r->DatabaseStatus == 'ONLINE'){
$body = $body.'<span class="label-success label label-default">'.$r->DatabaseStatus.'</span>';
}else{
$body = $body.'<span class="label-default label label-danger">'.$r->DatabaseStatus.'</span>';
}
$body = $body."</td></tr>";
}
$body = $body.'</tbody>
</table>
</div>
</div>
</div>';
echo $body;
$_SESSION['bodyL'] = $body;
odbc_close($conexión);
?><file_sep>/Billing/core/lib/BDCobros.php
<?php
class BDCobros{
var $conectorLocal;
var $ExternalConector;
var $ErrorExternalConector;
var $id_carrier;
var $BodyText;
var $carrier_name;
var $id_db;
var $schema;
var $table;
var $where;
var $field;
var $fp;
function __construct(){
$this->conectorLocal = new MySQL(0);
$this->ErrorExternalConector = false;
$this->id_carrier = "";
$this->BodyText = "";
$this->carrier_name = "";
$this->id_db = "";
$this->schema = "";
$this->table = "";
$this->where = "";
$this->field = "";
}
function StartLog($log){
$this->fp = fopen(LOGS.DS.$log.date('Y_m_d').".txt", "a");
}
function LoadAllServices(){
$query = "call LoadCarrierDB;";
$result = $this->conectorLocal->consulta($query);
self::AddBodyLog("Servicios a ejecutar: ".$this->conectorLocal->num_rows($result));
return $result;
}
function StartProcess($data,$opt,$SaveAction){
while ($row = $this->conectorLocal->fetch_row($data)){
$this->id_carrier = $row[0];
$this->carrier_name = $row[1];
$this->id_db = $row[2];
$this->schema = $row[3];
$this->table = $row[4];
$this->where = $row[5];
$this->field = $row[6];
try {
$consumer = self::GetQuery($this->schema,$this->table,$this->field,$this->where,$opt);
self::AddBodyLog( "**************************Realizando llamado a GetCharges para ".$this->carrier_name."**************************");
self::GetCharges($this->id_db,$consumer,$opt,$SaveAction);
$this->ErrorExternalConector = false;
self::AddBodyLog( "**************************finalizacion de generacion de cobro**************************");
} catch (Exception $e) {
self::AddBodyLog("No se logro obtener la informacion de ".$this->carrier_name." Validar conexion a Base de datos!!!!!!!!!!!!!!!");
}
self::WriteLog();
self::clearBodyLog();
}
}
function SaveCharges($DataCharge, $option, $save){
$conectorLocal1 = new MySQL(0);
switch ($option) {
case 1:
$LoadCant = ($DataCharge[0] != "") ? $DataCharge[0] : 0;
$query = 'insert into billing.'.strtolower($this->carrier_name).
' values(null,'.$this->id_carrier.',date(date_add(now(), interval -6 hour)),hour(date_add(now(), interval -6 hour)),'.$LoadCant.");";
break;
case 2:
$LoadCant = ($DataCharge[2] != "") ? $DataCharge[2] : 0;
$query = 'insert into billing.'.strtolower($this->carrier_name).'_i values(null,'.$this->id_carrier.','.$DataCharge[0].',"'.$DataCharge[1].'",date(date_add(now(), interval -6 hour)),hour(date_add(now(), interval -6 hour)),'.$LoadCant.");";
break;
case 3:
$LoadCant = ($DataCharge[0] != "") ? $DataCharge[0] : 0;
$avg = ($DataCharge[1] != "") ? $DataCharge[1] : 0;
$query = "call SaveMonitorCharges(".$this->id_carrier.",'".$this->carrier_name."',".$LoadCant.",".$avg.",2);";
break;
case 4:
$LoadCant = ($DataCharge[3] != "") ? $DataCharge[3] : 0;
$query = 'insert into billing.'.strtolower($this->carrier_name).'_i_p values(null,'.$this->id_carrier.','.$DataCharge[0].','.$DataCharge[1].',"'.$DataCharge[2].'",date(date_add(now(), interval -6 hour)),hour(date_add(now(), interval -6 hour)),'.$LoadCant.");";
break;
}
self::AddBodyLog($query);
if($save)
$result = $conectorLocal1->consulta($query);
$conectorLocal1->MySQLClose();
}
function GetCharges($db_selection,$query,$opt,$SaveAction){
if(isset($db_selection) and isset($query)){
try {
$conectorLocal1 = new MySQL(0);
$dbdata = "call GetDBKey(".$db_selection.");";
$exec = $conectorLocal1->consulta($dbdata);
$conectorLocal1->prepareNextResult();
$result = $conectorLocal1->fetch_row($exec);
self::MySQLExternal($result[1],$result[2],$result[3],$this->schema);
if (!$this->ErrorExternalConector){
$execute = self::externalQuery($query);
$i = 0;
while ($row = self::externalfetch_row($execute)){
switch ($opt) {
case 1:
$LoadCant = 0;
if($row[0] != "")
$LoadCant = $row[0];
self::AddBodyLog( "Cobros generados: ".$LoadCant);
self::AddBodyLog( "Enviando a guardar informacion...........");
self::SaveCharges($row,$opt,$SaveAction);
break;
case 2:
self::AddBodyLog( "Cobros generados para ".$row[1].": ".$row[2]);
self::AddBodyLog( "Enviando a guardar informacion...........");
self::SaveCharges($row,$opt,$SaveAction);
$i++;
break;
case 3:
$LoadCant = 0;
if($row[0] != "")
$LoadCant = $row[0];
$dbdata = "call GetAVGChargesPerCarrier(".$this->id_carrier.",2);";
$exec = $conectorLocal1->consulta($dbdata);
$result = $conectorLocal1->fetch_row($exec);
$info[0] = $row[0];
$info[1] = $result[0];
self::AddBodyLog( "Obteniendo Promedio de cobros ".$dbdata.": ".$result[0]);
self::AddBodyLog( "Cobros generados: ".$LoadCant);
self::AddBodyLog( "Enviando a guardar informacion...........");
self::SaveCharges($info,$opt,$SaveAction);
break;
case 4 :
self::AddBodyLog( "Cobros generados para ".$row[2].": ".$row[3]);
self::AddBodyLog( "Enviando a guardar informacion...........");
self::SaveCharges($row,$opt,$SaveAction);
$i++;
break;
break;
}
}
if($opt == 2 ){self::AddBodyLog( "Integradores Procesados: ".$i);}
if($opt == 4 ){self::AddBodyLog( "Productos Procesados: ".$i);}
}
$conectorLocal1->MySQLClose();
} catch (Exception $e) {
self::AddBodyLog("No se logro obtener la informacion de ".$this->carrier_name." Validar conexion a Base de datos!!!!!!!!!!!!!!!");
self::AddBodyLog("Trace ".$this->ErrorExternalConector);
}
}
}
function GetQuery($schema, $table, $field, $where,$opt){
if(isset($schema) and isset($table) and isset($where)){
$AddFields = "";
$GroupBy = ";";
$MakeJoin = "";
if($opt == 2){
$AddFields = "a.integrator_id,b.name,";
$MakeJoin = "join ".$schema.".integratordetails b on a.integrator_id = b.integrator_id";
$GroupBy = "group by a.integrator_id";
}
if($opt == 4){
$AddFields = "a.integrator_id,a.product_id,b.product_name,";
$MakeJoin = "join ".$schema.".product_master b on a.product_id = b.product_id";
$GroupBy = "group by a.integrator_id,a.product_id,b.product_name";
}
$DynamicQuery = "select ".$AddFields ."sum(a.".$field.") Cobros ";
$DynamicQuery = $DynamicQuery."From ".$schema.".".$table." a ";
$DynamicQuery = $DynamicQuery.$MakeJoin." ";
$DynamicQuery = $DynamicQuery."Where ".$where." ";
$DynamicQuery = $DynamicQuery.$GroupBy;
return $DynamicQuery;
}
}
function MySQLExternal($h, $u, $p, $s){
@$this->ExternalConector = mysqli_connect($h,$u,$p,$s);
if (mysqli_connect_errno()){
self::AddBodyLog("Connect failed: ".mysqli_connect_error());
$this->ErrorExternalConector = true;
}
}
function externalQuery($consulta){
$resultado = $this->ExternalConector->query($consulta);
if(!$resultado)
self::AddBodyLog( 'MySQL Error: '. $this->ExternalConector->error);
return $resultado;
}
function externalfetch_array($consulta){
return $consulta->fetch_array();
}
function externalfetch_row($consulta){
return $consulta->fetch_row();
}
function AddBodyLog($comment){
$this->BodyText = $this->BodyText."[".date('Y-m-d H:i:s')."] ".$comment."\n";
}
function clearBodyLog(){
$this->BodyText = '';
}
function WriteLog(){
fputs($this->fp,$this->BodyText);
}
}
?>
<file_sep>/Billing/app/templates/basic/CarrierD_I.php
<!--Begin Grafica CarrierD_I-->
<?php
require_once LIB.DS."MySQL.php";
include(MINMODULES.DS.'detalle/metricas_int.php');
?>
<!--End Grafica CarrierD_I -->
<!-- BEGIN Chart3 CarrierD_I -->
<?php
$conexion = new MySQL(0);
$tituloG = "";
$query3 = ' select * from (select id_transaction,max(cantidad) as Total,fecha
from billing.'.$name1.'_i
where id_integrador = '.$integrador.'
group by fecha, id_integrador
order by fecha desc
limit 30)orden order by fecha asc
';
$resultfox= $conexion->consulta($query3);
$data10 = '';
while($rfox= $conexion->fetch_row($resultfox)){
$y=date('d-m', strtotime($rfox[2]));
$data10 = $data10."data3.addRow(['".$y."',".$rfox[1]."]);\n";
};
?>
<!-- END Chart3 CarrierD_I -->
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin page-header -->
<h1 class="page-header"><?php echo strtoupper($name1);?> <small>Detalle Por Integrador Movistar <?php echo $pais;?></small></h1>
<!-- end page-header -->
<div class="row">
<!-- begin col-4 -->
<div class="col-md-4">
<!-- begin COMBO INTEGRADORES -->
<div class="panel panel-inverse" data-sortable-id="form-plugins-4">
<div class="panel-heading">
<div class="panel-heading-btn">
</div>
<h4 class="panel-title">Selecciona el integrador</h4>
</div>
<div class="panel-body panel-form">
<form class="form-horizontal form-bordered" method ='POST'>
<div class="form-group">
<label class="control-label col-md-4">Integrador</label>
<div class="col-md-8">
<select class="form-control selectpicker" data-size="10" data-live-search="true" data-style="btn-white" id="combo" name="combo"; onchange="submit();";>
<?php
$plat = 1;
$horaActual = date('H', (strtotime ("+1 Hours")));
try{
$conexion = new MySQL(0);
if ($horaActual >= 22){
$query = ' select id_integrador, descripcion
from billing.'.strtolower($name1).'_i
where fecha = date(date_add((NOW()), INTERVAL -6 hour))
group by id_integrador, descripcion
order by descripcion asc;';
}else{
$query = ' select id_integrador, descripcion
from billing.'.strtolower($name1).'_i
where fecha = date(date_add((NOW()), INTERVAL -6 hour))
group by id_integrador, descripcion
order by descripcion asc;';
}
$combo= $conexion->consulta($query);
if ((! $combo)){
throw new Exception ("No se logro obtener informacion de cobros....\n");
}else{
if($integrador == 0){
echo "<option value='' selected>Integrador</option>";
}
while ($dato= $conexion->fetch_row($combo)){
if($integrador == $dato[0]){
$tituloG = $dato[1];
echo '<option value='.$dato[0].' selected>'.$dato[1].'</option>';
}else{
echo '<option value='.$dato[0].'>'.$dato[1].'</option>';
}
}
}
$conexion->MySQLClose();
}catch(Exception $e){
echo 'Excepcion capturada: ', $e->getMessage(), "\n";
}
?>
</select>
</div>
</div>
</form>
</div>
</div>
<!-- end panel -->
<!-- BEGIN CarrierD_I -->
<div class="panel panel-inverse" data-sortable-id="ui-buttons-2">
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
</div>
<h4 class="panel-title"><?php if($tituloG == ''){echo "Integrador";}else{echo $tituloG;}?></h4>
</div>
<div class="panel-body">
<div id="CarrierD_I" class="height-sm"></div>
</div>
</div>
<!-- END CarrierD_I -->
</div>
<!-- end col-4 -->
<!-- begin col-8 Integradores -->
<div class="col-md-8">
<!--Begin Panel Promedios-->
<div class="panel panel-inverse" data-sortable-id="table-basic-7">
<div class="panel-heading">
<h4 class="panel-title">Transacciones</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Integrador</th>
<th>Cobros Hoy</th>
<th>Promedio de Cobros</th>
<th>Porcentaje del Dia</th>
</tr>
</thead>
<tbody>
<tr> <?php
echo '<td>'.$tituloG.'</td>';
$conexion = new MySQL($bd_id);
$query = 'select sum(qty) Cobros
from '.$schema.'.resume_carrier
where created_date >= left(NOW() - INTERVAL 6 HOUR,10) and type in ("DB") and status = "Success" and integrator_id ='.$integrador.' ';
$exec = $conexion->consulta($query);
$row = $conexion->fetch_row($exec);
$value = $row[0];
$query = 'select sum(qty) Cobros
from '.$schema.'.resume_carrier
where created_date between left((CURDATE() - INTERVAL 168 HOUR),10) and left((CURDATE()) - INTERVAL 6 HOUR,10)
and type in ("DB") and status = "Success" and integrator_id ='.$integrador.' and integrator_id <> 0;';
$exec = $conexion->consulta($query);
$row = $conexion->fetch_row($exec);
$value2 = $row[0]/7;
$value3 = ($value2 == 0) ? 0 : (($value*100)/$value2);
echo"<td>".number_format($value)."</td><td align=\"center\">".number_format($value2)."</td>";
echo"<td align=\"left\">".number_format($value3)."%</td>";
?>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- End Panel Promedios-->
<!--Begin Panel Integradores-->
<div class="panel panel-inverse" data-sortable-id="ui-buttons-1"->
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
</div>
<h4 class="panel-title">Productos</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table69" class="table table-striped table-bordered">
<thead>
<tr>
<th>Id Producto</th>
<th>Descripcion</th>
<th>Transacciones Exitosas</th>
</tr>
</thead>
<?php
$fecha = date('H', (strtotime ("+1 Hours")));
$fecha1 = date("Y-m-d");
$query = ' select a.product_id,b.product_name,sum(a.qty)
from '.$schema.'.resume_billing a
join '.$schema.'.product_master b on a.product_id=b.product_id
where a.integrator_id = '.$integrador.' and a.created_date = date(date_add((NOW()), INTERVAL -6 hour))
and date(now()) and a.price > 0
group by a.product_id ,b.product_name
order by sum(a.qty) desc;';
$conexion = new MySQL($bd_id);
$exec = $conexion->consulta($query);
echo "<tbody>";
while ($row2= $conexion->fetch_row($exec)){
echo "<tr><td>$row2[0]</td><td><a onclick=\"GotoDetails($integrador,$row2[0])\">$row2[1]<a></td><td>".number_format($row2[2])."</td></tr>";
}
echo"</tbody>"
?>
</table>
</div>
</div>
</div>
<!-- End Panel Integradores-->
</div>
<!-- end col-8 Integradores-->
<!-- begin col-12 -->
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="table-basic-7">
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
</div>
<h4 class="panel-title">Cobros Por Dia</h4>
</div>
<div class="panel-body">
<div id="ex0" class="height-sm"></div>
</div>
</div>
<!-- end panel -->
<!-- begin panel contactos integradores -->
<div class="panel panel-inverse" data-sortable-id="table-basic-7">
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-warning" data-click="panel-collapse"><i class="fa fa-minus"></i></a>
</div>
<h4 class="panel-title">Contactos Integrador</h4>
</div>
<div class="panel-body" style="display: none;">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Nombre</th>
<th>Organizacion</th>
<th>Email</th>
<th>Telefono</th>
</tr>
</thead>
<tbody>
<?php
$numero=1;
$conexion = new MySQL(0);
$contactos='select * from contacts where id_carrier=1 and id_integrador ='.$integrador.'';
$result69= $conexion->consulta($contactos);
while($row69= $conexion->fetch_row($result69)){
echo"<tr><td>$numero</td><td>$tituloG</td><td>$row69[3]</td><td>$row69[4]</td><td>$row69[5]</td></tr>";
$numero++;}
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- end panel contactos integradores -->
</div>
<!-- end col-12 -->
</div><br>
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<?php include(TEMPLATE.DS.'footer.php');?>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/ionRangeSlider/js/ion-rangeSlider/ion.rangeSlider.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-colorpicker/js/bootstrap-colorpicker.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/masked-input/masked-input.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-timepicker/js/bootstrap-timepicker.min.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/password-indicator/js/password-indicator.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-combobox/js/bootstrap-combobox.js"></script>
<script src="<?=WEBROOT.DS;?>plugins/bootstrap-select/bootstrap-select.min.js"></script>
<script>
$(document).ready(function() {
App.init();
TableManageDefault.init();
//Chart.init();
FormPlugins.init();
$('#data-table69').dataTable( {
"order": [[ 2, 'desc' ]]
} );
});
</script>
</body>
</html>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
<!--Comienza-->
var data1 = new google.visualization.DataTable();
data1.addColumn('number', 'Hora');
data1.addColumn('number', 'Promedio');
data1.addColumn('number', 'Ayer');
data1.addColumn('number', 'Hoy');
<?php
echo $data1;
?>
var options1 = {
title: '<?php echo 'Cobros '.$tituloG;?>',
hAxis: {title: 'Hora', titleTextStyle: {color: '#333'}, ticks: data1.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {lineDashStyle: [2, 2]},
1: {lineDashStyle: [2, 2]},
},
colors: ['#9EABB4','#01AEBF','#0fd43a'],
legend: { position: 'top' },
chartArea:{width:'70%',height:'60%'}
};
var formatter1 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter1.format(data1, 1);
formatter1.format(data1, 2);
formatter1.format(data1, 3);
var chart1 = new google.visualization.AreaChart(document.getElementById('CarrierD_I'));
chart1.draw(data1, options1);
/*----------------------*/
var data3 = new google.visualization.DataTable();
data3.addColumn('string', 'Dia');
data3.addColumn('number', 'Cobros');
<?php
echo $data10;
?>
var options = {
colors:['#1DB05A'],
title: 'Cobros totales por Dia',
legend: { position: 'top' },
chartArea:{width:'76%',height:'60%'},
hAxis: {
title: 'Dia',
minValue: 0
},
vAxis: {
title: 'Cobros'
}
};
var formatter2 = new google.visualization.NumberFormat(
{negativeColor: 'black', negativeParens: true, pattern: '###,###'});
formatter2.format(data3, 1);
var chart = new google.visualization.ColumnChart(
document.getElementById('ex0'));
chart.draw(data3, options);
}
$(window).resize(function(){
drawChart();
});
function GotoDetails(inte,prod) {
var redirect = 'http://<?php echo URL; ?>/detalle/<?php echo $name1;?>P';
$.redirectPost(redirect, {combo1: inte, combo2: prod});
}
$.extend({
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="'+location+'" method="POST">'+form+'</form>').submit();
}
});
</script>
<file_sep>/Billing/index.php
<?php
define('CMSPATH',str_replace("\\","/",dirname(__FILE__)));
define('DS',"/");
define('COREPATH',CMSPATH.DS.'core');
require_once COREPATH.DS."loader.php";
$access = Import::load("lib","Start_Page");
$access = $access and import::load('lib', 'view');
$access = $access and import::load('lib', 'Validate_Auth');
validate_auth::start();
$LestStart = new Start_Page();
if ($access){
if ($LestStart->checkURL() == URL.DS){
header( 'Location: http://'.URL.DS.'login'.DS."start" );
}else{
$LestStart->start();
}
}else{
echo "No se logro realizar la carga de los archivos.";
}
?>
<file_sep>/Billing/app/modules/minimodules/dashboard/guardia.php
<?php
import::load('lib', 'MySQL');
$conexion = new MySQL(6);
?>
<!-- begin page-header -->
<h1 class="page-header">Servicios <small>Detalle de servicios alarmados para Legacy y David</small></h1>
<!-- end page-header -->
<!-- ****************************** Server Newrelic ******************************************* -->
<div>
<!-- begin col-4 -->
<div class="col-md-4">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="index-2">
<div class="panel-heading">
<h4 class="panel-title">Servidores NewRelic
<?php
$strConsulta = "select cantidad from monitor where id_servicio =4";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){//if($var>0){
?>
<span class="label label-danger pull-right">Alarmas: <?= $row['cantidad'];?></span>
<?php
}else{
?>
<span class="label label-Success pull-right">OK</span>
<?php } ?>
</h4>
</div>
<div class="panel-body bg-silver">
<div data-scrollbar="true" data-height="225px">
<center>
<img src="<?=WEBROOT.DS?>img/server1.png" class="animated rubberBand" alt="Sample Image 1">
</center>
<a href="#modal-dialog" class="btn btn-sm btn-success" onclick="clickButton(4);" data-toggle="modal">Detalle</a>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-4 -->
<!-- ****************************** Servicios Newrelic ******************************************* -->
<!-- begin col-4 -->
<div class="col-md-4">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="index-2">
<div class="panel-heading">
<h4 class="panel-title">Servicios NewRelic
<?php
$strConsulta = "select cantidad from monitor where id_servicio =5";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){//if($var>0){
?>
<span class="label label-danger pull-right">Alarmas: <?= $row['cantidad'];?></span>
<?php
}else{
?>
<span class="label label-Success pull-right">OK</span>
<?php } ?>
</h4>
</div>
<div class="panel-body bg-silver">
<div data-scrollbar="true" data-height="225px">
<center>
<img src="<?=WEBROOT.DS?>img/apps1.png" class="animated rubberBand" alt="Sample Image 1">
</center>
<a href="#modal-dialog" class="btn btn-sm btn-success" onclick="clickButton(5);" data-toggle="modal">Detalle</a>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-4 -->
<!-- ****************************** Key Transaction Newrelic ******************************************* -->
<!-- begin col-4 -->
<div class="col-md-4">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="index-2">
<div class="panel-heading">
<h4 class="panel-title">Key Transaction
<?php
$strConsulta = "select cantidad from monitor where id_servicio =6";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){//if($var>0){
?>
<span class="label label-danger pull-right">Alarmas: <?= $row['cantidad'];?></span>
<?php
}else{
?>
<span class="label label-Success pull-right">OK</span>
<?php } ?>
</h4>
</div>
<div class="panel-body bg-silver">
<div data-scrollbar="true" data-height="225px">
<center>
<img src="<?=WEBROOT.DS?>img/porcess1.png" class="animated rubberBand" alt="Sample Image 1">
</center>
<a href="#modal-dialog" class="btn btn-sm btn-success" onclick="clickButton(6);" data-toggle="modal">Detalle</a>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-4 -->
<!-- ****************************** Monitoring ******************************************* -->
<!-- begin col-4 -->
<div class="col-md-4">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="index-2">
<div class="panel-heading">
<h4 class="panel-title">Monitoring
<?php
$strConsulta = "select cantidad from monitor where id_servicio =7";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){//if($var>0){
?>
<span class="label label-danger pull-right">Alarmas: <?= $row['cantidad'];?></span>
<?php
}else{
?>
<span class="label label-Success pull-right">OK</span>
<?php } ?>
</h4>
</div>
<div class="panel-body bg-silver">
<div data-scrollbar="true" data-height="225px">
<center>
<img src="<?=WEBROOT.DS?>img/monitoring1.png" class="animated rubberBand" alt="Sample Image 1">
</center>
<a href="#modal-dialog" class="btn btn-sm btn-success" onclick="clickButton(7);" data-toggle="modal">Detalle</a>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-4 -->
<!-- ****************************** RXTX Legacy ******************************************* -->
<!-- begin col-4 -->
<div class="col-md-4">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="index-2">
<div class="panel-heading">
<h4 class="panel-title">RX/TX Legacy
<?php
$strConsulta = "select cantidad from monitor where id_servicio =1";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){//if($var>0){
?>
<span class="label label-danger pull-right">Alarmas: <?= $row['cantidad'];?></span>
<?php
}else{
?>
<span class="label label-Success pull-right">OK</span>
<?php } ?>
</h4>
</div>
<div class="panel-body bg-silver">
<div data-scrollbar="true" data-height="225px">
<center>
<img src="<?=WEBROOT.DS?>img/RXTX.png" class="animated rubberBand" alt="Sample Image 1">
</center>
<a href="#modal-dialog" class="btn btn-sm btn-success" onclick="clickButton(1);" data-toggle="modal">Detalle</a>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-4 -->
<!-- ****************************** GATEWAY Legacy ******************************************* -->
<!-- begin col-4 -->
<div class="col-md-4">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="index-2">
<div class="panel-heading">
<h4 class="panel-title">Status Gateway
<?php
$strConsulta = "select cantidad from monitor where id_servicio =2";
$consulta = $conexion->consulta($strConsulta);
$row= $conexion->fetch_array($consulta);
if($row['cantidad'] > 0){//if($var>0){
?>
<span class="label label-danger pull-right">Alarmas: <?= $row['cantidad'];?></span>
<?php
}else{
?>
<span class="label label-Success pull-right">OK</span>
<?php } ?>
</h4>
</div>
<div class="panel-body bg-silver">
<div data-scrollbar="true" data-height="225px">
<center>
<img src="<?=WEBROOT.DS?>img/gateway1.png" class="animated rubberBand" alt="Sample Image 1">
</center>
<a href="#modal-dialog" class="btn btn-sm btn-success" onclick="clickButton(2);" data-toggle="modal">Detalle</a>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-4 -->
</div><file_sep>/Billing/app/modules/minimodules/dashboard/metricas.php
<?php
/********************************Inicio Llamado de cada grafica******************************/
/**/$conexion = new MySQL(0);
/**/$query = 'CALL GetGraphList();';
/**/$result = $conexion->consulta($query);
/**/$conexion->prepareNextResult();
/**/$IhaveSomeChargeInfo = '';
/**/$HtmlCode = '';
/**/$JSCode = '';
/**/
/**/if(! $result){
/**/ throw new Exception ("No se logro obtener informacion de cobros....\n");
/**/}else{
/**/ $IhaveSomeChargeInfo = DrawSomeTables();
/**/ $contData = 0;
/**/ while ($carrier = $conexion->fetch_row($result)){
$carrierN = ($carrier[0] == 'SACA') ? 'SAGUA' : $carrier[0];
/**/ $dataMericas = getData($carrier[0],$contData);
/**/ $HtmlCode = $HtmlCode.getMyHTMLCode($carrierN);
/**/ $JSCode = $JSCode.getMyJSCode($carrierN,$contData,$dataMericas);
/**/ $contData++;
/**/ }
/**/}
/**///print_r($dataMericas);
/**/$conexion->MySQLClose();
/***********************************Fin Llamado de cada grafica******************************/
function getData($name,$num){
$dataArray = "";
try{
$conexion = new MySQL(0);
$query0 = ' select hour(date_add(NOW(), INTERVAL -'.HOURDB.' hour));';
$result0 = $conexion->consulta($query0);
$exec0 = $conexion->fetch_row($result0);
$fecha = $exec0[0];
$query = 'CALL GetCarrierChargeToday("'.strtolower($name).'",'.HOURDB.');';
$result = $conexion->consulta($query);
$conexion->prepareNextResult();
$query1 = 'CALL GetCarrierChargeYesterday("'.strtolower($name).'",'.HOURDB.');';
$result1 = $conexion->consulta($query1);
$conexion->prepareNextResult();
$query2 = 'CALL GetCarrierChargeProm("'.strtolower($name).'",'.HOURDB.');';
$result2 = $conexion->consulta($query2);
$conexion->prepareNextResult();
if ((! $result) or (! $result1) or (! $result2)){
throw new Exception ("No se logro obtener informacion de cobros....\n");
}else{
$cont = 0;
@$hoy = $conexion->fetch_row($result);
@$ayer = $conexion->fetch_row($result1);
@$prom = $conexion->fetch_row($result2);
while ($cont <= $fecha){
if(($ayer[1] == $cont) and ($ayer[1] != '')){
@$valor = $ayer[0];
@$ayer = $conexion->fetch_row($result1);
}else{
$valor = 0;
}
if(($hoy[1] == $cont) and ($hoy[1] != '')){
@$valor1 = $hoy[0];
@$hoy = $conexion->fetch_row($result);
}else{
$valor1 = 0;
}
if(($prom[1] == $cont) and ($prom[1] != '')){
@$valor2 = $prom[0];
@$prom = $conexion->fetch_row($result2);
}else{
$valor2 = 0;
}
$dataArray = $dataArray."\t\t\tdata".$num.'.addRow(['.$cont.', '.number_format($valor2,0,'','').', '.$valor.' , '.$valor1.']);'."\n";
$cont++;
}
}
$conexion->MySQLClose();
}catch(Exception $e){
echo 'Excepcion capturada: ', $e->getMessage(), "\n";
}
return $dataArray;
}
function getMyHTMLCode($name){
$HtmlCode = ' <!-- begin '.$name.' -->';
$HtmlCode = $HtmlCode.' <div class="col-md-4">
<div class="panel panel-inverse" data-sortable-id="flot-chart-6">
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
</div>
<h4 class="panel-title">'.$name.'</h4>
</div>
<div class="panel-body">
<div id="'.$name.'" class="height-sm"></div>
</div>
</div>
</div>';
return $HtmlCode;
}
function getMyJSCode($name,$num,$data){
$JSCode = '
var data'.$num.' = new google.visualization.DataTable();
data'.$num.'.addColumn(\'number\', \'Hora\');
data'.$num.'.addColumn(\'number\', \'Promedio\');
data'.$num.'.addColumn(\'number\', \'Ayer\');
data'.$num.'.addColumn(\'number\', \'Hoy\');
'.$data.'
var options'.$num.' = {
title: \'Cobro '.$name.'\',
hAxis: {title: \'Hora\', titleTextStyle: {color: \'#333\'}, ticks: data'.$num.'.getDistinctValues(0)},
vAxis: {minValue: 0},
pointSize: 5,
series:{
0: {lineDashStyle: [2, 2]},
1: {lineDashStyle: [2, 2]}
},
colors: [\'#9EABB4\',\'#01AEBF\',\'#0fd43a\'],
legend: { position: \'top\' },
chartArea:{width:\'70%\',height:\'60%\'}
};
var formatter'.$num.' = new google.visualization.NumberFormat(
{negativeColor: \'black\', negativeParens: true, pattern: \'###,###\'});
formatter'.$num.'.format(data'.$num.', 1);
formatter'.$num.'.format(data'.$num.', 2);
formatter'.$num.'.format(data'.$num.', 3);
var chart'.$num.' = new google.visualization.AreaChart(document.getElementById(\''.$name.'\'));
chart'.$num.'.draw(data'.$num.', options'.$num.');';
return $JSCode;
}
function DrawSomeTables(){
$Table = '';
$conexionD = new MySQL(0);
$query = 'call GetMaxTable();';
$exec = $conexionD->consulta($query);
$conexionD->prepareNextResult();
$resultado = $conexionD->fetch_row($exec);
$numFields = $resultado[1];
$query = 'call GetDataTable();';
$exec = $conexionD->consulta($query);
$conexionD->prepareNextResult();
$tempT2 = $tempT1 = '
<div class="CSSTableGenerator" style="display:inline-block;">
<table>
<tr>
<td >Super Agregador</td>
<td >Cobros Hoy</td>
<td >Promedio</td>
<td >Porcentaje</td>
</tr>
';
while ($row = $conexionD->fetch_row($exec)){
$nombreC = ($row[0] == 'saca') ? 'SAGUA' : $row[0];
$CantHoy = number_format($row[1]);
$CantProm = number_format($row[2]);
$CantPor = ($CantProm == 0) ? 0 : number_format(($CantHoy*100)/$CantProm);
switch ($row[3]) {
case 1:
$tempT1 = $tempT1 .'<tr><td align="center"><a href="http://'.URL.DS.'detalle/'.strtolower($nombreC).'"> '.strtoupper($nombreC).' </a> </td><td align="right">'.$CantHoy.'</td><td align="right">'.$CantProm.'</td><td align="right">'.$CantPor.'%</td></tr>';
break;
case 2:
$tempT2 = $tempT2 .'<tr><td align="center"><a href="http://'.URL.DS.'detalle/'.strtolower($nombreC).'"> '.strtoupper($nombreC).' </a> </td><td align="right">'.$CantHoy.'</td><td align="right">'.$CantProm.'</td><td align="right">'.$CantPor.'%</td></tr>';
break;
}
}
$tempT1 = $tempT1 .'
</table>
</div>
<div style="display:inline-block;"></div>';
$tempT2 = $tempT2 .'
</table>
</div>
<div style="display:inline-block;"></div>';
$Table = $tempT1.$tempT2;
return $Table;
}
?><file_sep>/Billing/core/Script_cobros_Monitor_V2.php
<?php
/*---------------------------------Script de cobros por Hora-------------------------------*/
define('PATH',str_replace("\\","/",dirname(__FILE__)));
define('DS',"/");
define('LIB',PATH.DS.'lib');
define('LOGS',PATH.DS.'logs');
$logFile = "BillingMonitorService";
//echo LOGS.DS.$logFile.date('Y_m_d').".txt";
$fp = fopen(LOGS.DS.$logFile.date('Y_m_d').".txt", "a");
fputs($fp, "[".date('Y-m-d H:i:s')."] Inicio de servicio de actualizacion de BD\n");
fputs($fp, "[".date('Y-m-d H:i:s')."]Parametrizacion de rutas y valores....\n\n");
fputs($fp, "[".date('Y-m-d H:i:s')."]Librerias a cargar: \n");
fputs($fp, "[".date('Y-m-d H:i:s')."]".LIB.DS."MySQL.php \n");
fputs($fp, "[".date('Y-m-d H:i:s')."]".LIB.DS."BDCobros.php \n");
fputs($fp, "[".date('Y-m-d H:i:s')."]Parametrizacion de rutas y valores....\n\n");
$step = 1;
fputs($fp, "[".date('Y-m-d H:i:s')."]Requerimiento de librerias....\n");
try{
if ((! @include_once( LIB.DS."MySQL.php" )) and (! @include_once( LIB.DS."BDCobros.php" ))){
$pass = false;
throw new Exception ('No se encontro la clase: MySql');
}
else{
require_once LIB.DS."MySQL.php";
require_once LIB.DS."BDCobros.php";
$pass = true;
}
}catch(Exception $e){
fputs($fp, "[".date('Y-m-d H:i:s').']Excepcion capturada: '.$e->getMessage()."\n");
$step = 0;
}
if($step){
$coreBD = new BDCobros();
$coreBD->StartLog($logFile);
fputs($fp, "[".date('Y-m-d H:i:s')."]Cargando procesos...........\n");
$execute = $coreBD->LoadAllServices();
fputs($fp, "[".date('Y-m-d H:i:s')."]Iniciando Procesos..........\n");
$coreBD->StartProcess($execute,3,false);
fputs($fp, "[".date('Y-m-d H:i:s')."]Procesos Finalizado..........\n");
fclose($fp);
}
?>
<file_sep>/Billing/app/modules/usuario/usuario_old.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/core/import.php');
import::load('lib', 'Validate_Auth');
import::load('core', 'Start_page');
import::load('lib', 'Session');
import::load('lib', 'MySQL');
import::load('lib', 'view');
class Usuario{
function __construct(){
$this->titulo = 'Billing Vas Pass';
$this->mensaje = '';
}
function start($mensaje){
if(self::check()){
if($_SESSION['access'] == 1){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("usuario/usuario.php",$data);
}else{
$_SESSION['value'] = 'Acceso denegado';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function edit($mensaje){
if(self::check()){
if($_SESSION['access'] == 1){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("usuario/editar.php",$data);
}else{
$_SESSION['value'] = 'Acceso denegado';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function delete($mensaje){
if(self::check()){
if($_SESSION['access'] == 1){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("usuario/baja.php",$data);
}else{
$_SESSION['value'] = 'Acceso denegado';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function profile($mensaje){
if(self::check()){
$data = array("Titulo" => "Billing Vas Pass", "mensaje" => $mensaje);
self::LoadTemplate("login/profile.php",$data);
}else{
exit(header( 'Location: http://'.URL.DS));
}
}
function save(){
if( (isset($_POST["User"])) and (isset($_POST["pass"])) and (isset($_POST["email"])) and (isset($_POST["selector"])) and (isset($_POST["nombre"]))
and ($_POST["User"] != '') and ($_POST["pass"] != '') and ($_POST["email"] != '') and ($_POST["selector"] != '') and ($_POST["nombre"] != '') ){
$conexion = new MySQL(0);
$strIngreso = "select usuario from usuario where usuario = '".$_POST["User"]."';";
$value1 = $conexion->consulta($strIngreso);
$cant = $conexion->num_rows($value1);
if ($cant==0){
$strIngreso = " insert into usuario (usuario, pass, fecha, estatus, id_rol,nombre, email)
values('".$_POST["User"]."','".$_POST["pass"]."',now(),'Activo',".$_POST["selector"].",'".$_POST["nombre"]."','".$_POST["email"]."');" ;
$value = $conexion->consulta($strIngreso);
$conexion->MySQLClose();
$_SESSION['value'] = 'Usuario creado exitosamente.';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}else{
//self::start('error2');
$_SESSION['value'] = "error2";
session_write_close();
exit(header( 'Location: http://'.URL.DS.'usuario'.DS.'start'));
}
}else{
//self::start('error');
$_SESSION['value'] = "error";
session_write_close();
exit(header( 'Location: http://'.URL.DS.'usuario'.DS.'start'));
}
}
function save1(){
if( (isset($_POST["pass"])) and (isset($_POST["pass1"])) and (isset($_POST["pass2"])) and ($_POST["pass"] != '') and ($_POST["pass1"] != '') and ($_POST["pass2"] != '')){
if ($_POST["pass"]===$_POST["pass1"]){
$conexion = new MySQL(0);
$p = $_POST["pass"];
$strIngreso = "select pass from usuario where usuario = '".$_SESSION["login"]."';";
$value1 = $conexion->consulta($strIngreso);
$cant = $conexion->fetch_array($value1);
if (($_POST["pass"] != $cant[0]) and ($_POST["pass2"] === $cant[0])) {
$strIngreso = "update usuario set pass = '$p' where usuario = '".$_SESSION["login"]."';";
$value1 = $conexion->consulta($strIngreso);
$_SESSION['value'] = 'Contraseña actualizada exitosamente.';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}else{
$_SESSION['value'] = "error3";
session_write_close();
exit(header( 'Location: http://'.URL.DS.'usuario'.DS.'profile'));
}
}else{
$_SESSION['value'] = "error2";
session_write_close();
exit(header( 'Location: http://'.URL.DS.'usuario'.DS.'profile'));
}
}else{
$_SESSION['value'] = "error";
session_write_close();
exit(header( 'Location: http://'.URL.DS.'usuario'.DS.'profile'));
}
}
function refresh(){
if( (isset($_POST["User"])) and (isset($_POST["pass"])) and (isset($_POST["email"])) and (isset($_POST["selector"])) and (isset($_POST["nombre"]))
and ($_POST["User"] != '') and ($_POST["pass"] != '') and ($_POST["email"] != '') and ($_POST["selector"] != '') and ($_POST["nombre"] != '') ){
$conexion = new MySQL(0);
$value = $conexion->consulta("select * from rol where usuario ='".$_POST["selector"]."';");
$row= $conexion->fetch_array($value);
$strIngreso = ' update usuario
set usuario = "'.$_POST["User"].'", pass ="'.$_POST["pass"].'",
estatus="'.$_POST["selector3"].'", id_rol='.$row['ID_Rol'].',
nombre ="'.$_POST["nombre"].'",email="'.$_POST["email"].'"
where Id_usuario = "'.$_POST["usuario"].'";' ;
$value1 = $conexion->consulta($strIngreso);
$conexion->MySQLClose();
$_SESSION['value'] = 'Usuario actualizado exitosamente.';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}else{
$_SESSION['value'] = "error";
session_write_close();
exit(header( 'Location: http://'.URL.DS.'usuario'.DS.'edit'));
}
}
function disable(){
if ((isset($_POST["usuario"])) and ($_POST["usuario"] != '')){
$conexion = new MySQL(0);
$strIngreso = "update usuario set estatus = 'Baja' where Id_usuario = '".$_POST["usuario"]."';" ;
$value = $conexion->consulta($strIngreso);
$conexion->MySQLClose();
$_SESSION['value'] = 'El usuario fue dado de baja.';
session_write_close();
exit(header( 'Location: http://'.URL.DS.'dashboard'.DS.'start'));
}else{
$_SESSION['value'] = "error";
session_write_close();
exit(header( 'Location: http://'.URL.DS.'usuario'.DS.'delete'));
}
}
private function check(){
return Validate_Auth::check();
}
private function LoadTemplate($template, $dataArr){
if (file_exists(TEMPLATE.DS.$template)){
Validate_Auth::start();
$view = new view($template);
if (!empty($dataArr)){
$view->render($dataArr);
}else{
$tempArr = array('NO' => 'DATA');
$view->render($tempArr);
}
}else{
echo 'Error!!! el template al que deseas accesar no existe. ';
echo $template;
}
}
}
?><file_sep>/Billing/app/modules/minimodules/guardia/Chargins2.php
<?php
$user = 'openalonzo';
$password = '<PASSWORD>';
$server = '192.168.2.101\SQLMercurio';
$database = 'SMSNET_ADMIN';
$conexión = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
odbc_exec($conexión,"USE SMSNET_ADMIN");
$body = " <table id='ticker-table' class='table m-table table-bordered table-hover table-heading'>
<thead>
<tr>
<th>Super Agregador</th>
<th>Cobros</th>
<th>Promedio</th>
<th>Weekly Chart</th>
</tr>
</thead>
<tbody>
<tr>
<td class='m-ticker'><b>SAMEX</b><span>Wau Movil.</span></td>";
$result = odbc_exec($conexión," select *
FROM
OPENQUERY([192.168.3.11], 'EXEC WauReports.dbo.[GetChargesSA]')");
$r= odbc_fetch_object($result);
$result2 = odbc_exec($conexión," select *
FROM
OPENQUERY([192.168.3.11], 'EXEC WauReports.dbo.[GetpercentageSA]')");
$r2= odbc_fetch_object($result2);
/*************************************************** SAMEX ********************************************************************/
$body = $body. "<td class='m-price'>".$r->SAMEX."</td>";
$body = $body. "<td class='m-change'>".$r2->SAMEX." (".(($r->SAMEX*100)/$r2->SAMEX)."%)</td>";
$body = $body. "<td class='td-graph'></td>
</tr>
<tr>
<td class='m-ticker'><b>SAPER</b><span>Wau Movil.</span></td>";
/*************************************************** SAPER ********************************************************************/
$body = $body. "<td class='m-price'>".$r->SAPER."</td>";
$body = $body. "<td class='m-change'>".$r2->SAPER." (".(($r->SAPER*100)/$r2->SAPER)."%)</td>";
$body = $body. "<td class='td-graph'></td>
</tr>
<tr>
<td class='m-ticker'><b>SANIC</b><span>Wau Movil.</span></td>";
/*************************************************** SANIC ********************************************************************/
$body = $body. "<td class='m-price'>".$r->SANIC."</td>";
$body = $body. "<td class='m-change'>".$r2->SANIC." (".(($r->SANIC*100)/$r2->SANIC)."%)</td>";
$body = $body. "<td class='td-graph'></td>
</tr>
<tr>
<td class='m-ticker'><b>SAECU</b><span>Wau Movil.</span></td>";
/*************************************************** SAECU ********************************************************************/
$body = $body. "<td class='m-price'>".$r->SAECU."</td>";
$body = $body. "<td class='m-change'>".$r2->SAECU." (".(($r->SAECU*100)/$r2->SAECU)."%)</td>";
$body = $body. "<td class='td-graph'></td>
</tr>
<tr>
<td class='m-ticker'><b>SAPAN</b><span>Wau Movil.</span></td>";
/*************************************************** SAPAN ********************************************************************/
$body = $body. "<td class='m-price'>".$r->SAPAN."</td>";
$body = $body. "<td class='m-change'>".$r2->SAPAN." (".(($r->SAPAN*100)/$r2->SAPAN)."%)</td>";
$body = $body. "<td class='td-graph'></td>
</tr>
</tbody>
</table>";
echo $body;
?><file_sep>/Billing/app/modules/minimodules/guardia/seguimiento.php
<div class="box col-md-12">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2>Servicios Monitoring</h2>
<div class="box-icon">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
<a href="#" class="btn btn-close btn-round btn-default"><i
class="glyphicon glyphicon-remove"></i></a>
</div>
</div>
<div class="box-content">
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Titulo</th>
<th>Fecha</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/core/import.php');
import::load('lib', 'MySQL');
$conexion = new MySQL();
$strConsulta = "select Titulo, fecha, estado
from falla
where estado <>'cerrada'
order by fecha desc";
$consulta = $conexion->consulta($strConsulta);
while($row2= $conexion->fetch_array($consulta)){
echo "<tr><td>";
echo $row2[0]."</td><td>".$row2[1]."</td>";
if($row2[2] == 'Abierta'){
echo '<td><span class="label label-success">'.$row2[2].'<span>';
}else{
echo '<td><span class="label label-warning">'.$row2[2].'<span>';
}
echo "</td></tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div><file_sep>/Billing/app/templates/database/editar.php
<?php include(TEMPLATE.DS.'header.php');?>
<body>
<?php include(TEMPLATE.DS.'top.php');?>
<?php include(TEMPLATE.DS.'menu.php');
if(isset($_POST['combo'])){$valor=$_POST['combo'];unset($_POST['combo']);}else{$valor = 0;}
?>
<!--********************************* begin #content ********************************************************************-->
<div id="content" class="content">
<!-- begin breadcrumb -->
<!-- end breadcrumb -->
<!-- begin page-header -->
<h1 class="page-header">Edicion de Host<small></small></h1>
<!-- end page-header -->
<div class="row">
<div id="DavidMod"></div>
<!-- #modal-dialog -->
<div class="modal fade" id="modal-dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Detalle de Alarmas.</h4>
</div>
<div class="modal-footer">
<a href="javascript:;" class="btn btn-sm btn-white" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
</div>
<!-- begin col-6 -->
<div class="col-md-6">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="form-validation-1">
<div class="panel-heading">
<div class="panel-heading-btn">
</div>
<h4 class="panel-title">Host a Editar</h4>
</div>
<div class="panel-body">
<form class="form-horizontal form-bordered" data-parsley-validate="true" name="demo-form" method="post">
<div class="form-group">
<label class="control-label col-md-4">Seleccione el servicio</label>
<div class="col-md-8">
<select class="form-control selectpicker" data-size="10" data-live-search="true" data-style="btn-white" name="combo" id="combo" onchange="submit();";>
<?php
import::load('lib', 'MySQL');
$query = " select id_base,descripcion
from billing.bases_cobro
where id_base not in (".$valor.");";
$conexion = new MySQL(0);
$exec = $conexion->consulta($query);
$query2 = " Select id_base,descripcion
from billing.bases_cobro
where id_base=".$valor.";";
//$conexion = new MySQL(0);
$exec2 = $conexion->consulta($query2);
$row = $conexion->fetch_row($exec2);
echo '<option value="'.$valor.'" selected>'.$row[1].'</option>';
while ($row2= $conexion->fetch_row($exec)){
echo "<option value= ".$row2[0]." >".$row2[1]."</option>";
}
$query = " Select descripcion,host_conexion,user,pass
from billing.bases_cobro
where id_base = ".$valor.";";
$exec = $conexion->consulta($query);
$row2= $conexion->fetch_row($exec);
if($row2[0]==""){$show = "Required";$show2 = "Required";}else{$show = $row2[0];$show2 = $row2[1];}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Descripcion * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="descripcion" name="descripcion" data-parsley-required="true" <?php if($row2[0]==""){?> placeholder="Required"<?php }else{?> value = <?php echo '"'.$row2[0].'"';}?> />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Host * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="host" name="host" data-parsley-required="true" <?php if($row2[1]==""){?> placeholder="Required"<?php }else{?> value = <?php echo '"'.$row2[1].'"';}?> />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">User * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="user" name="user" data-parsley-required="true" <?php if($row2[2]==""){?> placeholder="Required"<?php }else{?> value = <?php echo '"'.$row2[2].'"';}?> />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4" for="fullname">Pass * :</label>
<div class="col-md-6 col-sm-6">
<input class="form-control" type="text" id="pass" name="pass" data-parsley-required="true" <?php if($row2[3]==""){?> placeholder="Required"<?php }else{?> value = <?php echo '"'.$row2[3].'"';}?> />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 col-sm-4"></label>
<div class="col-md-6 col-sm-6">
<button type="submit" class="btn btn-primary" onclick = "this.form.action = 'http://<?=URL.DS;?>database/refresh'">Submit</button>
</div>
</div>
</form>
<?php if (isset($_SESSION['value']) and ($_SESSION['value'] == "ok")) {unset($_SESSION['value']);?>
<div class="alert alert-success fade in m-b-15">
<strong>Success!</strong>
Pais Editado correctamente.
<span class="close" data-dismiss="alert">×</span>
</div>
<?php }?>
<?php if (isset($_SESSION['value']) and ($_SESSION['value'] == "error")) {unset($_SESSION['value']);?>
<div class="alert alert-danger fade in m-b-15">
<strong>Error!</strong>
Debe seleccionar un pais.
<span class="close" data-dismiss="alert">×</span>
</div>
<?php }?>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-6 -->
<!-- begin row -->
<div class="row">
<!-- begin col-12 -->
<div class="col-md-6">
<!-- begin panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-success" data-click="panel-reload"><i class="fa fa-repeat"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-warning" data-click="panel-collapse"><i class="fa fa-minus"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-danger" data-click="panel-remove"><i class="fa fa-times"></i></a>
</div>
<h4 class="panel-title">Detalle de Host</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Descripcion</th>
<th>Host</th>
<th>Usuario</th>
</tr>
</thead>
<tbody>
<?php
import::load('lib', 'MySQL');
$query = " Select descripcion,host_conexion,user
from billing.bases_cobro;";
$conexion = new MySQL(0);
$exec = $conexion->consulta($query);
while ($row2= $conexion->fetch_row($exec)){
//if ($row2[2] == 1){$value = "Activo";}else{$value = "Baja";}
echo "<tr><td>$row2[0]</td><td>$row2[1]</td><td>$row2[2]</td></tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-12 -->
</div>
<!-- end row -->
</div>
<!--********************************* end #content ********************************************************************-->
<!-- begin scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top fade" data-click="scroll-top"><i class="fa fa-angle-up"></i></a>
<!-- end scroll to top btn -->
</div>
<!-- end page container -->
<script src="<?=WEBROOT.DS;?>js/ui-modal-notification.demo.min.js"></script>
</body>
</html>
<script src="<?=WEBROOT.DS;?>js/dashboard-v2.js"></script>
<?php include(TEMPLATE.DS.'footer.php');?>
<script>
$(document).ready(function() {
App.init();
TableManageDefault.init();
FormPlugins.init();
});
</script>
<file_sep>/Billing/app/modules/minimodules/guardia/KeyTransaction.php
<?php
$body = '
<!-- begin row -->
<div class="row">
<!-- begin col-12 -->
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<div class="panel-heading-btn">
</div>
<h4 class="panel-title">Data Table - Default</h4>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="data-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Nombre del Servido</th>
<th>App Server</th>
<th>Throughput</th>
<th>Error %</th>
</tr>
</thead>
<tbody>';
$curl = curl_init('https://api.newrelic.com/v2/key_transactions.json');
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Api-Key:7157dea6a415fe0c854831ef8b65f8adcdbd825ca5274e4","Content-Type: application/json"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
//echo $resp;
$servers = json_decode($resp,true);
curl_close($curl);
if(count($servers['key_transactions'])>0){
$var=0;
for($i=0;$i<count($servers['key_transactions']);$i++){
if ($servers['key_transactions'][$i]['health_status']=='gray'){
$body = $body. "<tr><td>";
$body = $body. '<span class="label-default label label-danger">'.$servers['key_transactions'][$i]['name'].'</span></td>';
$body = $body. '<td >';
$body = $body. '0 ms </td>';
$body = $body. '<td >';
$body = $body. '0 rpm </td>';
$body = $body. '<td >';
$body = $body. '0 % ';
$body = $body. "</td></tr>";
$var++;
}else{
if (($servers['key_transactions'][$i]['application_summary']['error_rate'] > 1)){
$body = $body. "<tr><td>";
$body = $body. '<span class="label-default label label-danger">'.$servers['key_transactions'][$i]['name'].'</span></td>';
$body = $body. '<td >';
$body = $body. $servers['key_transactions'][$i]['application_summary']['response_time'].'ms </td>';
$body = $body. '<td >';
$body = $body. $servers['key_transactions'][$i]['application_summary']['throughput'].'rpm </td>';
$body = $body. '<td >';
$body = $body. $servers['key_transactions'][$i]['application_summary']['error_rate'].'% ';
$body = $body. "</td></tr>";
$var++;
}
}
}
}
$body = $body.'</tbody>
</table>';
if ($var < 1){
$body = $body. '<tr> <div align="center">
<h5>No hay servicios alarmados</h5>
<ul class="ajax-loaders">
<li><img src="'.ROOT.DS.'img/ajax-loaders/ajax-loader-9.gif"
title="img/ajax-loaders/ajax-loader-9.gif"></li>
</ul>
</div></tr>';
}
$body = $body.'
</tbody>
</table>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-12 -->
</div>
<!-- end row -->';
echo $body;
?><file_sep>/Billing/app/modules/minimodules/guardia/comentario.php
<?php
$account="<EMAIL>";
$password="<PASSWORD>!";
$to="<EMAIL>";
$from="<EMAIL>";
$from_name="<NAME>";
//$msg="<strong>This is a bold text.</strong>"; // HTML message
$subject="HTML message";
$msg = '<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pase de Guardia</title>
<style type="text/css">
#psdgraphics-com-table {
margin:0;
padding: 4px;
width: 578px;
font: 11px Arial, Helvetica, sans-serif;
color:#747474;
background-color:#0c2a62;
}
#psdg-header {
margin:0;
padding: 14px 0 0 24px;
width: 554px;
height: 55px;
color:#FFF;
font-size:13px;
background: #0c2c65 url(images/head-bcg.jpg) no-repeat right top;
}
.psdg-bold {
font: bold 22px Arial, Helvetica, sans-serif;
}
#psdg-top {
margin:0;
padding: 0;
width: 578px;
height: 46px;
border-top: 2px solid #FFF;
background: #eff4ff url(images/top-light-blue.png) repeat-x left top;
}
.psdg-top-cell {
float:left;
padding: 15px 0 0 0;
text-align:center;
width:105px;
height: 31px;
border-right: 1px solid #ced9ec;
color:#1f3d71;
font: 13px Arial, Helvetica, sans-serif;
}
#psdg-middle {
margin:0;
padding: 0;
width: 578px;
background: #f6f6f6 url(images/center-bcg.png) repeat-y right top;
}
.psdg-left {
float:left;
margin:0;
padding: 10px 0 0 24px;
width: 129px;
text-align: left;
height: 25px;
border-right: 1px solid #ced9ec;
border-bottom: 1px solid #b3c1db;
color:#1f3d71;
font: 13px Arial, Helvetica, sans-serif;
background: #e4ebf8 url(images/center-blue.png) repeat-y left top;
}
.psdg-right {
float:left;
margin:0;
padding: 11px 0 0 0;
width: 105px;
text-align:center;
height: 24px;
border-right: 1px solid #ced9ec;
border-bottom: 1px solid #b3c1db;
}
#psdg-bottom {
clear:both;
margin:0;
padding: 0;
width: 578px;
height: 48px;
border-top: 2px solid #FFF;
background: #e4e3e3 url(images/bottom-line.png) repeat-x left top;
}
.psdg-bottom-cell {
float:left;
padding: 15px 0 0 0;
text-align:center;
width:105px;
height: 33px;
border-right: 1px solid #ced9ec;
color:#070707;
font: 13px Arial, Helvetica, sans-serif;
}
#psdg-footer {
font-size: 10px;
color:#8a8a8a;
margin:0;
padding: 8px 0 8px 12px;
width: 566px;
background: #f6f6f6 url(images/center-bcg.png) repeat-y right top;
}
</style>
</head>
<body>
<center>
<div id="psdgraphics-com-table">
<div id="psdg-header">
<span class="psdg-bold">NOC</span><br />
Pase de Guarda Hora:<br>
Usuario Entrega:<br>
</div>
<div id="psdg-top">
<div class="psdg-top-cell" style="width:129px; text-align:left; padding-left: 24px;">Servicios</div>
<div class="psdg-top-cell">Descripcion</div>
<div class="psdg-top-cell">Descripcion</div>
<div class="psdg-top-cell">Descripcion</div>
<div class="psdg-top-cell" style="border:none;">Descripcion</div>
</div>
<div id="psdg-middle">
<div class="psdg-left">Legacy</div>
<div class="psdg-right">Base de datos [Etiqueta OK]</div>
<div class="psdg-right">Beconnected [Etiqueta OK]</div>
<div class="psdg-right">Cobros[Etiqueta OK]</div>
<div class="psdg-right">Conexiones Base de datos [Etiqueta OK]</div>
<div class="psdg-left">David</div>
<div class="psdg-right">300 000</div>
<div class="psdg-right">300 000</div>
<div class="psdg-right">300 000</div>
<div class="psdg-right">300 000</div>
<div class="psdg-left">SAPER</div>
<div class="psdg-right">Firefox</div>
<div class="psdg-right">Firefox</div>
<div class="psdg-right">Firefox</div>
<div class="psdg-right">Firefox</div>
<div class="psdg-left">SAMEX</div>
<div class="psdg-right">Windows 7</div>
<div class="psdg-right">Windows 7</div>
<div class="psdg-right">Windows 7</div>
<div class="psdg-right">Windows 7</div>
<div class="psdg-left">SAECU</div>
<div class="psdg-right">1280x1024</div>
<div class="psdg-right">1280x1024</div>
<div class="psdg-right">1280x1024</div>
<div class="psdg-right">1280x1024</div>
<div class="psdg-left">SANIC</div>
<div class="psdg-right">.com</div>
<div class="psdg-right">.com</div>
<div class="psdg-right">.com</div>
<div class="psdg-right">.com</div>
<div class="psdg-left">Continent</div>
<div class="psdg-right">Europe</div>
<div class="psdg-right">Europe</div>
<div class="psdg-right">Europe</div>
<div class="psdg-right">Europe</div>
<div id="psdg-bottom">
<div class="psdg-bottom-cell" style="width:129px; text-align:left; padding-left: 24px;">Status:</div>
<div class="psdg-bottom-cell">Approved</div>
<div class="psdg-bottom-cell">Approved</div>
<div class="psdg-bottom-cell">Approved</div>
<div class="psdg-bottom-cell" style="border:none;">Approved</div>
</div>
</div>
<div id="psdg-footer">
Powered by: Mongolesforever!!!
</div>
</div>
</center>
</body>
</html>';
include_once(LIB1.DS."PHPMailer/PHPMailerAutoload.php");
//import::load('lib/PHPMailer', 'class.phpmailer');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth= true;
$mail->Port = 465; // Or 587
$mail->Username= $account;
$mail->Password= $<PASSWORD>;
$mail->SMTPSecure = 'ssl';
$mail->From = $from;
$mail->FromName= $from_name;
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $msg;
//$mail->addAddress($to);
//$mail->addCC($to);
$mail->addBCC($to);
//addCC
//addBCC
if(!$mail->send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo "E-Mail has been sent";
}
?> | 9fb62150d48302bcc5a7ec5dd20cf0232c06673c | [
"PHP"
]
| 51 | PHP | C0l0ch0/BPV_WAU | d10749b370838c5a5c1105a6b9376aef97d191d2 | 330d733eecc7705ef813e134b1523cf78c4eedd3 |
refs/heads/master | <repo_name>diegomfe/design-patterns<file_sep>/DesignPatterns.Application/Interfaces/IUserServices.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPatterns.Application.Interfaces
{
public interface IUserServices
{
void UserMethod();
}
}
<file_sep>/DesignPatterns.IoC/Injection.cs
using DesignPatterns.Application.Interfaces;
using DesignPatterns.Application.Services;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPatterns.IoC
{
public class Injection
{
public static void RegisterService(IServiceCollection services)
{
services.AddScoped<IUserServices, UserServices>();
}
}
}
<file_sep>/README.txt
Swagger:
https://docs.microsoft.com/pt-br/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-5.0&tabs=visual-studio<file_sep>/DesignPatterns.Web/Controllers/UserController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DesignPatterns.Application.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace DesignPatterns.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly IUserServices userServices;
public UserController(IUserServices services)
{
this.userServices = services;
}
[HttpGet]
public IActionResult Get()
{
return Ok("Ok!");
}
}
}<file_sep>/DesignPatterns.Application/Services/UserServices.cs
using DesignPatterns.Application.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPatterns.Application.Services
{
public class UserServices : IUserServices
{
public void UserMethod()
{ }
}
}
| c99d6e4f61dc83c0ad385b78954f419f8fbf6d32 | [
"C#",
"Text"
]
| 5 | C# | diegomfe/design-patterns | 1a76d70e4888911c200a025ea184e366298431ef | e04bc8d038c8559dcdb930a37ef4ae362e63ea49 |
refs/heads/master | <repo_name>uzakovnikita/frontend-project-lvl1<file_sep>/src/games/gcd.js
import getRandom from '../utils';
import engine from '../engine';
const searchGcd = (firstNumber, secondNumber) => {
if (secondNumber === 0) {
return firstNumber;
}
return searchGcd(secondNumber, firstNumber % secondNumber);
};
const generateConditions = () => {
const firstNumber = getRandom(0, 100);
const secondNumber = getRandom(0, 100);
const question = `${firstNumber} ${secondNumber}`;
const trueAnswer = searchGcd(firstNumber, secondNumber).toString();
const result = [question, trueAnswer];
return result;
};
const description = 'Find the greatest common divisor of given numbers.';
export default () => engine(generateConditions, description);
<file_sep>/src/games/progression.js
import engine from '../engine';
import getRandom from '../utils';
const lengthOfProgression = 10;
const generateConditions = () => {
const beginningOfProgression = getRandom(0, 100);
const progressionStep = getRandom(0, 100);
const progression = [];
for (let i = 0; i < lengthOfProgression; i += 1) {
if (i === 0) {
progression[i] = beginningOfProgression;
} else {
progression[i] = progressionStep + progression[i - 1];
}
}
let question = '';
const hiddenMemberIndex = getRandom(0, lengthOfProgression - 1);
for (let j = 0; j < lengthOfProgression; j += 1) {
if (j === hiddenMemberIndex) {
question = `${question}.. `;
}
question = `${question}${progression[j]} `;
}
question = question.trim();
const trueAnswer = progression[hiddenMemberIndex];
const result = [question, trueAnswer];
return result;
};
const description = 'What number is missing in the progression?';
export default () => engine(generateConditions, description);
<file_sep>/README.md
# frontend-project-lvl1
[](https://codeclimate.com/github/uzakovnikita/frontend-project-lvl1/maintainability)
[](https://travis-ci.org/uzakovnikita/frontend-project-lvl1)
A set of mini-games includes:
1) **brain-gcd** - the search for the greatest common dividend. For launcg game type **brain-gcd**.
2) **brain-progression** - the search for the missing member of the progression. For launcg game type **brain-progression**.
3) **brain-even** - guessing even or odd number. For launcg game type **brain-even**.
4) **brain-prime** - guessing a simple or complicated number. For launcg game type **brain-prime**.
For **INSTALL** type the following commands after loading this repository from github
make install
make publish
npm link
[](https://asciinema.org/a/282667)
[](https://asciinema.org/a/282668)
[](https://asciinema.org/a/282669)
[](https://asciinema.org/a/282670)
[](https://asciinema.org/a/282661)
<file_sep>/src/games/even.js
import getRandom from '../utils';
import engine from '../engine';
const isEven = (x) => (!(x % 2));
const description = 'Answer "yes" if the number is even, otherwise answer "no".';
const generateConditions = () => {
const question = getRandom(0, 1000);
const trueAnswer = isEven(question) ? 'yes' : 'no';
const result = [question, trueAnswer];
return result;
};
export default () => engine(generateConditions, description);
<file_sep>/src/games/prime.js
import engine from '../engine';
import getRandom from '../utils';
const isPrime = (x) => {
if (x === 2) {
return true;
} if (x <= 1) {
return false;
}
for (let i = 3; i < x / 2; i += 1) {
if (x % i === 0) return false;
}
return true;
};
const generateConditions = () => {
const question = getRandom(0, 100).toString();
const trueAnswer = isPrime(question) ? 'yes' : 'no';
const result = [question, trueAnswer];
return result;
};
const description = 'Answer "yes" if given number is prime. Otherwise answer "no"';
export default () => engine(generateConditions, description, 0);
<file_sep>/src/engine.js
import readlineSync from 'readline-sync';
const roundsCount = 3;
export default (generateConditions, description) => {
let nikname = '';
for (let i = 0; i < roundsCount; i += 1) {
if (i === 0) {
console.log('Welcome to the Brain Games!');
console.log(description);
nikname = readlineSync.question('May i have you name?');
console.log(`Hello, ${nikname}!`);
}
const conditions = generateConditions();
const [question, trueAnswer] = conditions;
console.log(`Question: ${question}`);
const userAnswer = readlineSync.question('Your answer ');
if (trueAnswer === userAnswer) {
console.log('Correct!');
} else {
console.log(`${userAnswer} is wrong answer ;(. Correct answer was ${trueAnswer}.`);
return;
}
}
console.log(`Congratulations, ${nikname}!`);
};
| 24f0d9e8bea00be701eba0ad9f1fc6905a12c429 | [
"JavaScript",
"Markdown"
]
| 6 | JavaScript | uzakovnikita/frontend-project-lvl1 | 3ac1ba4fd90166840c7eaea9491d54b629608886 | f75c935881caec0e93cdfdafbf59923d513e729d |
refs/heads/master | <file_sep><div class="page-sidebar">
<ul>
<li class="sticker sticker-color-red"><a href="<?php echo site_url('work');?>"><i class="icon-clipboard"></i>近期工作</a></li>
<li class="sticker sticker-color-blue"><a href="<?php echo site_url('article');?>"><i class="icon-book"></i>美文阅读</a></li>
<li class="sticker sticker-color-green"><a href="<?php echo site_url('about');?>"><i class="icon-history"></i>关于</a></li>
</ul>
</div><file_sep><?php
if (! defined('BASEPATH'))
exit('No direct script access allowed');
/**
*
*@function 文件管理模型
*@date 2013-10-16
*@author gerui
*@email <<EMAIL>>
*/
class File_model extends MY_Model{
protected $tables = array(
'cnt', //0
'cnt_dep_rel', //1
'dep', //2
'user', //3
'user_dep_rel' //4
);
public function __construct()
{
parent::__construct();
}
/**
* 获取所有联系人信息
*/
public function get_all_cnt(){
$this->db->select('a.id, a.cnt_num, a.cnt_name, a.phone, a.desc, a.create_time, a.update_time, c.dep_name');
$this->db->from("{$this->tables[0]} as a");
$this->db->join("{$this->tables[1]} as b", "a.id = b.cnt_id", "left");
$this->db->join("{$this->tables[2]} as c", "b.dep_id = c.id", "left");
$data = $this->db->get()->result();
return $data;
}
public function export_cnt_xls(){
//获取所有联系人信息
$data = $this->get_all_cnt();
require_once 'application/libraries/PHPExcel.php';
require_once 'application/libraries/PHPExcel/Writer/Excel5.php';
// 创建一个处理对象实例
$objExcel = new PHPExcel();
// 创建文件格式写入对象实例, uncomment
$objWriter = new PHPExcel_Writer_Excel5($objExcel);
//设置文档基本属性
$objProps = $objExcel->getProperties();
$objProps->setCreator("苏州大学");
$objProps->setLastModifiedBy("苏州大学");
$objProps->setTitle("苏州大学联系人");
$objProps->setSubject("苏州大学联系人");
$objProps->setDescription("苏州大学联系人信息表");
$objProps->setKeywords("苏州大学联系人");
$objProps->setCategory("苏州大学联系人");
//*************************************
//设置当前的sheet索引,用于后续的内容操作。
//一般只有在使用多个sheet的时候才需要显示调用。
//缺省情况下,PHPExcel会自动创建第一个sheet被设置SheetIndex=0
$objExcel->setActiveSheetIndex(0);
$objActSheet = $objExcel->getActiveSheet();
//设置当前活动sheet的名称
$objActSheet->setTitle('联系人');
//*************************************
//
//设置宽度,这个值和EXCEL里的不同,不知道是什么单位,略小于EXCEL中的宽度
$objActSheet->getColumnDimension('A')->setWidth(20);
$objActSheet->getColumnDimension('B')->setWidth(20);
$objActSheet->getColumnDimension('C')->setWidth(20);
$objActSheet->getColumnDimension('D')->setWidth(20);
$objActSheet->getColumnDimension('E')->setWidth(30);
$objActSheet->getColumnDimension('F')->setWidth(25);
$objActSheet->getColumnDimension('G')->setWidth(25);
$objActSheet->getRowDimension(1)->setRowHeight(30);
$objActSheet->getRowDimension(2)->setRowHeight(27);
$objActSheet->getRowDimension(3)->setRowHeight(16);
//设置单元格的值
$objActSheet->setCellValue('A1', '苏州大学联系人信息');
//合并单元格
$objActSheet->mergeCells('A1:G1');
//设置样式
$objStyleA1 = $objActSheet->getStyle('A1');
$objStyleA1->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objFontA1 = $objStyleA1->getFont();
$objFontA1->setName('宋体');
$objFontA1->setSize(18);
$objFontA1->setBold(true);
$column = array('A', 'B', 'C', 'D', 'E', 'F', 'G');
foreach($column as $v){
//设置居中对齐
$objActSheet->getStyle($v.'2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
}
$objActSheet->setCellValue('A2', '联系人编号');
$objActSheet->setCellValue('B2', '联系人姓名');
$objActSheet->setCellValue('C2', '电话号码');
$objActSheet->setCellValue('D2', '所属部门');
$objActSheet->setCellValue('E2', '备注');
$objActSheet->setCellValue('F2', '建档时间');
$objActSheet->setCellValue('G2', '更新时间');
foreach($column as $v){
//设置边框
$objActSheet->getStyle($v.'2')->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
$objActSheet->getStyle($v.'2')->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
$objActSheet->getStyle($v.'2')->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
$objActSheet->getStyle($v.'2')->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
}
$i=1;
//从数据库取值循环输出
foreach ($data as $result){
$n=$i+2;
$objActSheet->getStyle('B'.$n)->getNumberFormat()->setFormatCode('@');
$objActSheet->getStyle('E'.$n)->getNumberFormat()->setFormatCode('@');
$objActSheet->getRowDimension($n)->setRowHeight(16);
foreach ($column as $v){
$objActSheet->getStyle($v.$n)->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
$objActSheet->getStyle($v.$n)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
$objActSheet->getStyle($v.$n)->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
$objActSheet->getStyle($v.$n)->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
}
$objActSheet->setCellValue('A'.$n, $result->cnt_num);
$objActSheet->setCellValue('B'.$n, $result->cnt_name);
$objActSheet->setCellValue('C'.$n, $result->phone);
$objActSheet->setCellValue('D'.$n, $result->dep_name);
$objActSheet->setCellValue('E'.$n, $result->desc);
$objActSheet->setCellValue('F'.$n, $result->create_time);
$objActSheet->setCellValue('G'.$n, $result->update_time);
$i++;
}
//*************************************
//输出内容
$outputFileName = "docs/excel/cnt.xls";
//到文件
$objWriter->save($outputFileName);
//下面这个输出我是有个页面用Ajax接收返回的信息
return '<a href="docs/excel/cnt.xls" mce_href="docs/excel/cnt.xls" target="_blank">点击下载电子表</a>';
}
/**
* 保存excel到mysql数据库
*/
public function save_excel(){
$config['upload_path'] = ('./docs/upload');
$config['allowed_types'] = 'xls';
//允许上传10M大小
$config['max_size'] = '10000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = $this->upload->display_errors();
return $error;
}
else
{
$data = $this->upload->data();
}
@require_once 'application/libraries/PHPExcel.php';
@require_once 'application/libraries/PHPExcel/IOFactory.php';
@require_once 'application/libraries/PHPExcel/Reader/Excel5.php';
$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format
$objPHPExcel = @$objReader->load('./docs/upload/'.$data['file_name']); //$filename可以是上传的文件,或者是指定的文件
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
$k = 0;
//循环读取excel文件,读取一条,插入一条
for($j=2;$j<=$highestRow;$j++)
{
$a = iconv('utf-8','utf-8',$objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue());//读取单元格
$b = iconv('utf-8','utf-8',$objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue());//读取单元格
echo $a.' '.$b.'<br/>';
}
return 1;
}
function uploadFile($file,$filetempname)
{
//自己设置的上传文件存放路径
$filePath = 'docs/upload/';
$str = "";
@require_once 'application/libraries/PHPExcel.php';
@require_once 'application/libraries/PHPExcel/IOFactory.php';
@require_once 'application/libraries/PHPExcel/Reader/Excel5.php';
$filename=explode(".",$file);//把上传的文件名以“.”好为准做一个数组。
$time=date("y-m-d-H-i-s");//去当前上传的时间
$filename[0]=$time;//取文件名t替换
$name=implode(".",$filename); //上传后的文件名
$uploadfile=$filePath.$name;//上传后的文件名地址
//move_uploaded_file() 函数将上传的文件移动到新位置。若成功,则返回 true,否则返回 false。
$result=move_uploaded_file($filetempname,$uploadfile);//假如上传到当前目录下
if($result) //如果上传文件成功,就执行导入excel操作
{
$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format
$objPHPExcel = $objReader->load($uploadfile);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
//循环读取excel文件,读取一条,插入一条
for($j=2;$j<=$highestRow;$j++)
{
for($k='A';$k<=$highestColumn;$k++)
{
$str .= iconv('utf-8','gbk',$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue()).'\\';//读取单元格
}
//explode:函数把字符串分割为数组。
$strs = explode("\\",$str);
$sql = "INSERT INTO tab_zgjx_award (jx_name,jx_degree,jx_item_name,jx_unit,dy_originator,de_originator,xm_intro,hj_item_id) VALUES('".
$strs[0]."','". //奖项名称
$strs[1]."','". //奖项届次
$strs[2]."','". //获奖项目名
$strs[3]."','". //获奖单位
$strs[4]."','". //第一发明人
$strs[5]."','". //第二发明人
$strs[6]."','". //项目简介
$strs[7]."')"; //获奖项目编号
mysql_query("set names GBK");//这就是指定数据库字符集,一般放在连接数据库后面就系了
if(!mysql_query($sql))
{
return false;
}
$str = "";
}
unlink($uploadfile); //删除上传的excel文件
$msg = "导入成功!";
}
else
{
$msg = "导入失败!";
}
return $msg;
}
public function __destruct(){
parent::__destruct();
}
}
/* End of file file_model.php */
/* Location: ./application/models/file_model.php */<file_sep> <div class="page">
<div class="nav-bar">
<div class="nav-bar-inner padding10">
<span class="element">
Copyright © <a class="fg-color-white" href="mailto:<EMAIL>"><NAME></a> 2013, All Rights Reserved
</span>
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/github.info.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/google-analytics.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/google-code-prettify/prettify.js"></script>
<script src="<?php echo base_url();?>metro/js/sharrre/jquery.sharrre-1.3.4.min.js"></script>
<script>
$('#shareme').sharrre({
share: {
googlePlus: true
,delicious: true
},
urlCurl: "<?php echo base_url();?>metro/js/sharrre/sharrre.php",
buttons: {
googlePlus: {size: 'tall'},
delicious: {size: 'tall'}
},
hover: function(api, options){
$(api.element).find('.buttons').show();
}
});
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8">
<meta name="viewport" content="target-densitydpi=device-dpi, width=device-width, initial-scale=1.0, maximum-scale=1">
<meta name="description" content="My HomePage">
<meta name="author" content="<NAME>">
<meta name="keywords" content="windows 8, modern style, Metro UI, style, modern, css, framework">
<link href="<?php echo base_url();?>metro/css/modern.css" rel="stylesheet">
<link href="<?php echo base_url();?>metro/css/modern-responsive.css" rel="stylesheet">
<link href="<?php echo base_url();?>metro/css/site.css" rel="stylesheet" type="text/css">
<link href="<?php echo base_url();?>metro/js/google-code-prettify/prettify.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/jquery.mousewheel.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/moment.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/moment_langs.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/dropdown.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/accordion.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/buttonset.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/carousel.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/input-control.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/pagecontrol.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/rating.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/slider.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/tile-slider.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/tile-drag.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/calendar.js"></script>
<title>GeRui's Home</title>
</head>
<body class="metrouicss" onload="prettyPrint()">
<?php include("navigation.php")?>
<file_sep><?php
if (! defined('BASEPATH'))
exit('No direct script access allowed');
/**
*
*@function 部门管理模型
*@date 2013-10-14
*@author gerui
*@email <<EMAIL>>
*/
class Dep_model extends MY_Model{
protected $tables = array(
'cnt', //0
'cnt_dep_rel', //1
'dep', //2
'user', //3
'user_dep_rel' //4
);
private $all_dep;
public function __construct()
{
parent::__construct();
}
/**
* 列出所有部门
* @param $dep_id_array 用户所有部门id的数组
* @return unknown
*/
public function list_dep($dep_id_array){
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$orderField = $this->input->post('orderField') ? $this->input->post('orderField') : 'a.id';
$orderDirection = $this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'desc';
$startOffset = $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) * $per_page : 0;
$this->db->select('a.id, a.dep_num, a.dep_name, a.lvl, a.father_dep_id, a.desc,
b.dep_name as father_dep_name, a.create_time, a.update_time');
$this->db->from("{$this->tables[2]} as a");
$this->db->join("{$this->tables[2]} as b", 'a.father_dep_id = b.id', 'left');
if (!empty($dep_id_array)){
$this->db->where_in('a.id', $dep_id_array);
}
else{
$this->db->where('a.id', 'xxx');
}
$this->db->limit($per_page, $startOffset);
$this->db->order_by($orderField, $orderDirection);
$result = $this->db->get()->result();
$data['list'] = $result;
$total = 0;
if (!empty($dep_id_array))
{
$this->db->select('a.id');
$this->db->from("{$this->tables[2]} as a");
$this->db->join("{$this->tables[2]} as b", 'a.father_dep_id = b.id', 'left');
$this->db->where_in('a.id', $dep_id_array);
$total = $this->db->get()->num_rows();
}
$data['total'] = $total;
return $data;
}
/**
* 搜索所有部门
*/
public function list_dep_search($dep_id_array){
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$orderField = $this->input->post('orderField') ? $this->input->post('orderField') : 'a.id';
$orderDirection = $this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'desc';
$startOffset = $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) * $per_page : 0;
if ($this->input->post('dep_num'))
{
$s_dep_num = $this->input->post('dep_num');
$this->session->set_userdata('dep_num', $s_dep_num);
}else{
if ($this->input->post('page_dep_num')){
$s_dep_num = $this->input->post('dep_num');
}else{
$s_dep_num = false;
$this->session->unset_userdata('dep_num');
}
}
if ($this->input->post('dep_name'))
{
$s_dep_name = $this->input->post('dep_name');
$this->session->set_userdata('dep_name', $s_dep_name);
}else{
if ($this->input->post('page_dep_name')){
$s_dep_name = $this->input->post('dep_name');
}else{
$s_dep_name = false;
$this->session->unset_userdata('dep_name');
}
}
if ($this->input->post('dep_desc'))
{
$s_dep_desc = $this->input->post('dep_desc');
$this->session->set_userdata('dep_desc', $s_dep_desc);
}else{
if ($this->input->post('page_dep_desc')){
$s_dep_desc = $this->input->post('dep_desc');
}else{
$s_dep_desc = false;
$this->session->unset_userdata('dep_desc');
}
}
$this->db->select('a.id, a.dep_num, a.dep_name, a.lvl, a.father_dep_id, a.desc,
b.dep_name as father_dep_name, a.create_time, a.update_time');
$this->db->from("{$this->tables[2]} as a");
$this->db->join("{$this->tables[2]} as b", 'a.father_dep_id = b.id', 'left');
$this->db->where_in('a.id', $dep_id_array);
if ($s_dep_num){
$this->db->like('a.dep_num', $s_dep_num);
}
if ($s_dep_name){
$this->db->like('a.dep_name', $s_dep_name);
}
if ($s_dep_desc){
$this->db->like('a.desc', $s_dep_desc);
}
$this->db->limit($per_page, $startOffset);
$this->db->order_by($orderField, $orderDirection);
$result = $this->db->get()->result();
$data['list'] = $result;
$this->db->select('a.id, a.dep_num, a.dep_name, a.lvl, a.father_dep_id, a.desc,
b.dep_name as father_dep_name, a.create_time, a.update_time');
$this->db->from("{$this->tables[2]} as a");
$this->db->join("{$this->tables[2]} as b", 'a.father_dep_id = b.id', 'left');
$this->db->where_in('a.id', $dep_id_array);
if ($s_dep_num){
$this->db->like('a.dep_num', $s_dep_num);
}
if ($s_dep_name){
$this->db->like('a.dep_name', $s_dep_name);
}
if ($s_dep_desc){
$this->db->like('a.desc', $s_dep_desc);
}
$total = $this->db->get()->num_rows();
$data['total'] = $total;
return $data;
}
/**
* 删除部门
*/
public function delete_dep($id){
$this->db->trans_start();
$this->delete($this->tables[2], $id);
$this->db->delete($this->tables[1], array('dep_id' => $id));
$this->db->delete($this->tables[4], array('dep_id' => $id));
$this->db->trans_complete();
if ($this->db->trans_status() == false)
{
return $this->db_error;
}
else
{
$this->applog->msg('删除联系人');
return 1;
}
}
/**
* 获取一个部门的信息
*/
public function get_dep($id){
return $this->read($this->tables[2], $id);
}
/**
* 保存部门信息
*/
public function save_dep(){
$data = array(
"dep_num" => $this->input->post('dep_num', true),
"dep_name" => $this->input->post('dep_name', true),
"desc" => $this->input->post('desc', true),
'lvl' => $this->input->post('lvl', true),
'update_time' => date('Y-m-d H:i:s')
);
$data2 = array(
'user_id' => $this->session->userdata('id')
);
if ($data['lvl'] > 0 ){
$data['father_dep_id'] = $this->input->post('dep', true);
$father_dep = $this->read($this->tables[2], $data['father_dep_id']);
$data['lvl'] = $father_dep['lvl'] + 1;
}else{
//根部门
$data['father_dep_id'] = -1;
}
$id = $this->input->post('id');
$dep_num = $this->is_exists($this->tables[2], 'dep_num', $data['dep_num']);
$dep_name = $this->is_exists($this->tables[2], 'dep_name', $data['dep_name']);
if ($id)
{
//更新保存
if ($dep_num && $dep_num['id'] != $id)
return '部门编号已存在';
if ($dep_name && $dep_name['id'] != $id)
return '部门名称已存在';
$old_lvl = '';
$update_dep = $this->is_exists($this->tables[2], 'id', $id);
$old_lvl = $update_dep['lvl'];
$dep_array = $this->get_chil_dep_all($id, $old_lvl);
$this->db->trans_start();
$this->update($this->tables[2], $id, $data);
//修改子部门的lvl
if(!empty($dep_array)){
$this->update_chil_dep($dep_array, $old_lvl, $data['lvl']);
}
$this->db->trans_complete();
if ($this->db->trans_status() == false)
{
return $this->db_error;
}
else
{
$this->applog->msg('成功修改部门');
return 1;
}
}
else{
//新增保存
if($dep_num)
{
return '部门编号已存在';
}
if ($dep_name){
return '部门名称已存在';
}
$data['create_time'] = date('Y-m-d H:i:s');
$this->db->trans_start();
$this->create($this->tables[2], $data);
$data2['dep_id'] = $this->db->insert_id();
$this->create($this->tables[4], $data2);
$this->db->trans_complete();
if ($this->db->trans_status() == false)
{
return $this->db_error;
}
else
{
$this->applog->msg('成功添加部门');
return 1;
}
}
}
/**
* 修改子部门的等级
* @param $dep_id 父部门id
* @param $old_lvl 父部门未修改之前的lvl
* @param $new_lvl 父部门修改之后的lvl
*/
public function update_chil_dep($dep_array, $old_lvl, $new_lvl){
foreach($dep_array as $line){
$data['lvl'] = $line['lvl'] - $old_lvl + $new_lvl;
$this->update($this->tables[2], $line['id'], $data);
}
}
/**
* 获取子部门
* @param $dep_id 父部门id
* @param $old_lvl 父部门未修改之前的lvl
* @param $new_lvl 父部门修改之后的lvl
*/
public function get_chil_dep_all($dep_id, $old_lvl){
$dep_array = $this->get_chil_dep_array($dep_id, $old_lvl);
if(!empty($dep_array))
{
$this->all_dep = array();
$this->get_dep_all_recur($dep_array);
return $this->all_dep;
}
return null;
}
/**
* 递归出所有子部门
* @param unknown_type $dep_array
*/
public function get_dep_all_recur($dep_array)
{
if (!empty($dep_array)){
foreach($dep_array as $line){
array_push($this->all_dep, $line);
$chil_dep_array = $this->get_chil_dep_array($line['id'], $line['lvl']);
if (!empty($chil_dep_array)){
//如果还有子部门,继续递归
$this->get_dep_all_recur($chil_dep_array);
}
}
}
}
/**
* 获取子部门的数组形式
* @param $father_id
* @param $father_lvl
*/
public function get_chil_dep_array($father_id, $father_lvl){
$rs = $this->get_chil_dep($father_id, $father_lvl);
return $rs->result_array();
}
/**
* 根据父部门从数据库中获取子部门
*/
public function get_chil_dep($father_id, $father_lvl){
$chil_lvl = $father_lvl + 1;
$this->db->select('id, dep_name, dep_num, father_dep_id, lvl, desc');
$this->db->from($this->tables[2]);
$this->db->where(array('father_dep_id' => $father_id));
$this->db->where(array('lvl' => $chil_lvl));
$chil_dep = $this->db->get();
return $chil_dep;
}
public function __destruct(){
parent::__destruct();
}
}
/* End of file dep_model.php */
/* Location: ./application/models/dep_model.php */<file_sep><?php
if (! defined('BASEPATH'))
exit('No direct script access allowed');
/**
* 权限模型
*
* 权限及用户的处理模型
*
* @package app
* @subpackage core
* @category model
* @author bruce.yang<<EMAIL>>
*
*/
class Permission_model extends MY_Model
{
/**
* 表名数组
* @var array
*/
protected $tables = array(
'user', //0
'user_dep_rel', //1
'dep' //2
);
public function __construct ()
{
parent::__construct();
}
public function __destruct ()
{
parent::__destruct();
}
/**
* ********************************模块**********************************
*/
/**
* 列出模块(分页)
*
* @return array 返回数组array('total'=>表记录总数,'list'=>记录列表)
*/
public function list_module ()
{
$total_rows = $this->count($this->tables[0]);
// 每页显示的记录条数,默认20条
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$data['total'] = $total_rows;
// list_data(表,抓取记录数,偏离量,排序字段,排序方法);
$data['list'] = $this->list_data($this->tables[0], $per_page, $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) *
$per_page : 0, $this->input->post('orderField') ? $this->input->post('orderField') : 'id',
$this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'desc');
return $data;
}
/**
* 列出模块(全部)
*
* @return array 返回对象数组
*/
public function list_module_all ()
{
return $this->list_all($this->tables[0]);
}
/**
* 保存模块
*
* @return int|string 成功返回1,否则返回出错信息
*/
public function save_module ()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<li>', '</li>');
$this->form_validation->set_rules('title', '模块名称', 'trim|required|xss_clean');
$this->form_validation->set_rules('code', '模块代码', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
return validation_errors();
} else {
$data = array(
'title' => $this->input->post('title', TRUE),
'code' => $this->input->post('code', TRUE),
'add_time' => date("Y-m-d H:i:s"),
'update_time' => date("Y-m-d H:i:s")
);
// 检查重复
$rs_title = $this->is_exists($this->tables[0], 'title', $data['title']);
$rs_code = $this->is_exists($this->tables[0], 'code', $data['code']);
if ($this->input->post('id')) { // 更新保存
unset($data['add_time']);
if ($rs_title and $rs_title['id'] != $this->input->post('id'))
return '模块名已经存在';
if ($rs_code and $rs_code['id'] != $this->input->post('id'))
return '模块代码已经存在';
if ($this->update($this->tables[0], $this->input->post('id'), $data)) {
return 1;
} else {
return $this->db_error;
}
} else { // 新增保存
if ($rs_title or $rs_code) {
return '模块名或模块代码已经存在';
}
if ($this->create($this->tables[0], $data)) {
return 1;
} else {
return $this->db_error;
}
}
}
}
/**
* 返回一个模块信息数组
*
* @param int $id 模块id
* @return array 模块数组信息
*/
public function get_module ($id)
{
return $this->read($this->tables[0], $id);
}
/**
* 删除模块
*
* @param int $id 模块id
* @return int|string 成功返回1,否则返回出错信息
*/
public function delete_module ($id)
{
// 判断是否有功能在模块下,有则停止删除
if($this->is_exists($this->tables[1], 'perm_module_id', $id))
return "在模块下存在功能,请先删除该模块下的功能!";
if ($this->delete($this->tables[0], $id)) {
return 1;
} else {
return $this->db_error;
}
}
/**
* ********************************模块**********************************
*/
/**
* ********************************功能**********************************
*/
/**
* 列出功能(分页)
*
* @return array 返回数组array('total'=>表记录总数,'list'=>记录列表)
*/
public function list_action ()
{
// 每页显示的记录条数,默认20条
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$data['total'] = $this->count($this->tables[1]);
// list_data(表,抓取记录数,偏离量,排序字段,排序方法);
$data['list'] = $this->list_data($this->tables[1], $per_page, $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) * $per_page : 0, $this->input->post('orderField') != '' ? $this->input->post('orderField') : 'perm_subject',
$this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'asc');
$modules = $this->list_module_all();
foreach ($data['list'] as &$temp_action) {
foreach ($modules as $module) {
if ($module->id == $temp_action->perm_module_id) {
$temp_action->module_title = $module->title;
continue;
}
}
}
return $data;
}
/**
* 取得所有功能数据
*
* @return array 返回对象数组
*/
public function list_action_all ()
{
$this->db->order_by('perm_subject, order_no desc');
return $this->db->get($this->tables[1])->result();
}
/**
* 取得所有功能主题数据
*
* @return array 返回对象数组
*/
public function list_subject ()
{
$sql = "SELECT distinct perm_subject, perm_module_id FROM (`plmis_perm_data`)";
return $this->db->query($sql)->result();
}
/**
* 保存功能
*
* @return int|string 成功返回1,否则返回出错信息
*/
public function save_action ()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<li>', '</li>');
$this->form_validation->set_rules('perm_module_id', '所属模块', 'trim|required|xss_clean');
$this->form_validation->set_rules('perm_subject', '功能', 'trim|required|xss_clean');
$this->form_validation->set_rules('perm_name', '动作', 'trim|required|xss_clean');
$this->form_validation->set_rules('perm_key', '代码', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
return validation_errors();
} else {
$data = array(
'perm_module_id' => $this->input->post('perm_module_id', TRUE),
'perm_subject' => $this->input->post('perm_subject', TRUE),
'order_no' => $this->input->post('order_no', TRUE),
'perm_name' => $this->input->post('perm_name', TRUE),
'perm_key' => $this->input->post('perm_key', TRUE),
'add_time' => date("Y-m-d H:i:s"),
'update_time' => date("Y-m-d H:i:s")
);
// 检查重复
$array = array(
'perm_subject' => $data['perm_subject'],
'perm_name' => $data['perm_name']
);
$this->db->from($this->tables[1]);
$this->db->where($array);
$query = $this->db->get();
$num_rows = $query->num_rows();
$row = $query->row();
$rs_perm_key = $this->is_exists($this->tables[1], 'perm_key', $data['perm_key']);
if ($this->input->post('id')) { // 更新保存
unset($data['add_time']);
if ($num_rows > 0) { // 该功能的动作已经已经存在
if ($row->perm_module_id == $data['perm_module_id']) { // 同时属于同一个模块
if ($this->input->post('id') != $row->id) { // 并且不是本次修改的记录
return '该功能的动作在选择模块已经存在';
}
}
}
if ($rs_perm_key) { // 功能key已经存在
if ($rs_perm_key['perm_module_id'] == $data['perm_module_id']) { // 同时属于同一个模块
if ($this->input->post('id') != $rs_perm_key['id']) { // 并且不是本次修改的记录
return '代码在选择模块中已经存在';
}
}
}
if ($this->update($this->tables[1], $this->input->post('id'), $data)) {
return 1;
} else {
return $this->db_error;
}
} else { // 新增保存
if ($num_rows > 0) { // 该功能的动作已经已经存在
if ($row->perm_module_id == $data['perm_module_id'])
return '该功能的动作在选择模块中已经存在';
}
if ($rs_perm_key) { // 功能key已经存在
if ($rs_perm_key['perm_module_id'] == $data['perm_module_id'])
return '代码在选择模块中已经存在';
}
if ($this->create($this->tables[1], $data)) {
return 1;
} else {
return $this->db_error;
}
}
}
}
/**
* 返回一个功能信息数组
*
* @param int $id 功能id
* @return array 功能信息数组
*/
public function get_action ($id)
{
return $this->read($this->tables[1], $id);
}
/**
* 删除功能
*
* @return int|string 成功返回1,否则返回出错信息
*/
public function delete_action ($id)
{
$this->db->trans_start();
$this->delete($this->tables[1],$id);
//同步删除已经分配给用户和角色的权限数据,以及用户禁用的数据
$this->db->delete($this->tables[3], array('perm_id' => $id));
$this->db->delete($this->tables[4], array('perm_id' => $id));
$this->db->delete($this->tables[6], array('perm_id' => $id));
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
return 1;
} else {
return $this->db_error;
}
}
/**
* 取得所有权限数据,即所有的模块和功能
*
* @return array 返回数组array('modules'=>模块列表,'actions'=>功能列表)
*/
public function get_all_perms ()
{
// 取得模块数据(控制器)
$modules = $this->list_module_all();
// 取得功能数据(控制器里的方法)
$actions = $this->list_action_all();
$data['modules'] = $modules;
$data['actions'] = $actions;
return $data;
}
/**
* ********************************功能**********************************
*/
/**
* ********************************角色**********************************
*/
/**
* 列出角色(分页)
*
* @return array 返回数组array('total'=>表记录总数,'list'=>记录列表)
*/
public function list_role ()
{
// 每页显示的记录条数,默认20条
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$data['total'] = $this->count($this->tables[2]);
// list_data(表,抓取记录数,偏离量,排序字段,排序方法);
$data['list'] = $this->list_data($this->tables[2], $per_page, $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) *
$per_page : 0, $this->input->post('orderField') ? $this->input->post('orderField') : 'id',
$this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'desc');
return $data;
}
/**
* 保存角色
*
* @return int|string 成功返回1,否则返回出错信息
*/
public function save_role ()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<li>', '</li>');
$this->form_validation->set_rules('role_name', '角色名称', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
return validation_errors();
} else {
$data = array(
'role_name' => $this->input->post('role_name', TRUE),
'description' => $this->input->post('description', TRUE),
'add_time' => date("Y-m-d H:i:s"),
'update_time' => date("Y-m-d H:i:s")
);
// 检查重复
$rs_role_name = $this->is_exists($this->tables[2], 'role_name', $data['role_name']);
if ($this->input->post('id')) { // 更新保存
unset($data['add_time']);
if ($rs_role_name and $rs_role_name['id'] != $this->input->post('id'))
return '角色已经存在';
if ($this->update($this->tables[2], $this->input->post('id'), $data)) {
$this->applog->msg('更新角色');
return 1;
} else {
return $this->db_error;
}
} else { // 新增保存
if ($rs_role_name) {
return '角色已经存在';
}
if ($this->create($this->tables[2], $data)) {
$this->applog->msg('新增角色');
return 1;
} else {
return $this->db_error;
}
}
}
}
/**
* 返回一个角色信息数组
*
* @param int $id 角色id
* @return array 角色信息数组
*/
public function get_role ($id)
{
return $this->read($this->tables[2], $id);
}
/**
* 删除角色
*
* @param int $id 角色id
* @return int|string 成功返回1,否则返回出错信息
*/
public function delete_role ($id)
{
$this->db->trans_start();
$this->delete($this->tables[2],$id);
//同步删除已经分配给用户角色数据,以及角色权限的数据
$this->db->delete($this->tables[5], array('role_id' => $id));
$this->db->delete($this->tables[3], array('role_id' => $id));
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
$this->applog->msg('删除角色');
return 1;
} else {
return $this->db_error;
}
}
/**
* 取得指定角色的权限字串数组
*
* @param int $id 角色id
* @return array 权限字符串数组
*/
public function get_role_perm_string ($id)
{
$role_perms = $this->list_all_where($this->tables[3], 'role_id', $id);
$perms_array = array();
if ($role_perms) {
foreach ($role_perms as $role_perm) {
$this->db->select('code,perm_key');
$this->db->from($this->tables[1]);
$this->db->join($this->tables[0], $this->tables[0] . '.id = ' . $this->tables[1] . '.perm_module_id', 'left');
$this->db->where($this->tables[1] . '.id', $role_perm->perm_id);
$temp_array = $this->db->get()->result_array();
foreach ($temp_array as $perm) {
$perms_array[] = $perm['code'] . '/' . $perm['perm_key'];
}
}
}
return $perms_array;
}
/**
* 取得指定角色的权限
*
* @param int $id 角色id
*/
public function get_role_perm ($id)
{
// 取得指定角色的权限
$role_perms = $this->list_all_where($this->tables[3], 'role_id', $id);
if ($role_perms) {
foreach ($role_perms as $role_perm) {
$perms[] = $role_perm->perm_id;
}
} else {
$perms = false;
}
return $perms;
}
/**
* 保存角色的权限
*
* @return int|string 成功返回1,否则返回出错信息
*/
public function save_role_perm ()
{
$role_id = $this->input->post('role_id');
$perms = $this->input->post('c1');
// 删除角色的旧权限
$this->db->delete($this->tables[3], array(
'role_id' => $role_id
));
$this->db->trans_start();
if ($perms) {
foreach ($perms as $k => $v) {
$data = array(
'role_id' => $role_id,
'perm_id' => $v
);
$this->create($this->tables[3], $data);
}
}
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
return $this->db_error;
} else {
$this->applog->msg('更新角色权限');
return 1;
}
}
/**
* ********************************角色**********************************
*/
/**
* ********************************用户**********************************
*/
/**
* 列出用户(分页)
*
* @return array 返回数组array('total'=>表记录总数,'list'=>记录列表)
*/
public function list_user ()
{
// 每页显示的记录条数,默认20条
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$data['total'] = $this->count($this->tables[0]);
// list_data(表,抓取记录数,偏离量,排序字段,排序方法);
$data['list'] = $this->list_data($this->tables[0], $per_page, $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) *
$per_page : 0, $this->input->post('orderField') ? $this->input->post('orderField') : 'id',
$this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'desc');
return $data;
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$orderField = $this->input->post('orderField') ? $this->input->post('orderField') : 'a.id';
$orderDirection = $this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'desc';
$startOffset = $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) * $per_page : 0;
//a: user b: user_dep_rel c:dep
$this->db->select('a.id, a.username, a.real_name, a.email, a.status, a.last_login_ip,
a.last_login_time, a.add_time, a.update_time, c.dep_name');
$this->db->from("{$this->tables[0]} as a");
$this->db->join("{$this->tables[1]} as b", "a.id = b.user_id", "left");
$this->db->join("{$this->tables[2]} as c", "b.dep_id = c.id", "left");
$this->db->limit($per_page, $startOffset);
$this->db->order_by($orderField, $orderDirection);
$result = $this->db->get()->result();
$data['list'] = $result;
$this->db->select('a.id, a.username, a.real_name, a.email, a.status, a.last_login_ip,
a.last_login_time, a.add_time, a.update_time, c.dep_name');
$this->db->from("{$this->tables[0]} as a");
$this->db->join("{$this->tables[1]} as b", "a.id = b.user_id", "left");
$this->db->join("{$this->tables[2]} as c", "b.dep_id = c.id", "left");
$total = $this->db->get()->num_rows();
$data['total'] = $total;
return $data;
}
/**
* 保存用户
*
* @return int,string 成功返回1,否则返回出错信息
*/
public function save_user ()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<li>', '</li>');
$this->form_validation->set_rules('username', '用户名称', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
return validation_errors();
} else {
$data = array(
'username' => $this->input->post('username', TRUE),
'password' => <PASSWORD>($this->input->post('password', TRUE)),
'email' => $this->input->post('email', TRUE),
'status' => $this->input->post('status', TRUE),
'add_time' => date("Y-m-d H:i:s"),
'update_time' => date("Y-m-d H:i:s")
);
// 检查重复
$rs_username = $this->is_exists($this->tables[0], 'username', $data['username']);
if ($this->input->post('id')) { // 更新保存
unset($data['add_time']);
if (! $this->input->post('password'))
unset($data['password']);
if ($rs_username and $rs_username['id'] != $this->input->post('id'))
return '用户已经存在';
if ($this->update($this->tables[0], $this->input->post('id'), $data)) {
$this->applog->msg('更新用户');
return 1;
} else {
return $this->db_error;
}
} else { // 新增保存
if (! $this->input->post('password'))
return '密码不能为空';
if ($rs_username) {
return '用户已经存在';
}
if ($this->create($this->tables[0], $data)) {
$this->applog->msg('新增用户');
return 1;
} else {
return $this->db_error;
}
}
}
}
/**
* 返回一个用户信息数组
*
* @param int $id 用户id
* @return array 用户信息数组
*/
public function get_user ($id)
{
return $this->read($this->tables[0], $id);
}
/**
* 删除用户
*
* @param int $id 用户id
* @return int|string 成功返回1,否则返回出错信息
*/
public function delete_user ($id)
{
if ($this->delete($this->tables[0], $id)) {
$this->applog->msg('删除用户');
return 1;
} else {
return $this->db_error;
}
}
/**
* 禁用或启用某个用户
*
* @param int $id 用户id
* @param int $flag
* 1,启用;0,禁用
*/
public function set_status ($id, $flag)
{
$rs = parent::set_status($this->tables[0], $id, $flag);
$this->applog->msg('更新用户状态');
return $rs;
}
/**
* 用户登录检查
*
* @return boolean
*/
public function check_login ()
{
$login_id = $this->input->post('username');
$passwd = $this->input->post('password');
$this->db->from($this->tables[0]);
$this->db->where('username', $login_id);
$this->db->where('password', sha1($passwd));
$this->db->where('status', 1);
$rs = $this->db->get();
if ($rs->num_rows() > 0) {
$user_info = $rs->row_array();
// 更新登陆信息
$data = array(
'last_login_time' => date('Y-m-d H:i:s'),
'last_login_ip' => $this->input->ip_address()
);
$this->update($this->tables[0], $user_info['id'], $data);
if ($login_id == "root"){
//root用户拥有所有权限
$user_info['perm'] = "ALL";
}else{
//$user_info['perm'] = $manage_dep_id;
}
//取得权限信息
/* $user_perm_string = array();
// 取得自身权限
$user_perm_string = $this->get_user_perm_string($user_info['id']);
// 取得禁止权限
$user_disable_string = $this->get_user_disable_string($user_info['id']);
// 取得用户的所有角色
$user_roles = $this->get_user_role($user_info['id']);
// 用户已经赋予角色数据
if ($user_roles['user_roles']) {
foreach ($user_roles['user_roles'] as $role_id) { // 循环抓取角色的权限
$role_perm_string = $this->get_role_perm_string($role_id); // 取得角色权限
if ($role_perm_string) {
foreach ($role_perm_string as $k => $v) { // 循环角色权限,合并到用户权限
$user_perm_string[] = $v;
}
}
}
}
// 去除角色和用户的重叠权限
$user_perm_string = array_unique($user_perm_string);
$user_info['perm'] = $user_perm_string;
$user_info['disable'] = $user_disable_string; */
$this->session->set_userdata($user_info);
return true;
} else {
return false;
}
}
/**
* 取得指定用户的权限字串数组
*
* @param int $id
* 用户id
* @return array 权限字串数组
*/
public function get_user_perm_string ($id)
{
$user_perms = $this->list_all_where($this->tables[4], 'user_id', $id);
$perms_array = array();
if ($user_perms) {
foreach ($user_perms as $user_perm) {
$this->db->select('code,perm_key');
$this->db->from($this->tables[1]);
$this->db->join($this->tables[0], $this->tables[0] . '.id = ' . $this->tables[1] . '.perm_module_id', 'left');
$this->db->where($this->tables[1] . '.id', $user_perm->perm_id);
$temp_array = $this->db->get()->result_array();
foreach ($temp_array as $perm) {
$perms_array[] = $perm['code'] . '/' . $perm['perm_key'];
}
}
}
return $perms_array;
}
/**
* 取得指定用户的禁用权限字串数组
*
* @param int $id
* 用户id
* @return array 权限字串数组
*/
public function get_user_disable_string ($id)
{
$user_perms = $this->list_all_where($this->tables[6], 'user_id', $id);
$perms_array = array();
if ($user_perms) {
foreach ($user_perms as $user_perm) {
$this->db->select('code,perm_key');
$this->db->from($this->tables[1]);
$this->db->join($this->tables[0], $this->tables[0] . '.id = ' . $this->tables[1] . '.perm_module_id', 'left');
$this->db->where($this->tables[1] . '.id', $user_perm->perm_id);
$temp_array = $this->db->get()->result_array();
foreach ($temp_array as $perm) {
$perms_array[] = $perm['code'] . '/' . $perm['perm_key'];
}
}
}
return $perms_array;
}
/**
* 取得指定用户的权限
*
* @param int $id
* 用户id
*/
public function get_user_perm ($id)
{
// 取得指定用户的权限
$user_perms = $this->list_all_where($this->tables[4], 'user_id', $id);
if ($user_perms) {
foreach ($user_perms as $user_perm) {
$perms[] = $user_perm->perm_id;
}
} else {
$perms = false;
}
return $perms;
}
/**
* 取得指定用户被禁用的权限
*
* @param int $id
* 用户id
*/
public function get_user_disable ($id)
{
$user_perms = $this->list_all_where($this->tables[6], 'user_id', $id);
if ($user_perms) {
foreach ($user_perms as $user_perm) {
$perms[] = $user_perm->perm_id;
}
} else {
$perms = false;
}
return $perms;
}
/**
* 保存用户的权限
*
* @return int|string 成功返回1,否则返回出错信息
*/
public function save_user_perm ()
{
$user_id = $this->input->post('user_id');
$perms = $this->input->post('c1');
// 删除用户的旧权限
$this->db->delete($this->tables[4], array(
'user_id' => $user_id
));
$this->db->trans_start();
if ($perms) {
foreach ($perms as $k => $v) {
$data = array(
'user_id' => $user_id,
'perm_id' => $v
);
$this->create($this->tables[4], $data);
}
}
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
return $this->db_error;
} else {
$this->applog->msg('更新用户权限');
return 1;
}
}
/**
* 保存用户禁用的权限
*
* @return int|string 成功返回1,否则返回出错信息
*/
public function save_user_disable ()
{
$user_id = $this->input->post('user_id');
$perms = $this->input->post('c2');
// 删除用户的旧权限
$this->db->delete($this->tables[6], array(
'user_id' => $user_id
));
$this->db->trans_start();
if ($perms) {
foreach ($perms as $k => $v) {
$data = array(
'user_id' => $user_id,
'perm_id' => $v
);
$this->create($this->tables[6], $data);
}
}
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
return $this->db_error;
} else {
$this->applog->msg('更新用户禁用权限');
return 1;
}
}
/**
* 取得指定用户的角色
*
* @param int $id
* 用户id
*/
public function get_user_role ($id)
{
// 取得角色数据
$all_roles = $this->list_all($this->tables[2]);
// 取得指定用户的角色
$rs = $this->list_all_where($this->tables[5], 'user_id', $id);
if ($rs) {
foreach ($rs as $user_role) {
$user_roles[] = $user_role->role_id;
}
} else {
$user_roles = false;
}
$data['all_roles'] = $all_roles; // 所有角色
$data['user_roles'] = $user_roles; // 用户的角色id数组
return $data;
}
/**
* 保存用户的角色
*
* @return int|string 成功返回1,否则返回出错信息
*/
public function save_user_role ()
{
$user_id = $this->input->post('user_id');
$roles = $this->input->post('c0');
// 删除用户的旧角色
$this->db->delete($this->tables[5], array(
'user_id' => $user_id
));
$this->db->trans_start();
if ($roles) {
foreach ($roles as $k => $v) {
$data = array(
'user_id' => $user_id,
'role_id' => $v
);
$this->create($this->tables[5], $data);
}
}
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
return $this->db_error;
} else {
$this->applog->msg('更新用户角色');
return 1;
}
}
/**
* 获取用户的权限
* @param unknown_type $id
*/
public function get_user_perms($id){
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$orderField = $this->input->post('orderField') ? $this->input->post('orderField') : 'a.id';
$orderDirection = $this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'desc';
$startOffset = $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) * $per_page : 0;
//获取该用户的信息
$data['user'] = $this->db->get_where($this->tables[0], array('id' => $id))->row_array();
$this->db->select("a.user_id, b.id, b.dep_num, b.dep_name, b.father_dep_id,
b.lvl, b.desc, c.dep_name as father_dep_name");
$this->db->from("{$this->tables[1]} as a");
$this->db->join("{$this->tables[2]} as b", 'a.dep_id = b.id', 'left');
$this->db->join("{$this->tables[2]} as c", 'b.father_dep_id = c.id', 'left');
$this->db->where("a.user_id", $id);
$this->db->limit($per_page, $startOffset);
$this->db->order_by($orderField, $orderDirection);
$data['list'] = $this->db->get()->result();
$this->db->select("a.user_id, b.id, b.dep_num, b.dep_name, b.father_dep_id,
b.lvl, b.desc, c.dep_name as father_dep_name");
$this->db->from("{$this->tables[1]} as a");
$this->db->join("{$this->tables[2]} as b", 'a.dep_id = b.id', 'left');
$this->db->join("{$this->tables[2]} as c", 'b.father_dep_id = c.id', 'left');
$this->db->where("a.user_id", $id);
$data['total'] = $this->db->get()->num_rows();
return $data;
}
/**
* 删除用户权限
* @param unknown_type $id
* @return number|string
*/
public function delete_user_perm($id){
$this->db->trans_start();
$this->delete($this->tables[1], $id);
$this->db->trans_complete();
if ($this->db->trans_status() === TRUE) {
return 1;
} else {
return $this->db_error;
}
}
public function save_user_perms(){
$data = array(
'dep_id' => $this->input->post('dep', true),
'user_id' => $this->input->post('user_id', true)
);
$this->db->select('id');
$this->db->from($this->tables[1]);
$this->db->where('dep_id', $data['dep_id']);
$this->db->where('user_id', $data['user_id']);
$num = $this->db->get()->num_rows();
if($num == 0){
$this->db->trans_start();
$this->create($this->tables[1], $data);
$this->db->trans_complete();
}else{
return '已经有这个权限了';
}
if ($this->db->trans_status() === TRUE) {
return 1;
} else {
return $this->db_error;
}
}
/**
* ********************************用户**********************************
*/
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* 自定义异常错误处理类
*
* @package app
* @subpackage Libraries
* @category Exceptions
* @author bruce.yang<<EMAIL>>
*/
class MY_Exceptions extends CI_Exceptions{
/**
* 404找不到文件处理
* @see CI_Exceptions::show_404()
*/
function show_404($page = '', $log_error = TRUE)
{
$heading = "404 Page Not Found";
$message = "The page you requested was not found.".$page;
// By default we log this, but allow a dev to skip it
if ($log_error)
{
log_message('error', '404 Page Not Found --> '.$page);
}
$info = array(
"statusCode"=>"300",
"message"=>$message
);
header('Content-type: text/json');
echo json_encode($info);
exit();
}
/**
* 500服务器错误处理
* @see CI_Exceptions::show_error()
*/
function show_error($heading, $message, $template = 'error_general', $status_code = 500)
{
$message = '<p>'.implode('</p><p>', ( ! is_array($message)) ? array($message) : $message).'</p>';
$info = array(
"statusCode"=>"300",
"message"=>$heading.'<br />'.$message.'<br />'
);
header('Content-type: text/json');
echo json_encode($info);
exit();
}
/**
* php解析错误处理
* @see CI_Exceptions::show_php_error()
*/
function show_php_error($severity, $message, $filepath, $line)
{
$severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity];
$filepath = str_replace("\\", "/", $filepath);
// For safety reasons we do not show the full file path
if (FALSE !== strpos($filepath, '/'))
{
$x = explode('/', $filepath);
$filepath = $x[count($x)-2].'/'.end($x);
}
$info = array(
"statusCode"=>"300",
"message"=>$message.'<br />'.$filepath.'<br />'.$line
);
$this->CI =& get_instance();
//$this->CI->db->trans_rollback();
header('Content-type: text/json');
echo json_encode($info);
exit();
}
}
/* End of file MY_Exceptions.php */
/* Location: ./application/controllers|models/MY_Exceptions.php */<file_sep><?php
if (! defined('BASEPATH'))
exit('No direct script access allowed');
/**
*
*@function 文章管理模型
*@date 2013-10-14
*@author gerui
*@email <<EMAIL>>
*/
class Article_model extends MY_Model{
protected $tables = array(
);
public function __construct()
{
parent::__construct();
}
/**
* 文章列表
* @return unknown
*/
public function list_article(){
$data = '';
return $data;
}
public function __destruct(){
parent::__destruct();
}
}
/* End of file article_model.php */
/* Location: ./application/models/article_model.php */<file_sep><?php
if (! defined('BASEPATH'))
exit('No direct script access allowed');
/**
* 扩展业务控制器
*
* 提供了权限认证功能
* @package app
* @subpackage Libraries
* @category controller
* @author bruce.yang<<EMAIL>>
*
*/
class MY_Controller extends CI_Controller
{
public function __construct ()
{
parent::__construct();
$this->load->model('log_model', 'applog');
}
}
/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */<file_sep><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html" style="height: 100%">
<head>
<meta charset="utf-8">
<meta name="viewport" content="target-densitydpi=device-dpi, width=device-width, initial-scale=1.0, maximum-scale=1">
<meta name="description" content="My HomePage">
<meta name="author" content="<NAME>">
<meta name="keywords" content="windows 8, modern style, Metro UI, style, modern, css, framework">
<link href="<?php echo base_url();?>metro/css/modern.css" rel="stylesheet">
<link href="<?php echo base_url();?>metro/css/modern-responsive.css" rel="stylesheet">
<link href="<?php echo base_url();?>metro/css/site.css" rel="stylesheet" type="text/css">
<link href="<?php echo base_url();?>metro/js/google-code-prettify/prettify.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/jquery.mousewheel.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/moment.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/moment_langs.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/dropdown.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/accordion.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/buttonset.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/carousel.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/input-control.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/pagecontrol.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/rating.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/slider.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/tile-slider.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/tile-drag.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/calendar.js"></script>
<title>GeRui's Home</title>
</head>
<body style="height: 100%" class="metrouicss bg-color-purple">
<div class="grid">
<div class="row">
<div class="span6">
</div>
<div class="span4 " style="margin: 20px">
<h1 style="text-align:center" class="fg-color-orange">登录</h1>
<form style="margin: 20px 0px;" action="<?php echo site_url('login/chk_login')?>">
<div class="input-control text">
<input type="text"/>
<button class="helper"></button>
</div>
<div class="input-control password">
<input type="password">
<button class="helper"></button>
</div>
<div class="place-right">
<input type="submit" value="登录" style="margin: 0px"/>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
if (! defined('BASEPATH'))
exit('No direct script access allowed');
/**
*
*@function 联系人管理模型
*@date 2013-10-13
*@author gerui
*@email <<EMAIL>>
*/
class Cnt_tree_model extends MY_Model{
protected $tables = array(
'cnt', //0
'cnt_dep_rel', //1
'dep', //2
'user', //3
'user_dep_rel' //4
);
private $all_dep = array();
private $all_chil_dep = array();
private $dep_tree = '';
public function __construct()
{
parent::__construct();
}
/**
* 联系人列表
* @return unknown
*/
public function list_cnt(){
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$orderField = $this->input->post('orderField') ? $this->input->post('orderField') : 'a.id';
$orderDirection = $this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'desc';
$startOffset = $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) * $per_page : 0;
$dep = $this->get_dep_all_uniq();
$dep_id_array = array();
$dep_array = array();
foreach($dep as $line){
if (!in_array($line['id'], $dep_id_array)){
//没有该部门就加入,有该部门就跳过
array_push($dep_id_array, $line['id']);
array_push($dep_array, $line);
}
}
$data['dep'] = $dep_array;
$data['tree'] = false;
$this->db->select('a.id, a.cnt_num, a.cnt_name, a.phone, a.desc, a.create_time, a.update_time, c.dep_name');
$this->db->from("{$this->tables[0]} as a");
$this->db->join("{$this->tables[1]} as b", "a.id = b.cnt_id", "left");
$this->db->join("{$this->tables[2]} as c", "b.dep_id = c.id", "left");
if(!empty($dep_id_array)){
$this->db->where_in("c.id", $dep_id_array);
}else{
//如果为空,则用户没有任何权限
$this->db->where('a.id', -1);
}
$this->db->limit($per_page, $startOffset);
$this->db->order_by($orderField, $orderDirection);
$result = $this->db->get()->result();
$data['list'] = $result;
$this->db->select('a.id');
$this->db->from("{$this->tables[0]} as a");
$this->db->join("{$this->tables[1]} as b", "a.id = b.cnt_id", "left");
$this->db->join("{$this->tables[2]} as c", "b.dep_id = c.id", "left");
if(!empty($dep_id_array)){
$this->db->where_in("c.id", $dep_id_array);
}else{
//如果为空,则用户没有任何权限
$this->db->where('a.id', -1);
}
$total = $this->db->get()->num_rows();
$data['total'] = $total;
return $data;
}
/**
* 获取一个部门下的所有子部门
* @param $dep_id 部门的id
* @return multitype:
*/
public function get_all_chil($dep_id){
$dep_info = $this->db->get_where($this->tables[2], array('id' => $dep_id))->result_array();
$this->all_dep = array();
$this->get_dep_all_recur($dep_info);
$all_chil = $this->all_dep;
return $all_chil;
}
/**
* 列出所有联系人
* @return unknown
*/
public function list_cnt_tree($dep_id){
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$orderField = $this->input->post('orderField') ? $this->input->post('orderField') : 'a.id';
$orderDirection = $this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'desc';
$startOffset = $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) * $per_page : 0;
//获取所有该部门的下属部门 (包含自己)
$all_chil = $this->get_all_chil($dep_id);
$all_chil_id_array = array();
foreach($all_chil as $line){
if (!in_array($line['id'], $all_chil_id_array)){
//没有该部门就加入,有该部门就跳过
array_push($all_chil_id_array, $line['id']);
}
}
//用户的全部的部门,用于select显示
$dep = $this->get_dep_all_uniq();
//print_r($dep);
//对遍历出来的部门去重
$dep_id_array = array();
$dep_array = array();
foreach($dep as $line){
if (!in_array($line['id'], $dep_id_array)){
//没有该部门就加入,有该部门就跳过
array_push($dep_id_array, $line['id']);
array_push($dep_array, $line);
}
}
$data['dep'] = $dep_array;
$data['tree'] = true;
$data['dep_id'] = $dep_id;
$data['treeFlag'] = true;
$this->db->select('a.id, a.cnt_num, a.cnt_name, a.phone, a.desc, a.create_time, a.update_time, c.dep_name');
$this->db->from("{$this->tables[0]} as a");
$this->db->join("{$this->tables[1]} as b", "a.id = b.cnt_id", "left");
$this->db->join("{$this->tables[2]} as c", "b.dep_id = c.id", "left");
$this->db->where_in('c.id', $all_chil_id_array);
$this->db->limit($per_page, $startOffset);
$this->db->order_by($orderField, $orderDirection);
$result = $this->db->get()->result();
$data['list'] = $result;
$this->db->select('a.id');
$this->db->from("{$this->tables[0]} as a");
$this->db->join("{$this->tables[1]} as b", "a.id = b.cnt_id", "left");
$this->db->join("{$this->tables[2]} as c", "b.dep_id = c.id", "left");
$this->db->where_in('c.id', $all_chil_id_array);
$total = $this->db->get()->num_rows();
$data['total'] = $total;
return $data;
}
/**
* 根据条件查找联系人
*/
public function list_cnt_search(){
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$orderField = $this->input->post('orderField') ? $this->input->post('orderField') : 'a.id';
$orderDirection = $this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'desc';
$startOffset = $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) * $per_page : 0;
$dep = $this->get_dep_all_uniq();
$dep_id_array = array();
$dep_array = array();
foreach($dep as $line){
array_push($dep_id_array, $line['id']);
array_push($dep_array, $line);
}
$data['dep'] = $dep_array;
$data['tree'] = false;
if ($this->input->post('dep'))
{
//有提交新的搜索
$s_dep = $this->input->post('dep');
$this->session->set_userdata('dep',$s_dep);
}else{
if ($this->input->post('page_dep'))
{
$s_dep = $this->session->userdata('dep');
}
else
{
//空白搜索
$s_dep = false;
$this->session->unset_userdata('dep');
}
}
if ($this->input->post('cnt_num'))
{
$s_cnt_num = $this->input->post('cnt_num');
$this->session->set_userdata('cnt_num',$s_cnt_num);
}else{
if ($this->input->post('page_cnt_num'))
{
$s_cnt_num = $this->session->userdata('cnt_num');
}
else
{
$s_cnt_num = false;
$this->session->unset_userdata('cnt_num');
}
}
if ($this->input->post('cnt_name'))
{
$s_cnt_name = $this->input->post('cnt_name');
$this->session->set_userdata('cnt_name',$s_cnt_name);
}else{
if ($this->input->post('page_cnt_name'))
{
$s_cnt_name = $this->session->userdata('cnt_name');
}
else
{
//没有输入
$s_cnt_name = false;
$this->session->unset_userdata('cnt_name');
}
}
if ($this->input->post('phone'))
{
$s_phone = $this->input->post('phone');
$this->session->set_userdata('phone',$s_phone);
}else{
if ($this->input->post('page_phone')){
$s_phone = $this->session->userdata('phone');
}else{
$s_phone = false;
$this->session->unset_userdata('phone');
}
}
if ($this->input->post('desc'))
{
$s_desc = $this->input->post('desc');
$this->session->set_userdata('desc',$s_desc);
}else{
if($this->input->post('page_desc')){
$s_desc = $this->session->userdata('desc');
}else{
$s_desc = false;
$this->session->unset_userdata('desc');
}
}
$this->db->select('a.id, a.cnt_num, a.cnt_name, a.phone, a.desc, a.create_time, a.update_time, c.dep_name');
$this->db->from("{$this->tables[0]} as a");
$this->db->join("{$this->tables[1]} as b", "a.id = b.cnt_id", "left");
$this->db->join("{$this->tables[2]} as c", "b.dep_id = c.id", "left");
if(!empty($dep_id_array)){
$this->db->where_in("c.id", $dep_id_array);
}else{
//如果为空,则用户没有任何权限
$this->db->where('a.id', -1);
}
if ($s_dep){
//ALL时,$s_dep=0,不会进入,表示所有部门
$this->db->where('c.id', $s_dep);
}
if ($s_cnt_num){
$this->db->like('a.cnt_num', $s_cnt_num);
}
if ($s_cnt_name){
$this->db->like('a.cnt_name', $s_cnt_name);
}
if ($s_phone){
$this->db->like('a.phone', $s_phone);
}
if ($s_desc){
$this->db->like('a.desc', $s_desc);
}
$this->db->limit($per_page, $startOffset);
$this->db->order_by($orderField, $orderDirection);
$result = $this->db->get()->result();
$data['list'] = $result;
$this->db->select('a.id');
$this->db->from("{$this->tables[0]} as a");
$this->db->join("{$this->tables[1]} as b", "a.id = b.cnt_id", "left");
$this->db->join("{$this->tables[2]} as c", "b.dep_id = c.id", "left");
if(!empty($dep_id_array)){
$this->db->where_in("c.id", $dep_id_array);
}else{
//如果为空,则用户没有任何权限
$this->db->where('a.id', -1);
}
if ($s_dep){
//ALL时,$s_dep=0,不会进入,表示所有部门
$this->db->where('c.id', $s_dep);
}
if ($s_cnt_num){
$this->db->like('a.cnt_num', $s_cnt_num);
}
if ($s_cnt_name){
$this->db->like('a.cnt_name', $s_cnt_name);
}
if ($s_phone){
$this->db->like('a.phone', $s_phone);
}
if ($s_desc){
$this->db->like('a.desc', $s_desc);
}
$total = $this->db->get()->num_rows();
$data['total'] = $total;
return $data;
}
/**
* 保存联系人信息,包括新增保存,修改保存
* @return string|number 1 => success;
*/
public function save_cnt(){
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<li>', '</li>');
$this->form_validation->set_rules('cnt_name', '联系人姓名', 'trim|required|xss_clean');
$this->form_validation->set_rules('cnt_num', '联系人编号', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
return validation_errors();
}
else
{
$data = array(
'cnt_num' => $this->input->post('cnt_num', true),
'cnt_name' => $this->input->post('cnt_name', true),
'phone' => $this->input->post('phone', true),
'desc' => $this->input->post('desc', true),
'update_time' => date('Y-m-d H:i:s')
);
//提交新的部门
$dep = $this->input->post('dep', true);
$cnt_num = $this->is_exists($this->tables[0], 'cnt_num', $data['cnt_num']);
$cnt_name = $this->is_exists($this->tables[0], 'cnt_name', $data['cnt_name']);
$id = $this->input->post('id');
if ($id)
{
$old_dep = $this->input->post('dep_id', true);
//更新保存
if ($cnt_num && $cnt_num['id'] != $id)
return '联系人编号已存在';
if ($cnt_name && $cnt_name['id'] != $id)
return '联系人姓名已存在';
$this->db->trans_start();
$this->update($this->tables[0], $id, $data);
if ($dep != $old_dep)
{
//修改了所属的部门
$data2 = array(
'cnt_id' => $id,
'dep_id' => $dep
);
$this->db->where(array('cnt_id' => $id, 'dep_id' => $old_dep));
$this->db->update($this->tables[1], $data2);
}
$this->db->trans_complete();
if ($this->db->trans_status() == false)
{
return $this->db_error;
}
else
{
$this->applog->msg('成功修改联系人');
return 1;
}
}else{
//新增保存
if($cnt_num)
{
return '联系人编号已存在';
}
if ($cnt_name){
return '联系人姓名已存在';
}
$data['create_time'] = date('Y-m-d H:i:s');
$this->db->trans_start();
$this->create($this->tables[0], $data);
$cnt_id = $this->db->insert_id();
$data_rel = array(
'cnt_id' => $cnt_id,
'dep_id' => $dep
);
$this->create($this->tables[1], $data_rel);
$this->db->trans_complete();
if ($this->db->trans_status() == false)
{
return $this->db_error;
}
else
{
$this->applog->msg('成功添加联系人');
return 1;
}
}
}
}
/**
* 删除指定的联系人
* @param $id 联系人id
*/
public function delete_cnt($id){
$this->db->trans_start();
$this->delete($this->tables[0], $id);
$this->db->delete($this->tables[1], array('cnt_id' => $id));
$this->db->trans_complete();
if ($this->db->trans_status() == false)
{
return $this->db_error;
}
else
{
$this->applog->msg('删除联系人');
return 1;
}
}
/**
* 获取要修改的联系人信息
*/
public function get_cnt($id){
$this->db->select('a.id, a.cnt_num, a.cnt_name, a.phone, a.desc,
a.create_time, a.update_time, b.dep_id, c.dep_name');
$this->db->from("{$this->tables[0]} as a");
$this->db->join("{$this->tables[1]} as b", "a.id = b.cnt_id", "left");
$this->db->join("{$this->tables[2]} as c", "b.dep_id = c.id", "left");
$this->db->where(array('a.id' => $id));
$result = $this->db->get()->result_array();
return $result[0];
}
/**
* 循环获取用户所有部门
*/
public function get_dep_tree(){
//获取所有在数据库中写入的部门
$dep = $this->get_dep_root_object();
$this->whole_dep = $dep;
$HTML=<<<HTML
<div class="accordion" fillSpace="sidebar">
<div class="accordionHeader">
<h2><span>Folder</span>部门</h2>
</div>
<div class="accordionContent">
<ul class="tree">
HTML;
$this->dep_tree = $HTML;
$lvl = 0;
$str = $this->get_dep_recur($dep, $lvl);
$this->dep_tree .= '</ul></div></div>';
return $this->dep_tree;
}
/**
* 递归获取所有部门
*/
public function get_dep_recur($dep, $lvl){
if (!empty($dep)){
$is_root = true;
foreach($dep as $k => $line){
$url = site_url("cnt/list_cnt_tree/$line->id");
$dep_name = $line->dep_name;
//判断根层的部门是否是其它部门子层
if ($lvl == 0){
foreach($dep as $root){
//遍历所有根层,判断是否存在父群组
if ($line->father_dep_id == $root->id){
$is_root = false;
break;
}
}
if(!$is_root){
continue;
}
}
$chil_dep = $this->get_chil_dep_object($line->id, $line->lvl);
$HTML=<<<HTML
<li>
<a href="$url" target="navTab" rel="list_cnt" fresh="true">$dep_name</a>
<ul>
HTML;
$this->dep_tree .= $HTML;
$this->get_dep_recur($chil_dep, $lvl + 1);
$this->dep_tree .= '</ul></li>';
}
}
}
/**
* 数组形式
* @param unknown_type $father_id
* @param unknown_type $father_lvl
*/
public function get_chil_dep_array($father_id, $father_lvl){
$rs = $this->get_chil_dep($father_id, $father_lvl);
return $rs->result_array();
}
/**
* 对象形式
* @param unknown_type $father_id
* @param unknown_type $father_lvl
*/
public function get_chil_dep_object($father_id, $father_lvl){
$rs = $this->get_chil_dep($father_id, $father_lvl);
return $rs->result();
}
/**
* 根据父部门从数据库中获取子部门
*/
public function get_chil_dep($father_id, $father_lvl){
$chil_lvl = $father_lvl + 1;
$this->db->select('id, dep_name, dep_num, father_dep_id, lvl, desc');
$this->db->from($this->tables[2]);
$this->db->where(array('father_dep_id' => $father_id));
$this->db->where(array('lvl' => $chil_lvl));
$chil_dep = $this->db->get();
return $chil_dep;
}
/**
* 返回对象形式的部门
*/
public function get_dep_root_object(){
$rs = $this->get_dep_root();
return $rs->result();
}
/**
* 返回数组形式的部门
*/
public function get_dep_root_array(){
$rs = $this->get_dep_root();
return $rs->result_array();
}
/**
* 获取被管理的所有0级部门,即根部门
* @return unknown
*/
public function get_dep_root(){
if ($this->session->userdata('username') == 'root'){
$this->db->select('id, dep_name, dep_num, father_dep_id, lvl, desc');
$this->db->from("{$this->tables[2]}");
$this->db->where(array('lvl' => 0));
}else{
$user_id = $this->session->userdata('id');
$this->db->select('b.id, b.dep_name, b.dep_num, b.father_dep_id, b.lvl, b.desc');
$this->db->from("{$this->tables[4]} as a");
$this->db->join("{$this->tables[2]} as b", "a.dep_id = b.id", "left");
$this->db->where(array('a.user_id' => $user_id));
}
return $this->db->get();
}
/**
* 去除其中的重复部门
* @return multitype:
*/
public function get_dep_all_object_uniq(){
$dep = $this->get_dep_all_object();
$dep_id_array = array();
$dep_array = array();
foreach($dep as $line){
if (!in_array($line->id, $dep_id_array)){
//没有该部门就加入,有该部门就跳过
array_push($dep_id_array, $line->id);
array_push($dep_array, $line);
}
}
return $dep_array;
}
/**
* 除去自己和自己的子部门剩下部门
*/
public function get_dep_all_uniq_excl_self($dep_id){
$dep = $this->get_dep_all_excl_self($dep_id);
$dep_id_array = array();
$dep_array = array();
foreach($dep as $line){
if (!in_array($line['id'], $dep_id_array)){
//没有该部门就加入,有该部门就跳过
array_push($dep_id_array, $line['id']);
array_push($dep_array, $line);
}
}
return $dep_array;
}
/**
* 获取除去自己和自己的子部门剩下部门
*/
public function get_dep_all_excl_self($dep_id){
//数据库中有直接关系的部门
$dir_dep = $this->get_dep_root_array();
//遍历直接关联的部门,获取下级部门
$this->all_dep = array();
if (!empty($dir_dep)){
$this->get_dep_all_recur_excl_self($dir_dep, $dep_id);
}else{
//没有可以管理的部门
return $dir_dep;
}
$dep = $this->all_dep;
return $dep;
}
/**
* 递归出所有子部门,如果遇到部门则跳过
* @param unknown_type $dep_array
*/
public function get_dep_all_recur_excl_self($dep_array, $dep_id)
{
if (!empty($dep_array)){
foreach($dep_array as $line){
if($line['id'] != $dep_id){
array_push($this->all_dep, $line);
$chil_dep_array = $this->get_chil_dep_array($line['id'], $line['lvl']);
if (!empty($chil_dep_array)){
//如果还有子部门,继续递归
$this->get_dep_all_recur_excl_self($chil_dep_array, $dep_id);
}
}
}
}
}
/**
* 去除其中的重复部门,
* @return 各个部门数组
*/
public function get_dep_all_uniq(){
$dep = $this->get_dep_all();
$dep_id_array = array();
$dep_array = array();
foreach($dep as $line){
if (!in_array($line['id'], $dep_id_array)){
//没有该部门就加入,有该部门就跳过
array_push($dep_id_array, $line['id']);
array_push($dep_array, $line);
}
}
return $dep_array;
}
/**
* 去除其中的重复部门,最后的部门id
* @return multitype:
*/
public function get_dep_all_uniq_id(){
$dep = $this->get_dep_all();
$dep_id_array = array();
foreach($dep as $line){
if (!in_array($line['id'], $dep_id_array)){
//没有该部门就加入,有该部门就跳过
array_push($dep_id_array, $line['id']);
}
}
return $dep_id_array;
}
/**
* 获取被管理的所有部门,递归得出
* @return unknown
*/
public function get_dep_all_object(){
//数据库中有直接关系的部门
$dir_dep = $this->get_dep_root_object();
//遍历直接关联的部门,获取下级部门
$this->all_dep = array();
if (!empty($dir_dep)){
$this->get_dep_all_recur_object($dir_dep);
}else{
//没有可以管理的部门
return $dir_dep;
}
$dep = $this->all_dep;
return $dep;
}
/**
* 递归出所有子部门
* @param unknown_type $dep_array
*/
public function get_dep_all_recur_object($dep_array)
{
foreach($dep_array as $line){
array_push($this->all_dep, $line);
$chil_dep_array = $this->get_chil_dep_object($line->id, $line->lvl);
if (!empty($chil_dep_array)){
//如果还有子部门,继续递归
$this->get_dep_all_recur_object($chil_dep_array);
}
}
}
/**
* 获取被管理的所有部门,递归得出
* @return unknown
*/
public function get_dep_all(){
//数据库中有直接关系的部门
$dir_dep = $this->get_dep_root_array();
//遍历直接关联的部门,获取下级部门
$this->all_dep = array();
if (!empty($dir_dep)){
$this->get_dep_all_recur($dir_dep);
}else{
//没有可以管理的部门
return $dir_dep;
}
$dep = $this->all_dep;
return $dep;
}
/**
* 递归出所有子部门
* @param unknown_type $dep_array
*/
public function get_dep_all_recur($dep_array)
{
if (!empty($dep_array)){
foreach($dep_array as $line){
array_push($this->all_dep, $line);
$chil_dep_array = $this->get_chil_dep_array($line['id'], $line['lvl']);
if (!empty($chil_dep_array)){
//如果还有子部门,继续递归
$this->get_dep_all_recur($chil_dep_array);
}
}
}
}
public function __destruct(){
parent::__destruct();
}
}
/* End of file cnt_tree_model.php */
/* Location: ./application/models/cnt_tree_model.php */<file_sep><div class="page">
<div class="nav-bar">
<div class="nav-bar-inner padding10">
<span class="pull-menu"></span>
<a href="<?php echo base_url();?>"><span class="element brand">
<img class="place-left" src="<?php echo base_url();?>metro/images/logo32.png" style="height: 20px"/>
GeRui's<small> Home</small>
</span></a>
<div class="divider"></div>
<ul class="menu">
<li><a href="<?php echo site_url('home');?>">首页</a></li>
<li><a href="<?php echo site_url('work');?>">近期工作</a></li>
<li><a href="<?php echo site_url('article');?>">美文欣赏</a></li>
<li data-role="dropdown">
<a href="#">Git</a>
<ul class="dropdown-menu" style="overflow: hidden; display: none;">
<li><a href="https://github.com/bairuiworld/" target="_blank">GitHub</a></li>
<li><a href="http://git.oschina.net/bairuiworld" target="_blank">Git@OSC</a></li>
</ul>
</li>
<li data-role="dropdown">
<a href="#">博客</a>
<ul class="dropdown-menu" style="overflow: hidden; display: none;">
<li><a href="http://www.cnblogs.com/gr-nick/" target="_blank">博客园</a></li>
<li><a href="http://www.forgerui.tk/blog" target="_blank">个人博客</a></li>
</ul>
</li>
<li><a href="http://www.forgerui.tk/talk" target="_blank">论坛</a></li>
<li><a href="<?php echo site_url('about')?>">关于</a></li>
</ul>
</div>
</div>
</div>
<!-- Baidu Button BEGIN -->
<script type="text/javascript" id="bdshare_js" data="type=slide&img=6&mini=1&pos=right&uid=732481" ></script>
<script type="text/javascript" id="bdshell_js"></script>
<script type="text/javascript">
var bds_config={"bdTop":19};
document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil(new Date()/3600000);
</script>
<!-- Baidu Button END --><file_sep>/**
* TileSlider- jQuery plugin for MetroUiCss framework
*/
$.easing.doubleSqrt = function(t, millisecondsSince, startValue, endValue,
totalDuration) {
var res = Math.sqrt(Math.sqrt(t));
return res;
};
(function($) {
var pluginName = 'TileSlider', initAllSelector = '[data-role=tile-slider], .block-slider, .tile-slider', paramKeys = [
'Period', 'Duration', 'Direction' ];
$[pluginName] = function(element, options) {
if (!element) {
return $()[pluginName]({
initAll : true
});
}
// default settings
// TODO: expose defaults with a $.fn[pluginName].defaults ={} block;
var defaults = {
// the period for changing images
period : 2000,
// animation length
duration : 1000,
// direction of animation (up, down, left, right)
direction : 'up'
};
// object plugin
var plugin = this;
// plugin settings
plugin.settings = {};
var $element = $(element); // reference to the jQuery version of DOM element
var blocks, //
currentBlockIndex, // the index of the current block
slideInPosition, // the start location of the block before the advent
slideOutPosition, // the final location of the block when you hide
tileWidth, // tile dimensions
tileHeight;
// initialize
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
// all blocks
blocks = $element.children(".tile-content");
// Do nothing if only single content block
if (blocks.length <= 1) {
return;
}
// the index of the currently active block
currentBlockIndex = 0;
// current tile dimensions
tileWidth = $element.innerWidth();
tileHeight = $element.innerHeight();
// block position
slideInPosition = getSlideInPosition();
slideOutPosition = getSlideOutPosition();
// prepare the block animation
blocks.each(function(index, block) {
block = $(block);
// blocks should be position:absolute
// may be specified through style class
// check and add if it is not
if (block.css('position') !== 'absolute') {
block.css('position', 'absolute');
}
// hide all blocks except the first
// TODO: add random start option
if (index !== 0) {
block.css('left', tileWidth);
}
});
// Use setInterval to do the period run
// TODO: preserve return value of setInterval to handle a clean stop.
setInterval(function() {
slideBlock();
}, plugin.settings.period);
};
// changing blocks
var slideBlock = function() {
var slideOutBlock, // the block that you want to hide
slideInBlock, // block to show
mainPosition = {
'left' : 0,
'top' : 0
}, options;
slideOutBlock = $(blocks[currentBlockIndex]);
currentBlockIndex++;
if (currentBlockIndex >= blocks.length) {
currentBlockIndex = 0;
}
slideInBlock = $(blocks[currentBlockIndex]);
slideInBlock.css(slideInPosition);
options = {
duration : plugin.settings.duration,
easing : 'doubleSqrt'
};
slideOutBlock.animate(slideOutPosition, options);
slideInBlock.animate(mainPosition, options);
};
// TODO: Consider refactoring the two functions below into one, given that the return values of
// each are simply the negative of the twin (given that -0=0)
// would seem an opportunity to shrink code size - consider good function name and usage to not
// diminish the self-documentation value of the two functions.
/**
*
* Returns the starting position for the block that you want to appear {left: xxx, top: yyy}
*/
var getSlideInPosition = function() {
var pos;
if (plugin.settings.direction === 'left') {
pos = {
'left' : tileWidth,
'top' : 0
}
} else if (plugin.settings.direction === 'right') {
pos = {
'left' : -tileWidth,
'top' : 0
}
} else if (plugin.settings.direction === 'up') {
pos = {
'left' : 0,
'top' : tileHeight
}
} else if (plugin.settings.direction === 'down') {
pos = {
'left' : 0,
'top' : -tileHeight
}
}
return pos;
};
/**
*
* Returns the final position for the block to escape {left: xxx, top: yyy}
*/
var getSlideOutPosition = function() {
var pos;
if (plugin.settings.direction === 'left') {
pos = {
'left' : -tileWidth,
'top' : 0
}
} else if (plugin.settings.direction === 'right') {
pos = {
'left' : tileWidth,
'top' : 0
}
} else if (plugin.settings.direction === 'up') {
pos = {
'left' : 0,
'top' : -tileHeight
}
} else if (plugin.settings.direction === 'down') {
pos = {
'left' : 0,
'top' : tileHeight
}
}
return pos;
};
plugin.getParams = function() {
// code goes here
};
plugin.init();
};
$.fn[pluginName] = function(options) {
var elements = options && options.initAll ? $(initAllSelector) : this;
return elements.each(function() {
var that = $(this), params = {}, plugin;
if (undefined == that.data(pluginName)) {
$.each(paramKeys, function(index, key) {
// TODO: Look into IE10 issue
// added try/catch block as I was seeing "no such method .toLowerCase()" errors in IE10,
// although not in Chrome/Win (27.0.1453.94) Safari/Win (5.1.7) or Firefox/Win (21.0)
// interestingly, catching and ignoring the exeception has tiles in IE10 behave correctly, but
// throwing an "alert" into the catch will result in the tiles not having specified settings
// applied - only the defaults.
try {
params[key[0].toLowerCase() + key.slice(1)] = that
.data('param' + key);
} catch (e) {
}
});
plugin = new $[pluginName](this, params);
that.data(pluginName, plugin);
}
});
};
// autoinit
$(function() {
$()[pluginName]({
initAll : true
});
});
})(jQuery);
<file_sep><?php
if (! defined('BASEPATH'))
exit('No direct script access allowed');
/**
* 系统设置模型
*
* @package app
* @subpackage core
* @category model
* @author Cmy<<EMAIL>>;Gr<<EMAIL>>
*
*/
class Sysconfig_model extends MY_Model
{
protected $tables = array(
);
public function __construct ()
{
parent::__construct();
}
public function __destruct ()
{
parent::__destruct();
}
}
/* End of file sysconfig_model.php */
/* Location: ./application/models/sysconfig_model.php */<file_sep>#My Homepage
===========
利用CodeIgniter与Metro UI CSS 实现的个人主页<br>
可以帮助学习CodeIgniter和Metro UI CSS 框架<file_sep><?php include(APPPATH."views/header.php")?>
<div class="page secondary with-sidebar" id="page-index">
<?php include(APPPATH."views/leftside.php")?>
<div class="page-region">
<div class="page-region-content">
<div class="grid">
<div class="row">
<div class="span2 offset7">
<?php $login_url = site_url('login');?>
<button class="image-button place-right bg-color-blueDark fg-color-white" style="margin: 0px" onclick="document.location.href='<?php echo $login_url;?>'">
登录
<i class="icon-user" style="margin: 0px 10px 0px 0px"></i>
</button>
</div>
</div>
</div>
<div class="grid">
<div class="row">
<div class="span9">
<div class="carousel" style="height: 200px;" data-role="carousel" data-param-period="3000" data-param-effect="fade" >
<div class="slides">
<div class="slide image" id="slide1" >
<img src="<?php echo base_url();?>metro/images/panner1.jpg">
<div class="description">
1
</div>
</div>
<div class="slide image" id="slide2" >
<img src="<?php echo base_url();?>metro/images/panner2.jpg">
<div class="description">
2
</div>
</div>
<div class="slide image" id="slide3">
<img src="<?php echo base_url();?>metro/images/panner3.jpg">
<div class="description">
3
</div>
</div>
<div class="slide image" id="slide4">
<img src="<?php echo base_url();?>metro/images/panner4.jpg">
<div class="description">
4
</div>
</div>
</div>
<!-- <span class="control left bg-color-darken">‹</span>
<span class="control right bg-color-darken">›</span> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php include(APPPATH."views/footer.php")?><file_sep><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html" style="height: 100%">
<head>
<meta charset="utf-8">
<meta name="viewport" content="target-densitydpi=device-dpi, width=device-width, initial-scale=1.0, maximum-scale=1">
<meta name="description" content="My HomePage">
<meta name="author" content="<NAME>">
<meta name="keywords" content="windows 8, modern style, Metro UI, style, modern, css, framework">
<link href="<?php echo base_url();?>metro/css/modern.css" rel="stylesheet">
<link href="<?php echo base_url();?>metro/css/modern-responsive.css" rel="stylesheet">
<link href="<?php echo base_url();?>metro/css/site.css" rel="stylesheet" type="text/css">
<link href="<?php echo base_url();?>metro/js/google-code-prettify/prettify.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/jquery.mousewheel.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/moment.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/assets/moment_langs.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/dropdown.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/accordion.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/buttonset.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/carousel.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/input-control.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/pagecontrol.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/rating.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/slider.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/tile-slider.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/tile-drag.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>metro/js/modern/calendar.js"></script>
<title>GeRui's Home</title>
</head>
<body style="height: 100%" class="metrouicss bg-color-purple">
<div class="grid">
<div class="row">
<div class="span2 fg-color-white" style="margin: 30px 0px 0px 50px">
<span style="font-size: 45px; font-weight:bold;">开始</span>
</div>
<div class="span2 fg-color-white place-right" style="margin: 30px 50px 0px 0px">
<span style="font-size: 45px; font-weight:bold;">用户</span>
</div>
</div>
</div>
<div class="grid">
<div class="row">
<div class="tiles clearfix" style="margin: 80px 0px 0px 50px">
<div class="tile double bg-color-green">
<div class="tile-content">
<h5><EMAIL></h5>
<p style="margin: 20px 0px 10px 0px; font-size:15px">Re: thanks for</p>
<p>Congratulations!your book...</p>
</div>
<div class="brand">
<div class="badge">12</div>
<div class="icon"><img src="<?php echo base_url();?>metro/images/Mail128.png"/></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php include(APPPATH."views/header.php")?>
<div class="page secondary with-sidebar" id="page-index">
<div class="page-header">
<div class="page-header-content">
<h1>美文<small>阅读</small></h1>
<a href="<?php echo base_url();?>" class="back-button big page-back"></a>
</div>
</div>
<?php include(APPPATH."views/leftside.php")?>
<div class="page-region">
<div class="page-region-content">
<div class="grid">
<?php for($i = 0; $i < 10; $i++):?>
<div class="row">
<div class="span9 ">
<div class="span2" style="margin:40px 10px 0px 0px">
<h3><strong class="bg-color-grey">货币战争</strong></h3>
</div>
</div>
<div class="span8 offset1 bg-color-blueDark">
<p class="long-text">W3CPLUS是一个前端爱好者的家园,W3CPLUS努力打造最优秀的web 前端学习的站点。W3CPLUS力求原创,以一起学习,一起进步,共同分享为原则。W3CPLUS站提供了有关于css,css3,html,html5,jQuery,手机移动端的技术文档、DEMO、资源,与前端爱好者一起共勉。
W3CPLUS是一个前端爱好者的家园,W3CPLUS努力打造最优秀的web 前端学习的站点。W3CPLUS力求原创,以一起学习,一起进步,共同分享为原则。W3CPLUS站提供了有关于css,css3,html,html5,jQuery,手机移动端的技术文档、DEMO、资源,与前端爱好者一起共勉。</p>
</div>
</div>
<?php endfor;?>
</div>
</div>
</div>
</div>
<?php include(APPPATH."views/footer.php")?><file_sep><?php include(APPPATH."views/header.php")?>
<div class="page secondary with-sidebar" id="page-index">
<div class="page-header">
<div class="page-header-content">
<h1>近期<small>工作</small></h1>
<a href="<?php echo base_url();?>" class="back-button big page-back"></a>
</div>
</div>
<?php include(APPPATH."views/leftside.php")?>
<div class="page-region">
<div class="page-region-content">
<div class="grid span9">
<div class="row">
<div class="span9" style="background-color: #ccc; height: 200px;">
<div class="page snapped bg-color-blue">
<p style="padding: 20px;">近期工作</p>
</div>
<div class="page fill bg-color-orange">
<ol>
<li>学习Metro UI CSS,搭建个人主页</li>
<li>学习MATLAB</li>
</ol>
</div>
</div>
</div>
<div class="row">
</div>
</div>
</div>
</div>
<?php include(APPPATH."views/footer.php")?><file_sep><?php include(APPPATH."views/header.php")?>
<div class="page secondary with-sidebar" id="page-index">
<div class="page-header">
<div class="page-header-content">
<h1>相关<small>信息</small></h1>
<a href="<?php echo base_url();?>" class="back-button big page-back"></a>
</div>
</div>
<?php include(APPPATH."views/leftside.php")?>
<div class="page-region">
<div class="page-region-content">
<div class="grid">
<div class="row">
<ul class="accordion dark" data-role="accordion">
<li class="">
<a href="#">个人信息</a>
<div style="overflow: hidden; display: none;">
<div class="tile double bg-color-blueDark">
<div class="tile-content">
<img src="<?php echo base_url();?>metro/images/profile.png" class="place-right">
<h4 style="margin-bottom: 5px;"><NAME></h4>
<p> </p>
<p>邮箱: <EMAIL></p>
<p>个人博客: www.forgerui.tk/blog</p>
<p></p>
</div>
<div class="brand">
<span class="name">新浪微博: @brorld</span>
</div>
</div>
</div>
</li>
<li class="">
<a href="#">网站信息</a>
<div style="overflow: hidden; display: none;">
<div class="grid span9">
<div class="row">
<div class="span9" style="background-color: #ccc; height: 200px;">
<div class="page span3 snapped bg-color-blue">
<p style="padding: 20px; ">网站信息</p>
</div>
<div class="page span8 fill bg-color-purple">
<p style="padding: 20px;font-size:20px;font-style:bold;">Ge Rui的个人主页</p>
<p style="padding: 5px;"><span>特色:使用Metro UI CSS 框架,Win8风格</span></p>
<p style="padding: 5px;"><span>版本: v1.0</span></p>
</div>
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php include(APPPATH."views/footer.php")?><file_sep><?php
if (! defined('BASEPATH'))
exit('No direct script access allowed');
/**
* 操作日志模型
*
* @package app
* @subpackage core
* @category model
* @author bruce.yang<<EMAIL>>
*
*/
class Log_model extends MY_Model{
protected $table_name = 'log';
public function __construct()
{
parent::__construct();
}
/**
* 记录日志
* @param string $msg
* @return int|string 成功返回1,否则返回出错信息
*/
public function msg($msg)
{
$data = array(
'username' => $this->session->userdata('username'),
'ip' => $this->session->userdata('last_login_ip'),
'action' => $msg,
'info' => implode(';', $this->db->queries),
'add_time' => date("Y-m-d H:i:s")
);
if ($this->create($this->table_name, $data)) {
return 1;
} else {
return $this->db_error;
}
}
/**
* 返回分页数据和总数
*
* @return array 返回数组array('total'=>表记录总数,'list'=>记录列表)
*/
public function list_log(){
$total_rows = $this->count($this->table_name);
// 每页显示的记录条数,默认20条
$per_page = $this->input->post('numPerPage') ? $this->input->post('numPerPage') : 20;
$data['total'] = $total_rows;
// list_data(表,抓取记录数,偏离量,排序字段,排序方法);
$data['list'] = $this->list_data($this->table_name, $per_page, $this->input->post('pageNum') ? ($this->input->post('pageNum') - 1) *
$per_page : 0, $this->input->post('orderField') ? $this->input->post('orderField') : 'id',
$this->input->post('orderDirection') ? $this->input->post('orderDirection') : 'desc');
return $data;
}
public function __destruct(){
parent::__destruct();
}
}
/* End of file log_model.php */
/* Location: ./application/models/log_model.php */ | 1b14c68423743e5cc8419bca74e84f049b1957f7 | [
"JavaScript",
"Markdown",
"PHP"
]
| 21 | PHP | bairuiworld/homepage | bacd7e56e855cbdadcc568d5b7961481b3839925 | e8e9d45dac310462cf72ec9e3535ed2643ff2136 |
refs/heads/master | <repo_name>visualcamp/pre-commit-cpp<file_sep>/README.md
# pre-commit-cpp
연구개발팀 C++ 프로젝트 pre-commit hooks
<file_sep>/src/vcbin.js
const vl = require('./vclog.js');
const ve = require('./vcexec.js');
/*
* Cpp Lint
*/
function cpplint(cb, args='') {
let e = (err) => {
const errMsg = err.stderr || '';
if (errMsg.includes('No files were specified')) {
vl.warn('체크할 파일 정보가 필요합니다.');
} else {
vl.warn('failed to run cpplint. it may not installed.');
}
};
const cmd = 'cpplint' + args;
ve.exec(cb, cmd, null, e);
}
/*
* Cpp format
*/
function cppformat(cb, args='') {
function e(err) {
const errMsg = err.stderr || '';
if (errMsg.includes('No such file or directory')) {
vl.warn('지정한 파일이 없습니다. \n' + errMsg);
} else {
vl.warn(errMsg);
}
}
function s(obj) {
// vl.note(obj.stdout);
// TODO: 변경 사항이 있으면 다시 커밋하기 위해 커밋 실패로 처리되야 함
vl.note('*** complete cpp format ***');
}
const cmd = 'clang-format -style=Google -verbose=1 -i ' + args;
ve.exec(cb, cmd, s, e);
}
module.exports = {
cpplint : cpplint,
cppformat : cppformat
}
<file_sep>/bin/vc-cpp-lint
#!/usr/bin/env node
const util = require('util');
const program = require('commander');
const exec = require('child_process').exec;
function whenRunSuccess(obj) {
let ourmsg = '';
const stdout = obj.stdout || '';
const stderr = obj.stderr || '';
if (stderr.includes(`Skipping input`)) {
ourmsg += 'no file to check';
}
if (stderr !== '') {
console.log(stderr);
}
if (stdout !== '') {
console.log(stdout);
}
if (ourmsg !== '') {
console.log(ourmsg);
}
return 0;
}
function whenRunError(obj) {
let ourmsg = '';
const stderr = obj.stderr || '';
const stdout = obj.stdout || '';
if (stderr === '') {
ourmsg += 'Run cpplint is failed. Did you installed it?\n';
}
if (stderr.includes('No files were specified')) {
ourmsg = 'No files were specified\n';
}
if (stderr.includes('Syntax: cpplint.py')) {
ourmsg = 'cpplint got the wrong parameter.\n';
}
if (ourmsg !== '') {
console.log(ourmsg);
} else if (stderr !== '') {
console.log(stderr);
}
return 255;
}
function getCppLintFilter() {
let fs = '--filter=';
fs += `-legal/copyright`;
fs += `,-whitespace/ending_newline`;
return `${fs} `;
}
function getBaseCommand() {
let cli = `cpplint`;
cli += ` --linelength=120 `;
cli += getCppLintFilter();
return cli;
}
function setTargetFiles(cli) {
let argv = process.argv;
let fidx = argv.indexOf('-f');
for (let i=fidx+1; i<argv.length; i++) {
cli += ` ${argv[i]}`;
}
return cli;
}
function makeCommand() {
let cli = setTargetFiles(getBaseCommand());
if (program.verbose) {
console.log(cli);
}
return cli;
}
async function runCppLint() {
let cmd = '';
try {
cmd = makeCommand();
}
catch (e) {
console.log(`Cpp-Lint makeCommand() failed.\n==> ${e}`);
process.exit(255);
}
try {
const $exec = util.promisify(exec);
const v = await $exec(cmd)
.then(whenRunSuccess).catch(whenRunError);
process.exit(v);
}
catch (e) {
console.log(`Cpp-Lint execute failed.\n==> ${e}`);
process.exit(255);
}
};
//
// entry point
//
program
.option('-f, --filelist', 'filelist marker')
.option('-v, --verbose', 'verbose mode')
program.parse(process.argv);
runCppLint();
<file_sep>/bin/vc-clang-format
#!/usr/bin/env node
const util = require('util');
const program = require('commander');
const exec = require('child_process').exec;
function whenRunSuccess(obj) {
let ourmsg = '';
const stdout = obj.stdout || '';
const stderr = obj.stderr || '';
if (stderr !== '') {
console.log(`${stderr}`);
}
if (stdout !== '') {
console.log(`${stdout}`);
}
return 0; // console.log(JSON.stringify(obj));
}
function whenRunError(obj) {
let ourmsg = '';
const stderr = obj.stderr || '';
const stdout = obj.stdout || '';
if (stderr === '') {
ourmsg += 'Run clang-format failed. did you installed it?\n';
}
if (ourmsg !== '') {
log.warn(JSON.stringify(ourmsg));
} else if (stderr !== '') {
console.log(stderr);
}
return 255;
}
function collect(value, previous) {
return previous.concat([value]);
}
function getBaseCommand() {
let cli = `clang-format -style=Google -verbose=1`;
if (program.inplace) {
cli += ` -i`;
}
if (program.si) {
cli += ` -sort-includes`;
}
return cli;
}
function setTargetFiles(cli) {
let argv = process.argv;
let fidx = argv.indexOf('-f');
for (let i=fidx+1; i<argv.length; i++) {
cli += ` ${argv[i]}`;
}
return cli;
}
function makeCommand() {
let cli = setTargetFiles(getBaseCommand());
if (program.verbose) {
console.log(cli);
}
return cli;
}
async function runCppFormat() {
let cmd = '';
try {
cmd = makeCommand();
}
catch (e) {
console.log(`Clang-Format makeCommand() failed.\n==> ${e}`);
process.exit(255);
}
try {
const $exec = util.promisify(exec);
const v = await $exec(cmd)
.then(whenRunSuccess).catch(whenRunError);
process.exit(v);
}
catch (e) {
console.log(`Clang-Format execute failed.\n==> ${e}`);
process.exit(255);
}
};
//
// entry point
//
program
.option('-f, --filelist', 'filelist marker')
.option('-v, --verbose', 'verbose mode')
.option('-s, --si', 'sort include')
.option('-i, --inplace', 'inplace edit')
program.parse(process.argv);
runCppFormat();
<file_sep>/gulpfile.js
const gulp = require('gulp');
const pip = require('./src/vcpip.js');
const bin = require('./src/vcbin.js');
gulp.task('install-cpplint', (cb) => {
pip.install(cb, 'cpplint');
});
gulp.task('run-cpplint', (cb) => {
bin.cpplint(cb, '');
});
gulp.task('run-cppformat', (cb) => {
bin.cppformat(cb, '');
});
| bdbb2125f497c1a9a35759e8f18baa6abe30adf1 | [
"Markdown",
"JavaScript"
]
| 5 | Markdown | visualcamp/pre-commit-cpp | 783396cdc621de815538914270bd8359baf53a50 | e5bed9011368e4efe8417c022af4702740f6bb14 |
refs/heads/master | <file_sep>package entity;
public class Teacher {
private String id;
private String name;
private String age;
private String email;
private String telephone;
public Teacher(){
}
public Teacher(String id,String name,String age,String email,String telephone){
this.id=id;
this.name=name;
this.age=age;
this.email=email;
this.telephone=telephone;
}
@Override
public String toString() {
return "Teacher [id=" + id + ", name=" + name + ", age=" + age + ", email=" + email + ", telephone=" + telephone
+ "]";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTeelphone(String telephone) {
this.telephone = telephone;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
<file_sep>package service;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.management.RuntimeErrorException;
import com.mysql.fabric.xmlrpc.base.Data;
import dao.UserDao;
import entity.Teacher;
import entity.User;
/**
* 用户的业务(异常的传递)
* @author Administrator
*
*/
public class UserService {
/**
* 登录
*/
public boolean login(String username,String password) {
boolean bool=false;
UserDao dao=new UserDao();
User user=dao.query(username, password);
if(user!=null) {
bool=true;
}
return bool;
}
/**
* 查看所有人信息
*/
public List<User> queryList() {
UserDao dao =new UserDao();
List<User> user=dao.queryList();
System.out.println(user);
return user;
}
/**
*查看教师信息
*/
public List<Teacher> queryList1(){
UserDao dao =new UserDao();
List<Teacher> teacher1=dao.queryList1();
return teacher1;
}
/*
* 注册信息
*/
public void Regester(User u){
UserDao dao =new UserDao();
System.out.println(u);
dao.Regester(u);
}
}
<file_sep>package view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
public class LoginJFrame<QureyJframe1> extends JFrame {
private JPanel contentPane;
private String loginUser1;
static String loginUser;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoginJFrame frame = new LoginJFrame(loginUser);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LoginJFrame(String loginUser) {
this.loginUser=loginUser;
setTitle("欢迎"+loginUser+"来到教务系统");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 733, 579);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("系统管理");
menuBar.add(menu);
JMenuItem mntmNewMenuItem = new JMenuItem("用户切换\r\n");
menu.add(mntmNewMenuItem);
JMenuItem menuItem = new JMenuItem("注册\r\n");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ResigerJFrame frame = new ResigerJFrame();
frame.setVisible(true);
}
});
menu.add(menuItem);
JMenu mnJiao = new JMenu("教务管理");
menuBar.add(mnJiao);
JMenuItem menuItem_4 = new JMenuItem("\u4E2A\u4EBA\u8BFE\u8868");
mnJiao.add(menuItem_4);
JMenuItem menuItem_3 = new JMenuItem("\u73ED\u7EA7\u8BFE\u8868");
mnJiao.add(menuItem_3);
JMenu menu_1 = new JMenu("教师管理");
menuBar.add(menu_1);
JMenuItem menuItem_2 = new JMenuItem("教师查询");
menuItem_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
QuJFrame frame = new QuJFrame();
frame.setVisible(true);
}
});
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
menu_1.add(menuItem_2);
JMenuBar menuBar_1 = new JMenuBar();
menu_1.add(menuBar_1);
JMenu menu_2 = new JMenu("学生管理");
menuBar.add(menu_2);
JMenuItem menuItem_1 = new JMenuItem("学生查询");
menuItem_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
QureyJFrame frame = new QureyJFrame();
frame.setVisible(true);
}
});
menu_2.add(menuItem_1);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setIcon(new ImageIcon("D:\\Documents\\Pictures\\\u9B54\u9053\u7956\u5E08\\f1555094565138.jpeg"));
lblNewLabel.setBounds(0, -26, 728, 538);
contentPane.add(lblNewLabel);
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}<file_sep>package view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import org.omg.Messaging.SyncScopeHelper;
import entity.User;
import service.UserService;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JCheckBox;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
public class ResigerJFrame extends JFrame {
private JPanel contentPane;
private JTextField textField_1;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ResigerJFrame frame = new ResigerJFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ResigerJFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 608, 535);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField_1 = new JTextField();
textField_1.setBounds(110, 56, 140, 24);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(387, 56, 147, 24);
contentPane.add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(111, 107, 139, 24);
contentPane.add(textField_4);
textField_4.setColumns(10);
textField_5 = new JTextField();
textField_5.setBounds(387, 107, 147, 24);
contentPane.add(textField_5);
textField_5.setColumns(10);
String[] jg={"北京","上海","天津","新疆","广州"};
JComboBox comboBox = new JComboBox(jg);
comboBox.setBounds(387, 189, 147, 24);
contentPane.add(comboBox);
JLabel lblNewLabel = new JLabel("\u59D3\u540D\uFF1A");
lblNewLabel.setBounds(51, 59, 45, 18);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("\u5BC6\u7801\uFF1A");
lblNewLabel_1.setBounds(328, 51, 45, 35);
contentPane.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("\u90AE\u7BB1\uFF1A");
lblNewLabel_2.setBounds(51, 110, 45, 18);
contentPane.add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel("\u7535\u8BDD\uFF1A");
lblNewLabel_3.setBounds(328, 110, 45, 18);
contentPane.add(lblNewLabel_3);
JLabel lblNewLabel_4 = new JLabel("\u7C4D\u8D2F\uFF1A");
lblNewLabel_4.setBounds(328, 192, 52, 18);
contentPane.add(lblNewLabel_4);
JLabel lblNewLabel_5 = new JLabel("\u6027\u522B\uFF1A");
lblNewLabel_5.setBounds(51, 192, 52, 18);
contentPane.add(lblNewLabel_5);
JRadioButton rdbtnNewRadioButton = new JRadioButton("\u7537");
rdbtnNewRadioButton.setBounds(112, 188, 59, 27);
contentPane.add(rdbtnNewRadioButton);
JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("\u5973");
rdbtnNewRadioButton_1.setBounds(177, 188, 73, 27);
contentPane.add(rdbtnNewRadioButton_1);
ButtonGroup bg=new ButtonGroup();
bg.add(rdbtnNewRadioButton);
bg.add(rdbtnNewRadioButton_1);
JLabel lblNewLabel_6 = new JLabel("\u5174\u8DA3");
lblNewLabel_6.setBounds(51, 284, 45, 18);
contentPane.add(lblNewLabel_6);
JCheckBox chckbxNewCheckBox = new JCheckBox("\u6E38\u6CF3");
chckbxNewCheckBox.setBounds(110, 280, 73, 27);
contentPane.add(chckbxNewCheckBox);
JCheckBox chckbxNewCheckBox_1 = new JCheckBox("\u8DF3\u821E");
chckbxNewCheckBox_1.setBounds(204, 280, 78, 27);
contentPane.add(chckbxNewCheckBox_1);
JLabel label = new JLabel("\u5907\u6CE8\uFF1A");
label.setBounds(51, 366, 52, 18);
contentPane.add(label);
textField = new JTextField();
textField.setBounds(127, 363, 407, 64);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("注册");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
User user=new User();
user.setId(String.valueOf(System.currentTimeMillis()));
user.setUsername(textField_1.getText());
user.setPassword(<PASSWORD>_3.getText());
user.setEmail(textField_4.getText());
UserService service =new UserService();
try{
service.Regester(user);
JOptionPane.showMessageDialog(ResigerJFrame.this, "注册成功");
}catch(Exception e1){
JOptionPane.showMessageDialog(ResigerJFrame.this, "注册失败");
}
}
});
btnNewButton.setBounds(112, 452, 113, 27);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("\u91CD\u7F6E");
btnNewButton_1.setBounds(344, 452, 113, 27);
contentPane.add(btnNewButton_1);
JLabel lblNewLabel_7 = new JLabel("New label");
lblNewLabel_7.setIcon(new ImageIcon("D:\\Documents\\Pictures\\\u9B54\u9053\u7956\u5E08\\\u9B54\u9053\u7956\u5E08wv_1540299834375.jpg"));
lblNewLabel_7.setBounds(0, 0, 592, 492);
contentPane.add(lblNewLabel_7);
}
}
<file_sep>package view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import entity.Teacher;
import entity.User;
import service.UserService;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.event.ActionListener;
import java.util.List;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
public class QuJFrame extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTable table;
String [] names={"编号","用户名","年龄","电话","邮箱"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
QuJFrame frame = new QuJFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public QuJFrame() {
setDefaultCloseOperation(QuJFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 724, 540);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("搜索");
btnNewButton.setBounds(581, 26, 113, 27);
contentPane.add(btnNewButton);
JButton button = new JButton("刷新");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UserService userServiceImpl=new UserService();
List<Teacher> teachers=userServiceImpl.queryList1();
//System.out.println(teachers);
System.out.println("-------");
System.out.println(teachers);
//把list变成二维数组
String[][] rows=new String[teachers.size()][5];
for(int i=0;i<teachers.size();i++){
Teacher t=teachers.get(i);
rows[i][0]=t.getId();
rows[i][1]=t.getName();
rows[i][2]=t.getAge();
rows[i][3]=t.getEmail();
rows[i][4]=t.getTelephone();
}
TableModel model=new DefaultTableModel(rows,names);
table.setModel(model);
table.updateUI();
}
});
button.setBounds(581, 457, 113, 27);
contentPane.add(button);
textField = new JTextField();
textField.setBounds(58, 27, 86, 24);
contentPane.add(textField);
textField.setColumns(10);
JLabel label = new JLabel("\u59D3\u540D");
label.setBounds(14, 30, 72, 18);
contentPane.add(label);
JLabel label_1 = new JLabel("\u5E74\u9F84");
label_1.setBounds(204, 30, 72, 18);
contentPane.add(label_1);
textField_1 = new JTextField();
textField_1.setBounds(246, 27, 86, 24);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblId = new JLabel("ID");
lblId.setBounds(397, 30, 72, 18);
contentPane.add(lblId);
textField_2 = new JTextField();
textField_2.setBounds(421, 27, 86, 24);
contentPane.add(textField_2);
textField_2.setColumns(10);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(14, 137, 680, 307);
contentPane.add(scrollPane);
String [][] xx=new String [20][5];
table = new JTable(xx,names);
scrollPane.setViewportView(table);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setIcon(new ImageIcon("D:\\Documents\\Pictures\\\u9B54\u9053\u7956\u5E08\\f1555094565138.jpeg"));
lblNewLabel.setBounds(0, 0, 708, 497);
contentPane.add(lblNewLabel);
}
}
<file_sep>package view;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import entity.User;
import service.UserService;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.ImageIcon;
public class QureyJFrame extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTable table_1;
String [] usernames={"编号","用户名","密码","邮箱"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
QureyJFrame frame = new QureyJFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame
*/
public QureyJFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 492);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(5, 5, 796, 1);
contentPane.add(panel);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new TitledBorder(null, "\u6570\u636E\u67E5\u8BE2", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel_1.setBounds(28, 32, 703, 194);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("id_card");
lblNewLabel_1.setBounds(27, 23, 90, 29);
panel_1.add(lblNewLabel_1);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setBounds(390, 34, 0, 0);
panel_1.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(92, 25, 130, 24);
panel_1.add(textField);
textField.setColumns(10);
JLabel lblUsername = new JLabel("username");
lblUsername.setBounds(330, 26, 72, 18);
panel_1.add(lblUsername);
textField_1 = new JTextField();
textField_1.setBounds(399, 22, 143, 24);
panel_1.add(textField_1);
textField_1.setColumns(10);
JLabel lblPassword = new JLabel("<PASSWORD>");
lblPassword.setBounds(26, 110, 72, 18);
panel_1.add(lblPassword);
textField_2 = new JTextField();
textField_2.setBounds(92, 106, 134, 24);
panel_1.add(textField_2);
textField_2.setColumns(10);
JLabel lblEmail = new JLabel(" email");
lblEmail.setBounds(330, 110, 72, 18);
panel_1.add(lblEmail);
JButton button = new JButton("查询");
button.setBounds(569, 17, 113, 27);
panel_1.add(button);
JButton btnNewButton = new JButton("刷新");
btnNewButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
UserService userServiceImpl=new UserService();
List<User> users=userServiceImpl.queryList();
//把list变成二维数组
String[][] rows=new String[users.size()][4];
for(int i=0;i<users.size();i++){
User u=users.get(i);
rows[i][0]=u.getId();
rows[i][1]=u.getUsername();
rows[i][2]=u.getPassword();
rows[i][3]=u.getEmail();
}
TableModel model=new DefaultTableModel(rows,usernames);
table_1.setModel(model);
table_1.updateUI();
}
});
btnNewButton.setBounds(569, 101, 113, 27);
panel_1.add(btnNewButton);
textField_3 = new JTextField();
textField_3.setBounds(399, 107, 143, 24);
panel_1.add(textField_3);
textField_3.setColumns(10);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(28, 253, 703, 183);
contentPane.add(scrollPane);
String [][] xx=new String [20][4];
table_1 = new JTable(xx,usernames);
scrollPane.setViewportView(table_1);
JLabel lblNewLabel_2 = new JLabel("New label");
lblNewLabel_2.setIcon(new ImageIcon("D:\\Documents\\Pictures\\\u9B54\u9053\u7956\u5E08\\f1555094565138.jpeg"));
lblNewLabel_2.setBounds(5, 5, 816, 448);
contentPane.add(lblNewLabel_2);
}
}
<file_sep>package view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import service.UserService;
public class MainJFrame extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainJFrame frame = new MainJFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainJFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 581, 487);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(194, 385, 218, 24);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(194, 303, 218, 24);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton btnNewButton = new JButton("\u767B\u5F55");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String username=textField_1.getText();
String password=textField.getText();
//常量写在前,避免NPE(空指针)问题
UserService u1=new UserService();
Boolean boolean1=false;
try {
boolean1=u1.login(username, password);
} catch (Exception e) {
JOptionPane.showMessageDialog(MainJFrame.this,e.getMessage());
}
if(boolean1) {
LoginJFrame frame = new LoginJFrame(username);
frame.setVisible(true);
//匿名类
MainJFrame.this.disable();
}else {
JOptionPane.showMessageDialog(MainJFrame.this, "登陆失败");
//System.out.println("登陆失败");
}
}
});
btnNewButton.setBounds(471, 302, 66, 27);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("\u6CE8\u518C");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ResigerJFrame frame=new ResigerJFrame();
frame.setVisible(true);
}
});
btnNewButton_1.setBounds(471, 384, 66, 27);
contentPane.add(btnNewButton_1);
textField_2 = new JTextField();
textField_2.setText("\u7528\u6237\u540D");
textField_2.setBounds(60, 303, 74, 24);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setText("\u5BC6\u7801");
textField_3.setBounds(60, 385, 74, 24);
contentPane.add(textField_3);
textField_3.setColumns(10);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setIcon(new ImageIcon("D:\\Documents\\Pictures\\\u9B54\u9053\u7956\u5E08\\\u9B54\u9053\u7956\u5E08wv_1540299834375.jpg"));
lblNewLabel.setBounds(0, 0, 565, 444);
contentPane.add(lblNewLabel);
}
}
<file_sep>package dao;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import entity.Teacher;
import entity.User;
import util.DBUtil;
public class UserDao {
/**
*
* 根据用用户名密码查询登录
* @return
*/
public User query(String username,String password) {
User user=null;
String sql="select * from user where username=? and password=?";
List<Map<String, Object>> list=DBUtil.query(sql,username,password);
if(list.size()>0) {
user=new User();
Map<String, Object> map=list.get(0);
user.setId(map.get("id")==null?null:map.get("id").toString());
user.setUsername(map.get("username")==null?null:map.get("username").toString());
user.setPassword(map.get("password")==null?null:map.get("password").toString());
user.setEmail(map.get("email")==null?null:map.get("email").toString());
}
DBUtil.close();
return user;
}
/**
* 查询所有信息
*/
public List<User> queryList(){
List<User> list =new ArrayList<User>();
String sql="select * from user";
List<Map<String, Object>> data =DBUtil.query(sql);
for(Map<String,Object>map:data){
User user=new User();
user.setId(map.get("id")==null?null:map.get("id").toString());
user.setUsername(map.get("username")==null?null:map.get("username").toString());
user.setPassword(map.get("password")==null?null:map.get("password").toString());
user.setEmail(map.get("email")==null?null:map.get("email").toString());
list.add(user);
}
DBUtil.close();
return list;
}
/**
* 查询教师的信息
*/
public List<Teacher> queryList1(){
List<Teacher> list =new ArrayList<Teacher>();
String sql="select * from teacher";
List<Map<String, Object>> data =DBUtil.query(sql);
for(Map<String,Object>map:data){
Teacher teacher=new Teacher();
teacher.setId(map.get("id")==null?null:map.get("id").toString());
teacher.setName(map.get("name")==null?null:map.get("name").toString());
teacher.setAge(map.get("age")==null?null:map.get("age").toString());
teacher.setEmail(map.get("email")==null?null:map.get("email").toString());
teacher.setTeelphone(map.get("telphone")==null?null:map.get("telphone").toString());
list.add(teacher);
}
DBUtil.close();
System.out.println(list);
return list;
}
/**
* 注册信息
*/
public void Regester(User user){
String sql="insert into user(id,username,password,email) values(?,?,?,?)";
DBUtil.update(sql, user.getId(),user.getUsername(),user.getPassword(),user.getEmail());
DBUtil.close();
//return row;
}
}
| 3a27bc2197cf323fcb5a4a3e84c36e770731172f | [
"Java"
]
| 8 | Java | weini-l/learning-code | b351ba418f01e1cbbe0ea1acff50ceb96867f9b5 | 66960a9ec4ee83cb36052dfc14713d50907c2e7c |
refs/heads/master | <repo_name>jessfeld/hnn-core<file_sep>/README.rst
hnn-core
========
.. image:: https://badges.gitter.im/hnn-core/hnn-core.svg
:target: https://gitter.im/hnn-core/hnn-core?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
:alt: Gitter
.. image:: https://api.travis-ci.org/jonescompneurolab/hnn-core.svg?branch=master
:target: https://travis-ci.org/jonescompneurolab/hnn-core
:alt: Build Status
.. image:: https://codecov.io/gh/jonescompneurolab/hnn-core/branch/master/graph/badge.svg
:target: https://codecov.io/gh/jonescompneurolab/hnn-core
:alt: Test coverage
This is a leaner and cleaner version of the code based off the `HNN repository <https://github.com/jonescompneurolab/hnn>`_. However, a Graphical User Interface is not supported at the moment in this repository.
It is early Work in Progress. Contributors are very welcome.
Dependencies
------------
* Neuron: installation instructions here: https://neuron.yale.edu/neuron/
* scipy
* numpy
* matplotlib
* joblib (optional for parallel processing)
Installation
============
We recommend the `Anaconda Python distribution <https://www.continuum.io/downloads>`_. To install ``hnn-core``, you first need to install its dependencies::
$ conda install numpy matplotlib scipy
For joblib, you can do::
$ pip install joblib
Additionally, you would need Neuron which is available here: `https://neuron.yale.edu/neuron/ <https://neuron.yale.edu/neuron/>`_
Since ``hnn-core`` does not yet have a stable release, we recommend installing the nightly version. This may change in the future if more users start using it.
To install the latest version of the code (nightly) do::
$ git clone https://github.com/jonescompneurolab/hnn-core.git
$ cd hnn-core/
$ python setup.py develop
A final step to the installation process is to compile custom ionic channel
mechanisms using `nrnivmodl` from Neuron. To do this, simple do::
$ cd mod/ && nrnivmodl
inside the ``hnn-core`` directory. It should create the compiled custom mechanism files.
To check if everything worked fine, you can do::
$ python -c 'import hnn_core'
and it should not give any error messages.
Bug reports
===========
Use the `github issue tracker <https://github.com/jonescompneurolab/hnn-core/issues>`_ to report bugs.
<file_sep>/hnn_core/feed.py
"""External feed to network."""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import numpy as np
from neuron import h
class ExtFeed(object):
""""The ExtFeed class.
Parameters
----------
ty : str
The feed type. Can be:
'extpois', 'evprox', 'evdist', 'extgauss', 'extinput'
celltype : str | None
The cell type.
p_ext : dict | list (XXX: check)
Parameters of external input.
p_ext has a different structure for the extinput
usually, p_ext is a dict of cell types
gid : int
The cell ID.
Attributes
----------
seed : int
The seed
gid : int
The cell ID
"""
def __init__(self, ty, celltype, p_ext, gid):
# VecStim setup
self.eventvec = h.Vector()
self.vs = h.VecStim()
# self.p_unique = p_unique[type]
self.p_ext = p_ext
self.celltype = celltype
self.ty = ty # feed type
self.gid = gid
self.set_prng() # sets seeds for random num generator
# sets event times into self.eventvec and plays into self.vs (VecStim)
self.set_event_times()
def __repr__(self):
class_name = self.__class__.__name__
s = 'seed %d, gid %d' % (self.seed, self.gid)
return '<%s | %s>' % (class_name, s)
def set_prng(self, seed=None):
if seed is None: # no seed specified then use p_ext to determine seed
# random generator for this instance
# qnd hack to make the seeds the same across all gids
# for just evoked
if self.ty.startswith(('evprox', 'evdist')):
if self.p_ext['sync_evinput']:
self.seed = self.p_ext['prng_seedcore']
else:
self.seed = self.p_ext['prng_seedcore'] + self.gid - 2
elif self.ty.startswith('extinput'):
# seed for events assuming a given start time
self.seed = self.p_ext['prng_seedcore'] + self.gid
# separate seed for start times
self.seed2 = self.p_ext['prng_seedcore']
else:
self.seed = self.p_ext['prng_seedcore'] + self.gid
else: # if seed explicitly specified use it
self.seed = seed
if hasattr(self, 'seed2'):
self.seed2 = seed
self.prng = np.random.RandomState(self.seed)
if hasattr(self, 'seed2'):
self.prng2 = np.random.RandomState(self.seed2)
# print('ty,seed:',self.ty,self.seed)
def set_event_times(self, inc_evinput=0.0):
# print('self.p_ext:',self.p_ext)
# each of these methods creates self.eventvec for playback
if self.ty == 'extpois':
self.__create_extpois()
elif self.ty.startswith(('evprox', 'evdist')):
self.__create_evoked(inc_evinput)
elif self.ty == 'extgauss':
self.__create_extgauss()
elif self.ty == 'extinput':
self.__create_extinput()
# load eventvec into VecStim object
self.vs.play(self.eventvec)
# based on cdf for exp wait time distribution from unif [0, 1)
# returns in ms based on lamtha in Hz
def __t_wait(self, lamtha):
return -1000. * np.log(1. - self.prng.rand()) / lamtha
# new external pois designation
def __create_extpois(self):
# print("__create_extpois")
if self.p_ext[self.celltype][0] <= 0.0 and \
self.p_ext[self.celltype][1] <= 0.0:
return False # 0 ampa and 0 nmda weight
# check the t interval
t0 = self.p_ext['t_interval'][0]
T = self.p_ext['t_interval'][1]
lamtha = self.p_ext[self.celltype][3] # index 3 is frequency (lamtha)
# values MUST be sorted for VecStim()!
# start the initial value
if lamtha > 0.:
t_gen = t0 + self.__t_wait(lamtha)
val_pois = np.array([])
if t_gen < T:
np.append(val_pois, t_gen)
# vals are guaranteed to be monotonically increasing, no need to
# sort
while t_gen < T:
# so as to not clobber confusingly base off of t_gen ...
t_gen += self.__t_wait(lamtha)
if t_gen < T:
val_pois = np.append(val_pois, t_gen)
else:
val_pois = np.array([])
# checks the distribution stats
# if len(val_pois):
# xdiff = np.diff(val_pois/1000)
# print(lamtha, np.mean(xdiff), np.var(xdiff), 1/lamtha**2)
# Convert array into nrn vector
# if len(val_pois)>0: print('val_pois:',val_pois)
self.eventvec.from_python(val_pois)
return self.eventvec.size() > 0
# mu and sigma vals come from p
def __create_evoked(self, inc=0.0):
if self.celltype in self.p_ext.keys():
# assign the params
mu = self.p_ext['t0'] + inc
sigma = self.p_ext[self.celltype][3] # index 3 is sigma_t_ (stdev)
numspikes = int(self.p_ext['numspikes'])
# print('mu:',mu,'sigma:',sigma,'inc:',inc)
# if a non-zero sigma is specified
if sigma:
val_evoked = self.prng.normal(mu, sigma, numspikes)
else:
# if sigma is specified at 0
val_evoked = np.array([mu] * numspikes)
val_evoked = val_evoked[val_evoked > 0]
# vals must be sorted
val_evoked.sort()
# print('__create_evoked val_evoked:',val_evoked)
self.eventvec.from_python(val_evoked)
else:
# return an empty eventvec list
self.eventvec.from_python([])
return self.eventvec.size() > 0
def __create_extgauss(self):
# assign the params
if self.p_ext[self.celltype][0] <= 0.0 and \
self.p_ext[self.celltype][1] <= 0.0:
return False # 0 ampa and 0 nmda weight
# print('gauss params:',self.p_ext[self.celltype])
mu = self.p_ext[self.celltype][3]
sigma = self.p_ext[self.celltype][4]
# mu and sigma values come from p
# one single value from Gaussian dist.
# values MUST be sorted for VecStim()!
val_gauss = self.prng.normal(mu, sigma, 50)
# val_gauss = np.random.normal(mu, sigma, 50)
# remove non-zero values brute force-ly
val_gauss = val_gauss[val_gauss > 0]
# sort values - critical for nrn
val_gauss.sort()
# if len(val_gauss)>0: print('val_gauss:',val_gauss)
# Convert array into nrn vector
self.eventvec.from_python(val_gauss)
return self.eventvec.size() > 0
def __create_extinput(self):
"""Creates the ongoing external inputs (rhythmic)."""
# print("__create_extinput")
# Return if all synaptic weights are 0
all_syn_weights_zero = True
for key in self.p_ext.keys():
if key.startswith('L2Pyr') or \
key.startswith('L5Pyr') or \
key.startswith('L2Bask') or \
key.startswith('L5Bask'):
if self.p_ext[key][0] > 0.0:
all_syn_weights_zero = False
if all_syn_weights_zero:
return False
# store f_input as self variable for later use if it exists in p
# t0 is always defined
t0 = self.p_ext['t0']
# If t0 is -1, randomize start time of inputs
if t0 == -1:
t0 = self.prng.uniform(25., 125.)
# randomize start time based on t0_stdev
elif self.p_ext['t0_stdev'] > 0.0:
# start time uses different prng
t0 = self.prng2.normal(t0, self.p_ext['t0_stdev'])
f_input = self.p_ext['f_input']
stdev = self.p_ext['stdev']
events_per_cycle = self.p_ext['events_per_cycle']
distribution = self.p_ext['distribution']
# events_per_cycle = 1
if events_per_cycle > 2 or events_per_cycle <= 0:
print("events_per_cycle should be either 1 or 2, trying 2")
events_per_cycle = 2
# If frequency is 0, create empty vector if input times
if not f_input:
t_input = []
elif distribution == 'normal':
# array of mean stimulus times, starts at t0
isi_array = np.arange(t0, self.p_ext['tstop'], 1000. / f_input)
# array of single stimulus times -- no doublets
if stdev:
t_array = self.prng.normal(
np.repeat(isi_array, self.p_ext['repeats']), stdev)
else:
t_array = isi_array
if events_per_cycle == 2: # spikes/burst in GUI
# Two arrays store doublet times
t_array_low = t_array - 5
t_array_high = t_array + 5
# Array with ALL stimulus times for input
# np.append concatenates two np arrays
t_input = np.append(t_array_low, t_array_high)
elif events_per_cycle == 1:
t_input = t_array
# brute force remove zero times. Might result in fewer vals than
# desired
t_input = t_input[t_input > 0]
t_input.sort()
# Uniform Distribution
elif distribution == 'uniform':
n_inputs = self.p_ext['repeats'] * \
f_input * (self.p_ext['tstop'] - t0) / 1000.
t_array = self.prng.uniform(t0, self.p_ext['tstop'], n_inputs)
if events_per_cycle == 2:
# Two arrays store doublet times
t_input_low = t_array - 5
t_input_high = t_array + 5
# Array with ALL stimulus times for input
# np.append concatenates two np arrays
t_input = np.append(t_input_low, t_input_high)
elif events_per_cycle == 1:
t_input = t_array
# brute force remove non-zero times. Might result in fewer vals
# than desired
t_input = t_input[t_input > 0]
t_input.sort()
else:
print("Indicated distribution not recognized. "
"Not making any alpha feeds.")
t_input = []
# Convert array into nrn vector
self.eventvec.from_python(t_input)
return self.eventvec.size() > 0
# for parallel, maybe be that postsyn for this is just nil (None)
def connect_to_target(self, threshold):
# print("connect_to_target")
nc = h.NetCon(self.vs, None) # why is target always nil??
nc.threshold = threshold
return nc
<file_sep>/hnn_core/network.py
"""Network class."""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import itertools as it
import numpy as np
from neuron import h
from .feed import ExtFeed
from .pyramidal import L2Pyr, L5Pyr
from .basket import L2Basket, L5Basket
from .params import create_pext
class Network(object):
"""The Network class.
Parameters
----------
params : dict
The parameters
n_jobs : int
The number of jobs to run in parallel
Attributes
----------
cells : list of Cell objects.
The list of cells
gid_dict : dict
Dictionary with keys 'evprox1', 'evdist1' etc.
containing the range of Cell IDs of different cell types.
ext_list : dictionary of list of ExtFeed.
Keys are:
'evprox1', 'evprox2', etc.
'evdist1', etc.
'extgauss', 'extpois'
spiketimes : tuple (n_trials, ) of list of float
Each element of the tuple is a trial.
The list contains the time stamps of spikes.
spikegids : tuple (n_trials, ) of list of float
Each element of the tuple is a trial.
The list contains the cell IDs of neurons that spiked.
"""
def __init__(self, params, n_jobs=1):
from .parallel import create_parallel_context
# setup simulation (ParallelContext)
create_parallel_context(n_jobs=n_jobs)
# set the params internally for this net
# better than passing it around like ...
self.params = params
# Number of time points
# Originally used to create the empty vec for synaptic currents,
# ensuring that they exist on this node irrespective of whether
# or not cells of relevant type actually do
self.N_t = np.arange(0., self.params['tstop'],
self.params['dt']).size + 1
# Create a h.Vector() with size 1xself.N_t, zero'd
self.current = {
'L5Pyr_soma': h.Vector(self.N_t, 0),
'L2Pyr_soma': h.Vector(self.N_t, 0),
}
# int variables for grid of pyramidal cells (for now in both L2 and L5)
self.gridpyr = {
'x': self.params['N_pyr_x'],
'y': self.params['N_pyr_y'],
}
self.N_src = 0
self.N = {} # numbers of sources
self.N_cells = 0 # init self.N_cells
# zdiff is expressed as a positive DEPTH of L5 relative to L2
# this is a deviation from the original, where L5 was defined at 0
# this should not change interlaminar weight/delay calculations
self.zdiff = 1307.4
# params of external inputs in p_ext
# Global number of external inputs ... automatic counting
# makes more sense
# p_unique represent ext inputs that are going to go to each cell
self.p_ext, self.p_unique = create_pext(self.params,
self.params['tstop'])
self.N_extinput = len(self.p_ext)
# Source list of names
# in particular order (cells, extinput, alpha names of unique inputs)
self.src_list_new = self._create_src_list()
# cell position lists, also will give counts: must be known
# by ALL nodes
# extinput positions are all located at origin.
# sort of a hack bc of redundancy
self.pos_dict = dict.fromkeys(self.src_list_new)
# create coords in pos_dict for all cells first
self._create_coords_pyr()
self._create_coords_basket()
self._count_cells()
# create coords for all other sources
self._create_coords_extinput()
# count external sources
self._count_extsrcs()
# create dictionary of GIDs according to cell type
# global dictionary of gid and cell type
self.gid_dict = {}
self._create_gid_dict()
# assign gid to hosts, creates list of gids for this node in _gid_list
# _gid_list length is number of cells assigned to this id()
self._gid_list = []
self._gid_assign()
# create cells (and create self.origin in create_cells_pyr())
self.cells = []
self.extinput_list = []
# external unique input list dictionary
self.ext_list = dict.fromkeys(self.p_unique)
# initialize the lists in the dict
for key in self.ext_list.keys():
self.ext_list[key] = []
def __repr__(self):
class_name = self.__class__.__name__
s = ("%d x %d Pyramidal cells (L2, L5)"
% (self.gridpyr['x'], self.gridpyr['y']))
s += ("\n%d L2 basket cells\n%d L5 basket cells"
% (self.N['L2_basket'], self.N['L5_basket']))
return '<%s | %s>' % (class_name, s)
def build(self):
"""Building the network in NEURON."""
print('Building the NEURON model')
from neuron import h
self._create_all_src()
self.state_init()
self._parnet_connect()
# set to record spikes
self.spiketimes = h.Vector()
self.spikegids = h.Vector()
self._record_spikes()
self.move_cells_to_pos() # position cells in 2D grid
print('[Done]')
def __enter__(self):
"""Context manager to cleanly build Network objects"""
return self
def __exit__(self, type, value, traceback):
"""Clear up NEURON internal gid information.
Notes
-----
This function must be called from the context of the
Network instance that ran __enter__(). This is a bug or
peculiarity of NEURON. If this function is called from a different
context, then the next simulation will run very slow because nrniv
workers are still going for the old simulation. If pc.gid_clear() is
called from the right context, then those workers can exit.
"""
from .parallel import pc
pc.gid_clear()
# creates the immutable source list along with corresponding numbers
# of cells
def _create_src_list(self):
# base source list of tuples, name and number, in this order
self.cellname_list = [
'L2_basket',
'L2_pyramidal',
'L5_basket',
'L5_pyramidal',
]
# add the legacy extinput here
self.extname_list = []
self.extname_list.append('extinput')
# grab the keys for the unique set of inputs and sort the names
# append them to the src list along with the number of cells
unique_keys = sorted(self.p_unique.keys())
self.extname_list += unique_keys
# return one final source list
src_list = self.cellname_list + self.extname_list
return src_list
# Creates cells and grid
def _create_coords_pyr(self):
""" pyr grid is the immutable grid, origin now calculated in relation to feed
"""
xrange = np.arange(self.gridpyr['x'])
yrange = np.arange(self.gridpyr['y'])
# create list of tuples/coords, (x, y, z)
self.pos_dict['L2_pyramidal'] = [
pos for pos in it.product(xrange, yrange, [0])]
self.pos_dict['L5_pyramidal'] = [
pos for pos in it.product(xrange, yrange, [self.zdiff])]
def _create_coords_basket(self):
"""Create basket cell coords based on pyr grid."""
# define relevant x spacings for basket cells
xzero = np.arange(0, self.gridpyr['x'], 3)
xone = np.arange(1, self.gridpyr['x'], 3)
# split even and odd y vals
yeven = np.arange(0, self.gridpyr['y'], 2)
yodd = np.arange(1, self.gridpyr['y'], 2)
# create general list of x,y coords and sort it
coords = [pos for pos in it.product(
xzero, yeven)] + [pos for pos in it.product(xone, yodd)]
coords_sorted = sorted(coords, key=lambda pos: pos[1])
# append the z value for position for L2 and L5
# print(len(coords_sorted))
self.pos_dict['L2_basket'] = [pos_xy + (0,) for
pos_xy in coords_sorted]
self.pos_dict['L5_basket'] = [
pos_xy + (self.zdiff,) for pos_xy in coords_sorted]
# creates origin AND creates external input coords
def _create_coords_extinput(self):
""" (same thing for now but won't fix because could change)
"""
xrange = np.arange(self.gridpyr['x'])
yrange = np.arange(self.gridpyr['y'])
# origin's z component isn't really used in
# calculating distance functions from origin
# these will be forced as ints!
origin_x = xrange[int((len(xrange) - 1) // 2)]
origin_y = yrange[int((len(yrange) - 1) // 2)]
origin_z = np.floor(self.zdiff / 2)
self.origin = (origin_x, origin_y, origin_z)
self.pos_dict['extinput'] = [self.origin for i in
range(self.N_extinput)]
# at this time, each of the unique inputs is per cell
for key in self.p_unique.keys():
# create the pos_dict for all the sources
self.pos_dict[key] = [self.origin for i in range(self.N_cells)]
def _count_cells(self):
"""Cell counting routine."""
# cellname list is used *only* for this purpose for now
for src in self.cellname_list:
# if it's a cell, then add the number to total number of cells
self.N[src] = len(self.pos_dict[src])
self.N_cells += self.N[src]
# general counting method requires pos_dict is correct for each source
# and that all sources are represented
def _count_extsrcs(self):
# all src numbers are based off of length of pos_dict entry
# generally done here in lieu of upstream changes
for src in self.extname_list:
self.N[src] = len(self.pos_dict[src])
def _create_gid_dict(self):
"""Creates gid dicts and pos_lists."""
# initialize gid index gid_ind to start at 0
gid_ind = [0]
# append a new gid_ind based on previous and next cell count
# order is guaranteed by self.src_list_new
for i in range(len(self.src_list_new)):
# N = self.src_list_new[i][1]
# grab the src name in ordered list src_list_new
src = self.src_list_new[i]
# query the N dict for that number and append here
# to gid_ind, based on previous entry
gid_ind.append(gid_ind[i] + self.N[src])
# accumulate total source count
self.N_src += self.N[src]
# now actually assign the ranges
for i in range(len(self.src_list_new)):
src = self.src_list_new[i]
self.gid_dict[src] = range(gid_ind[i], gid_ind[i + 1])
# this happens on EACH node
# creates self._gid_list for THIS node
def _gid_assign(self):
from .parallel import nhosts, rank, pc
# round robin assignment of gids
for gid in range(rank, self.N_cells, nhosts):
# set the cell gid
pc.set_gid2node(gid, rank)
self._gid_list.append(gid)
# now to do the cell-specific external input gids on the same proc
# these are guaranteed to exist because all of
# these inputs were created for each cell
for key in self.p_unique.keys():
gid_input = gid + self.gid_dict[key][0]
pc.set_gid2node(gid_input, rank)
self._gid_list.append(gid_input)
# legacy handling of the external inputs
# NOT perfectly balanced for now
for gid_base in range(rank, self.N_extinput, nhosts):
# shift the gid_base to the extinput gid
gid = gid_base + self.gid_dict['extinput'][0]
# set as usual
pc.set_gid2node(gid, rank)
self._gid_list.append(gid)
# extremely important to get the gids in the right order
self._gid_list.sort()
def gid_to_type(self, gid):
"""Reverse lookup of gid to type."""
for gidtype, gids in self.gid_dict.items():
if gid in gids:
return gidtype
def _create_all_src(self):
"""Parallel create cells AND external inputs (feeds)
these are spike SOURCES but cells are also targets
external inputs are not targets.
"""
from .parallel import pc
# loop through gids on this node
for gid in self._gid_list:
# check existence of gid with Neuron
if pc.gid_exists(gid):
# get type of cell and pos via gid
# now should be valid for ext inputs
type = self.gid_to_type(gid)
type_pos_ind = gid - self.gid_dict[type][0]
pos = self.pos_dict[type][type_pos_ind]
# figure out which cell type is assoc with the gid
# create cells based on loc property
# creates a NetCon object internally to Neuron
type2class = {'L2_pyramidal': L2Pyr, 'L5_pyramidal': L5Pyr,
'L2_basket': L2Basket, 'L5_basket': L5Basket}
if type in ('L2_pyramidal', 'L5_pyramidal', 'L2_basket',
'L5_basket'):
Cell = type2class[type]
if type in ('L2_pyramidal', 'L5_pyramidal'):
self.cells.append(Cell(gid, pos, self.params))
else:
self.cells.append(Cell(gid, pos))
pc.cell(
gid, self.cells[-1].connect_to_target(
None, self.params['threshold']))
elif type == 'extinput':
# print('type',type)
# to find param index, take difference between REAL gid
# here and gid start point of the items
p_ind = gid - self.gid_dict['extinput'][0]
# now use the param index in the params and create
# the cell and artificial NetCon
self.extinput_list.append(ExtFeed(
type, None, self.p_ext[p_ind], gid))
pc.cell(
gid, self.extinput_list[-1].connect_to_target(
self.params['threshold']))
elif type in self.p_unique.keys():
gid_post = gid - self.gid_dict[type][0]
cell_type = self.gid_to_type(gid_post)
# create dictionary entry, append to list
self.ext_list[type].append(ExtFeed(
type, cell_type, self.p_unique[type], gid))
pc.cell(
gid, self.ext_list[type][-1].connect_to_target(
self.params['threshold']))
else:
print("None of these types in Net()")
exit()
else:
print("None of these types in Net()")
exit()
# connections:
# this NODE is aware of its cells as targets
# for each syn, return list of source GIDs.
# for each item in the list, do a:
# nc = pc.gid_connect(source_gid, target_syn), weight,delay
# Both for synapses AND for external inputs
def _parnet_connect(self):
from .parallel import pc
# loop over target zipped gids and cells
# cells has NO extinputs anyway. also no extgausses
for gid, cell in zip(self._gid_list, self.cells):
# ignore iteration over inputs, since they are NOT targets
if pc.gid_exists(gid) and self.gid_to_type(gid) \
!= 'extinput':
# for each gid, find all the other cells connected to it,
# based on gid
# this MUST be defined in EACH class of cell in self.cells
# parconnect receives connections from other cells
# parreceive receives connections from external inputs
cell.parconnect(gid, self.gid_dict, self.pos_dict, self.params)
cell.parreceive(gid, self.gid_dict, self.pos_dict, self.p_ext)
# now do the unique inputs specific to these cells
# parreceive_ext receives connections from UNIQUE
# external inputs
for type in self.p_unique.keys():
p_type = self.p_unique[type]
cell.parreceive_ext(
type, gid, self.gid_dict, self.pos_dict, p_type)
# setup spike recording for this node
def _record_spikes(self):
from .parallel import pc
# iterate through gids on this node and
# set to record spikes in spike time vec and id vec
# agnostic to type of source, will sort that out later
for gid in self._gid_list:
if pc.gid_exists(gid):
pc.spike_record(gid, self.spiketimes, self.spikegids)
# aggregate recording all the somatic voltages for pyr
def aggregate_currents(self):
"""This method must be run post-integration."""
# this is quite ugly
for cell in self.cells:
# check for celltype
if cell.celltype in ('L5_pyramidal', 'L2_pyramidal'):
# iterate over somatic currents, assumes this list exists
# is guaranteed in L5Pyr()
for key, I_soma in cell.dict_currents.items():
# self.current_L5Pyr_soma was created upon
# in parallel, each node has its own Net()
self.current['%s_soma' % cell.name].add(I_soma)
def state_init(self):
"""Initializes the state closer to baseline."""
for cell in self.cells:
seclist = h.SectionList()
seclist.wholetree(sec=cell.soma)
for sect in seclist:
for seg in sect:
if cell.celltype == 'L2_pyramidal':
seg.v = -71.46
elif cell.celltype == 'L5_pyramidal':
if sect.name() == 'L5Pyr_apical_1':
seg.v = -71.32
elif sect.name() == 'L5Pyr_apical_2':
seg.v = -69.08
elif sect.name() == 'L5Pyr_apical_tuft':
seg.v = -67.30
else:
seg.v = -72.
elif cell.celltype == 'L2_basket':
seg.v = -64.9737
elif cell.celltype == 'L5_basket':
seg.v = -64.9737
def move_cells_to_pos(self):
"""Move cells 3d positions to positions used for wiring."""
for cell in self.cells:
cell.move_to_pos()
def plot_input(self, ax=None, show=True):
"""Plot the histogram of input.
Parameters
----------
ax : instance of matplotlib axis | None
An axis object from matplotlib. If None,
a new figure is created.
show : bool
If True, show the figure.
Returns
-------
fig : instance of matplotlib Figure
The matplotlib figure handle.
"""
import matplotlib.pyplot as plt
spikes = np.array(sum(self.spiketimes, []))
gids = np.array(sum(self.spikegids, []))
valid_gids = np.r_[[v for (k, v) in self.gid_dict.items()
if k.startswith('evprox')]]
mask_evprox = np.in1d(gids, valid_gids)
valid_gids = np.r_[[v for (k, v) in self.gid_dict.items()
if k.startswith('evdist')]]
mask_evdist = np.in1d(gids, valid_gids)
bins = np.linspace(0, self.params['tstop'], 50)
if ax is None:
fig, ax = plt.subplots(1, 1)
ax.hist(spikes[mask_evprox], bins, color='r', label='Proximal')
ax.hist(spikes[mask_evdist], bins, color='g', label='Distal')
plt.legend()
if show:
plt.show()
return ax.get_figure()
def plot_spikes(self, ax=None, show=True):
"""Plot the spiking activity for each cell type.
Parameters
----------
ax : instance of matplotlib axis | None
An axis object from matplotlib. If None,
a new figure is created.
show : bool
If True, show the figure.
Returns
-------
fig : instance of matplotlib Figure
The matplotlib figure object
"""
import matplotlib.pyplot as plt
spikes = np.array(sum(self.spiketimes, []))
gids = np.array(sum(self.spikegids, []))
spike_times = np.zeros((4, spikes.shape[0]))
cell_types = ['L5_pyramidal', 'L5_basket', 'L2_pyramidal', 'L2_basket']
for idx, key in enumerate(cell_types):
mask = np.in1d(gids, self.gid_dict[key])
spike_times[idx, mask] = spikes[mask]
if ax is None:
fig, ax = plt.subplots(1, 1)
ax.eventplot(spike_times, colors=['r', 'b', 'g', 'w'])
ax.legend(cell_types, ncol=2)
ax.set_facecolor('k')
ax.set_xlabel('Time (ms)')
ax.get_yaxis().set_visible(False)
ax.set_ylim((-1, 4.5))
if show:
plt.show()
return ax.get_figure()
<file_sep>/examples/plot_simulate_somato.py
"""
====================
Simulate somato data
====================
This example demonstrates how to simulate the source time
courses obtained during median nerve stimulation in the MNE
somatosensory dataset.
"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
###############################################################################
# First, we will import the packages and define the paths
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import somato
from mne.minimum_norm import apply_inverse, make_inverse_operator
data_path = somato.data_path()
subject = '01'
task = 'somato'
raw_fname = op.join(data_path, 'sub-{}'.format(subject), 'meg',
'sub-{}_task-{}_meg.fif'.format(subject, task))
fwd_fname = op.join(data_path, 'derivatives', 'sub-{}'.format(subject),
'sub-{}_task-{}-fwd.fif'.format(subject, task))
subjects_dir = op.join(data_path, 'derivatives', 'freesurfer', 'subjects')
###############################################################################
# Then, we get the raw data and estimage the source time course
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, 40)
events = mne.find_events(raw, stim_channel='STI 014')
event_id, tmin, tmax = 1, -.2, .15
baseline = None
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=baseline,
reject=dict(grad=4000e-13, eog=350e-6), preload=True)
evoked = epochs.average()
fwd = mne.read_forward_solution(fwd_fname)
cov = mne.compute_covariance(epochs)
inv = make_inverse_operator(epochs.info, fwd, cov)
method = "MNE"
snr = 3.
lambda2 = 1. / snr ** 2
stc = apply_inverse(evoked, inv, lambda2, method=method, pick_ori="normal",
return_residual=False, verbose=True)
pick_vertex = np.argmax(np.linalg.norm(stc.data, axis=1))
plt.figure()
plt.plot(1e3 * stc.times, stc.data[pick_vertex, :].T * 1e9, 'ro-')
plt.xlabel('time (ms)')
plt.ylabel('%s value (nAM)' % method)
plt.xlim((0, 150))
plt.axhline(0)
plt.show()
###############################################################################
# Now, let us try to simulate the same with MNE-neuron
import os.path as op
import hnn_core
from hnn_core import simulate_dipole, read_params, Network
hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
params_fname = op.join(hnn_core_root, 'param', 'N20.json')
params = read_params(params_fname)
net = Network(params)
dpl = simulate_dipole(net)
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 6))
dpl[0].plot(ax=axes[0])
net.plot_input(ax=axes[1])
net.plot_spikes()
<file_sep>/hnn_core/tests/test_network.py
# Authors: <NAME> <<EMAIL>>
from copy import deepcopy
import os.path as op
import hnn_core
from hnn_core import read_params, Network
def test_network():
"""Test network object."""
hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
params_fname = op.join(hnn_core_root, 'param', 'default.json')
params = read_params(params_fname)
net = Network(deepcopy(params))
# Assert that params are conserved across Network initialization
for p in params:
assert params[p] == net.params[p]
assert len(params) == len(net.params)
print(net)
print(net.cells[:2])
# Assert that proper number of gids are created for Network inputs
assert len(net.gid_dict['extinput']) == 2
assert len(net.gid_dict['extgauss']) == net.N_cells
assert len(net.gid_dict['extpois']) == net.N_cells
for ev_input in params['t_ev*']:
type_key = ev_input[2: -2] + ev_input[-1]
assert len(net.gid_dict[type_key]) == net.N_cells
<file_sep>/hnn_core/tests/test_compare_hnn.py
import os.path as op
from numpy import loadtxt
from numpy.testing import assert_array_equal
from mne.utils import _fetch_file
import hnn_core
from hnn_core import simulate_dipole, read_params, Network
def test_hnn_core():
"""Test to check if MNE neuron does not break."""
# small snippet of data on data branch for now. To be deleted
# later. Data branch should have only commit so it does not
# pollute the history.
data_url = ('https://raw.githubusercontent.com/jonescompneurolab/'
'hnn-core/test_data/dpl.txt')
if not op.exists('dpl.txt'):
_fetch_file(data_url, 'dpl.txt')
dpl_master = loadtxt('dpl.txt')
hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
params_fname = op.join(hnn_core_root, 'param', 'default.json')
params = read_params(params_fname)
net = Network(params, n_jobs=1)
dpl = simulate_dipole(net)[0]
fname = './dpl2.txt'
dpl.write(fname)
dpl_pr = loadtxt(fname)
assert_array_equal(dpl_pr[:, 2], dpl_master[:, 2]) # L2
assert_array_equal(dpl_pr[:, 3], dpl_master[:, 3]) # L5
# Test spike type counts
spiketype_counts = {}
for spikegid in net.spikegids[0]:
if net.gid_to_type(spikegid) not in spiketype_counts:
spiketype_counts[net.gid_to_type(spikegid)] = 0
else:
spiketype_counts[net.gid_to_type(spikegid)] += 1
assert 'extinput' not in spiketype_counts
assert 'exgauss' not in spiketype_counts
assert 'extpois' not in spiketype_counts
assert spiketype_counts == {'evprox1': 269,
'L2_basket': 54,
'L2_pyramidal': 113,
'L5_pyramidal': 395,
'L5_basket': 85,
'evdist1': 234,
'evprox2': 269}
<file_sep>/hnn_core/pyramidal.py
"""Model for Pyramidal cell class."""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import numpy as np
from neuron import h
from .cell import _Cell
from .params import compare_dictionaries
from .params_default import (get_L2Pyr_params_default,
get_L5Pyr_params_default)
# Units for e: mV
# Units for gbar: S/cm^2 unless otherwise noted
class Pyr(_Cell):
"""Pyramidal neuron.
Attributes
----------
name : str
The name of the cell
dends : dict
The dendrites. The key is the name of the dendrite
and the value is an instance of h.Section.
list_dend : list of h.Section
List of dendrites.
"""
def __init__(self, gid, soma_props):
_Cell.__init__(self, gid, soma_props)
self.create_soma()
# store cell_name as self variable for later use
self.name = soma_props['name']
# preallocate dict to store dends
self.dends = {}
# for legacy use with L5Pyr
self.list_dend = []
def get_sectnames(self):
"""Create dictionary of section names with entries
to scale section lengths to length along z-axis."""
seclist = h.SectionList()
seclist.wholetree(sec=self.soma)
d = dict((sect.name(), 1.) for sect in seclist)
for key in d.keys():
# basal_2 and basal_3 at 45 degree angle to z-axis.
if 'basal_2' in key:
d[key] = np.sqrt(2) / 2.
elif 'basal_3' in key:
d[key] = np.sqrt(2) / 2.
# apical_oblique at 90 perpendicular to z-axis
elif 'apical_oblique' in key:
d[key] = 0.
# All basalar dendrites extend along negative z-axis
if 'basal' in key:
d[key] = -d[key]
return d
def create_dends(self, p_dend_props):
"""Create dendrites."""
for key in p_dend_props:
self.dends[key] = h.Section(
name=self.name + '_' + key) # create dend
# apical: 0--4; basal: 5--7
self.list_dend = [self.dends[key] for key in
['apical_trunk', 'apical_oblique', 'apical_1',
'apical_2', 'apical_tuft', 'basal_1', 'basal_2',
'basal_3'] if key in self.dends]
def set_dend_props(self, p_dend_props):
""""Iterate over keys in p_dend_props. Create dend for each key."""
for key in p_dend_props:
# set dend props
self.dends[key].L = p_dend_props[key]['L']
self.dends[key].diam = p_dend_props[key]['diam']
self.dends[key].Ra = p_dend_props[key]['Ra']
self.dends[key].cm = p_dend_props[key]['cm']
# set dend nseg
if p_dend_props[key]['L'] > 100.:
self.dends[key].nseg = int(p_dend_props[key]['L'] / 50.)
# make dend.nseg odd for all sections
if not self.dends[key].nseg % 2:
self.dends[key].nseg += 1
def get_sections(self):
ls = [self.soma]
for key in ['apical_trunk', 'apical_1', 'apical_2', 'apical_tuft',
'apical_oblique', 'basal_1', 'basal_2', 'basal_3']:
if key in self.dends:
ls.append(self.dends[key])
return ls
def get_section_names(self):
"""Get section names."""
ls = ['soma']
for key in ['apical_trunk', 'apical_1', 'apical_2', 'apical_tuft',
'apical_oblique', 'basal_1', 'basal_2', 'basal_3']:
if key in self.dends:
ls.append(key)
return ls
def _get_dend_props(self):
"""Returns hardcoded dendritic properties."""
props = {
'apical_trunk': {
'L': self.p_all['%s_apicaltrunk_L' % self.name],
'diam': self.p_all['%s_apicaltrunk_diam' % self.name],
'cm': self.p_all['%s_dend_cm' % self.name],
'Ra': self.p_all['%s_dend_Ra' % self.name],
},
'apical_1': {
'L': self.p_all['%s_apical1_L' % self.name],
'diam': self.p_all['%s_apical1_diam' % self.name],
'cm': self.p_all['%s_dend_cm' % self.name],
'Ra': self.p_all['%s_dend_Ra' % self.name],
},
'apical_tuft': {
'L': self.p_all['%s_apicaltuft_L' % self.name],
'diam': self.p_all['%s_apicaltuft_diam' % self.name],
'cm': self.p_all['%s_dend_cm' % self.name],
'Ra': self.p_all['%s_dend_Ra' % self.name],
},
'apical_oblique': {
'L': self.p_all['%s_apicaloblique_L' % self.name],
'diam': self.p_all['%s_apicaloblique_diam' % self.name],
'cm': self.p_all['%s_dend_cm' % self.name],
'Ra': self.p_all['%s_dend_Ra' % self.name],
},
'basal_1': {
'L': self.p_all['%s_basal1_L' % self.name],
'diam': self.p_all['%s_basal1_diam' % self.name],
'cm': self.p_all['%s_dend_cm' % self.name],
'Ra': self.p_all['%s_dend_Ra' % self.name],
},
'basal_2': {
'L': self.p_all['%s_basal2_L' % self.name],
'diam': self.p_all['%s_basal2_diam' % self.name],
'cm': self.p_all['%s_dend_cm' % self.name],
'Ra': self.p_all['%s_dend_Ra' % self.name],
},
'basal_3': {
'L': self.p_all['%s_basal3_L' % self.name],
'diam': self.p_all['%s_basal3_diam' % self.name],
'cm': self.p_all['%s_dend_cm' % self.name],
'Ra': self.p_all['%s_dend_Ra' % self.name],
},
}
if self.name == 'L5Pyr':
props.update({
'apical_2': {
'L': self.p_all['L5Pyr_apical2_L'],
'diam': self.p_all['L5Pyr_apical2_diam'],
'cm': self.p_all['L5Pyr_dend_cm'],
'Ra': self.p_all['L5Pyr_dend_Ra'],
},
})
return props
def _get_syn_props(self):
return {
'ampa': {
'e': self.p_all['%s_ampa_e' % self.name],
'tau1': self.p_all['%s_ampa_tau1' % self.name],
'tau2': self.p_all['%s_ampa_tau2' % self.name],
},
'nmda': {
'e': self.p_all['%s_nmda_e' % self.name],
'tau1': self.p_all['%s_nmda_tau1' % self.name],
'tau2': self.p_all['%s_nmda_tau2' % self.name],
},
'gabaa': {
'e': self.p_all['%s_gabaa_e' % self.name],
'tau1': self.p_all['%s_gabaa_tau1' % self.name],
'tau2': self.p_all['%s_gabaa_tau2' % self.name],
},
'gabab': {
'e': self.p_all['%s_gabab_e' % self.name],
'tau1': self.p_all['%s_gabab_tau1' % self.name],
'tau2': self.p_all['%s_gabab_tau2' % self.name],
}
}
def _synapse_create(self, p_syn):
"""Creates synapses onto this cell."""
# Somatic synapses
self.synapses = {
'soma_gabaa': self.syn_create(self.soma(0.5), p_syn['gabaa']),
'soma_gabab': self.syn_create(self.soma(0.5), p_syn['gabab']),
}
# Dendritic synapses
self.apicaloblique_ampa = self.syn_create(
self.dends['apical_oblique'](0.5), p_syn['ampa'])
self.apicaloblique_nmda = self.syn_create(
self.dends['apical_oblique'](0.5), p_syn['nmda'])
self.basal2_ampa = self.syn_create(
self.dends['basal_2'](0.5), p_syn['ampa'])
self.basal2_nmda = self.syn_create(
self.dends['basal_2'](0.5), p_syn['nmda'])
self.basal3_ampa = self.syn_create(
self.dends['basal_3'](0.5), p_syn['ampa'])
self.basal3_nmda = self.syn_create(
self.dends['basal_3'](0.5), p_syn['nmda'])
self.apicaltuft_ampa = self.syn_create(
self.dends['apical_tuft'](0.5), p_syn['ampa'])
self.apicaltuft_nmda = self.syn_create(
self.dends['apical_tuft'](0.5), p_syn['nmda'])
if self.name == 'L5Pyr':
self.apicaltuft_gabaa = self.syn_create(
self.dends['apical_tuft'](0.5), p_syn['gabaa'])
class L2Pyr(Pyr):
"""Layer 2 pyramidal cell class.
Parameters
----------
gid : int
The cell id.
p : dict
The parameters dictionary.
Attributes
----------
name : str
The name of the cell
dends : dict
The dendrites. The key is the name of the dendrite
and the value is an instance of h.Section.
list_dend : list of h.Section
List of dendrites.
"""
def __init__(self, gid=-1, pos=-1, p={}):
# Get default L2Pyr params and update them with any
# corresponding params in p
p_all_default = get_L2Pyr_params_default()
self.p_all = compare_dictionaries(p_all_default, p)
# Get somatic, dendritic, and synapse properties
p_soma = self._get_soma_props(pos)
# usage: Pyr.__init__(self, soma_props)
Pyr.__init__(self, gid, p_soma)
p_dend = self._get_dend_props()
p_syn = self._get_syn_props()
self.celltype = 'L2_pyramidal'
# geometry
# creates dict of dends: self.dends
self.create_dends(p_dend)
self.topol() # sets the connectivity between sections
# sets geom properties;
# adjusted after translation from hoc (2009 model)
self.geom(p_dend)
# biophysics
self._biophys_soma()
self._biophys_dends()
# dipole_insert() comes from Cell()
self.yscale = self.get_sectnames()
self.dipole_insert(self.yscale)
# create synapses
self._synapse_create(p_syn)
# self.__synapse_create()
# run record_current_soma(), defined in Cell()
self.record_current_soma()
# Returns hardcoded somatic properties
def _get_soma_props(self, pos):
return {
'pos': pos,
'L': self.p_all['L2Pyr_soma_L'],
'diam': self.p_all['L2Pyr_soma_diam'],
'cm': self.p_all['L2Pyr_soma_cm'],
'Ra': self.p_all['L2Pyr_soma_Ra'],
'name': 'L2Pyr',
}
def geom(self, p_dend):
"""The geometry."""
soma = self.soma
dend = self.list_dend
# increased by 70% for human
soma.L = 22.1
dend[0].L = 59.5
dend[1].L = 340
dend[2].L = 306
dend[3].L = 238
dend[4].L = 85
dend[5].L = 255
dend[6].L = 255
soma.diam = 23.4
dend[0].diam = 4.25
dend[1].diam = 3.91
dend[2].diam = 4.08
dend[3].diam = 3.4
dend[4].diam = 4.25
dend[5].diam = 2.72
dend[6].diam = 2.72
# resets length,diam,etc. based on param specification
self.set_dend_props(p_dend)
def topol(self):
"""Connects sections of THIS cell together."""
# child.connect(parent, parent_end, {child_start=0})
# Distal (Apical)
self.dends['apical_trunk'].connect(self.soma, 1, 0)
self.dends['apical_1'].connect(self.dends['apical_trunk'], 1, 0)
self.dends['apical_tuft'].connect(self.dends['apical_1'], 1, 0)
# apical_oblique comes off distal end of apical_trunk
self.dends['apical_oblique'].connect(self.dends['apical_trunk'], 1, 0)
# Proximal (basal)
self.dends['basal_1'].connect(self.soma, 0, 0)
self.dends['basal_2'].connect(self.dends['basal_1'], 1, 0)
self.dends['basal_3'].connect(self.dends['basal_1'], 1, 0)
self.basic_shape() # translated from original hoc (2009 model)
def basic_shape(self):
"""Define shape of the neuron."""
# THESE AND LENGHTHS MUST CHANGE TOGETHER!!!
pt3dclear = h.pt3dclear
pt3dadd = h.pt3dadd
soma = self.soma
dend = self.list_dend
pt3dclear(sec=soma)
pt3dadd(-50, 765, 0, 1, sec=soma)
pt3dadd(-50, 778, 0, 1, sec=soma)
pt3dclear(sec=dend[0])
pt3dadd(-50, 778, 0, 1, sec=dend[0])
pt3dadd(-50, 813, 0, 1, sec=dend[0])
pt3dclear(sec=dend[1])
pt3dadd(-50, 813, 0, 1, sec=dend[1])
pt3dadd(-250, 813, 0, 1, sec=dend[1])
pt3dclear(sec=dend[2])
pt3dadd(-50, 813, 0, 1, sec=dend[2])
pt3dadd(-50, 993, 0, 1, sec=dend[2])
pt3dclear(sec=dend[3])
pt3dadd(-50, 993, 0, 1, sec=dend[3])
pt3dadd(-50, 1133, 0, 1, sec=dend[3])
pt3dclear(sec=dend[4])
pt3dadd(-50, 765, 0, 1, sec=dend[4])
pt3dadd(-50, 715, 0, 1, sec=dend[4])
pt3dclear(sec=dend[5])
pt3dadd(-50, 715, 0, 1, sec=dend[5])
pt3dadd(-156, 609, 0, 1, sec=dend[5])
pt3dclear(sec=dend[6])
pt3dadd(-50, 715, 0, 1, sec=dend[6])
pt3dadd(56, 609, 0, 1, sec=dend[6])
def _biophys_soma(self):
"""Adds biophysics to soma."""
# set soma biophysics specified in Pyr
# self.pyr_biophys_soma()
# Insert 'hh2' mechanism
self.soma.insert('hh2')
self.soma.gkbar_hh2 = self.p_all['L2Pyr_soma_gkbar_hh2']
self.soma.gl_hh2 = self.p_all['L2Pyr_soma_gl_hh2']
self.soma.el_hh2 = self.p_all['L2Pyr_soma_el_hh2']
self.soma.gnabar_hh2 = self.p_all['L2Pyr_soma_gnabar_hh2']
# Insert 'km' mechanism
# Units: pS/um^2
self.soma.insert('km')
self.soma.gbar_km = self.p_all['L2Pyr_soma_gbar_km']
def _biophys_dends(self):
"""Defining biophysics for dendrites."""
# set dend biophysics
# iterate over keys in self.dends and set biophysics for each dend
for key in self.dends:
# neuron syntax is used to set values for mechanisms
# sec.gbar_mech = x sets value of gbar for mech to x for all segs
# in a section. This method is significantly faster than using
# a for loop to iterate over all segments to set mech values
# Insert 'hh' mechanism
self.dends[key].insert('hh2')
self.dends[key].gkbar_hh2 = self.p_all['L2Pyr_dend_gkbar_hh2']
self.dends[key].gl_hh2 = self.p_all['L2Pyr_dend_gl_hh2']
self.dends[key].gnabar_hh2 = self.p_all['L2Pyr_dend_gnabar_hh2']
self.dends[key].el_hh2 = self.p_all['L2Pyr_dend_el_hh2']
# Insert 'km' mechanism
# Units: pS/um^2
self.dends[key].insert('km')
self.dends[key].gbar_km = self.p_all['L2Pyr_dend_gbar_km']
def parconnect(self, gid, gid_dict, pos_dict, p):
"""Collect receptor-type-based connections here."""
postsyns = [self.apicaloblique_ampa, self.basal2_ampa,
self.basal3_ampa]
self._connect(gid, gid_dict, pos_dict, p,
'L2_pyramidal', 'L2Pyr', lamtha=3., receptor='ampa',
postsyns=postsyns, autapses=False)
postsyns = [self.apicaloblique_nmda, self.basal2_nmda,
self.basal3_nmda]
self._connect(gid, gid_dict, pos_dict, p,
'L2_pyramidal', 'L2Pyr', lamtha=3., receptor='nmda',
postsyns=postsyns, autapses=False)
self._connect(gid, gid_dict, pos_dict, p,
'L2_basket', 'L2Basket', lamtha=50., receptor='gabaa',
postsyns=[self.synapses['soma_gabaa']])
self._connect(gid, gid_dict, pos_dict, p,
'L2_basket', 'L2Basket', lamtha=50., receptor='gabab',
postsyns=[self.synapses['soma_gabab']])
# may be reorganizable
def parreceive(self, gid, gid_dict, pos_dict, p_ext):
"""Connect cell."""
for gid_src, p_src, pos in zip(gid_dict['extinput'], p_ext,
pos_dict['extinput']):
# Check if AMPA params defined in p_src
if 'L2Pyr_ampa' in p_src.keys():
nc_dict_ampa = {
'pos_src': pos,
'A_weight': p_src['L2Pyr_ampa'][0],
'A_delay': p_src['L2Pyr_ampa'][1],
'lamtha': p_src['lamtha'],
'threshold': p_src['threshold'],
'type_src': 'ext'
}
# Proximal feed AMPA synapses
if p_src['loc'] == 'proximal':
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_ampa, self.basal2_ampa))
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_ampa, self.basal3_ampa))
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_ampa, self.apicaloblique_ampa))
# Distal feed AMPA synapses
elif p_src['loc'] == 'distal':
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_ampa, self.apicaltuft_ampa))
# Check is NMDA params defined in p_src
if 'L2Pyr_nmda' in p_src.keys():
nc_dict_nmda = {
'pos_src': pos,
'A_weight': p_src['L2Pyr_nmda'][0],
'A_delay': p_src['L2Pyr_nmda'][1],
'lamtha': p_src['lamtha'],
'threshold': p_src['threshold'],
'type_src': 'ext'
}
# Proximal feed NMDA synapses
if p_src['loc'] == 'proximal':
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_nmda, self.basal2_nmda))
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_nmda, self.basal3_nmda))
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_nmda, self.apicaloblique_nmda))
# Distal feed NMDA synapses
elif p_src['loc'] == 'distal':
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_nmda, self.apicaltuft_nmda))
# one parreceive function to handle all types of external parreceives
# types must be defined explicitly here
# this function handles evoked, gaussian, and poisson inputs
def parreceive_ext(self, type, gid, gid_dict, pos_dict, p_ext):
"""Connect cell to external input."""
if type.startswith(('evprox', 'evdist')):
if self.celltype in p_ext.keys():
gid_ev = gid + gid_dict[type][0]
# separate dictionaries for ampa and nmda evoked inputs
nc_dict_ampa = {
'pos_src': pos_dict[type][gid],
# index 0 for ampa weight
'A_weight': p_ext[self.celltype][0],
'A_delay': p_ext[self.celltype][2], # index 2 for delay
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
nc_dict_nmda = {
'pos_src': pos_dict[type][gid],
# index 1 for nmda weight
'A_weight': p_ext[self.celltype][1],
'A_delay': p_ext[self.celltype][2], # index 2 for delay
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
if p_ext['loc'] == 'proximal':
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_ampa, self.basal2_ampa))
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_ampa, self.basal3_ampa))
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_ampa, self.apicaloblique_ampa))
# NEW: note that default/original is 0 nmda weight
# for these proximal dends
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_nmda, self.basal2_nmda))
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_nmda, self.basal3_nmda))
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_nmda, self.apicaloblique_nmda))
elif p_ext['loc'] == 'distal':
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_ampa, self.apicaltuft_ampa))
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_nmda, self.apicaltuft_nmda))
elif type == 'extgauss':
# gid is this cell's gid
# gid_dict is the whole dictionary, including the gids of
# the extgauss
# pos_list is also the pos of the extgauss (net origin)
# p_ext_gauss are the params (strength, etc.)
# gid shift is based on L2_pyramidal cells NOT L5
# I recognize this is ugly (hack)
# gid_shift = gid_dict['extgauss'][0] - gid_dict['L2_pyramidal'][0]
if 'L2_pyramidal' in p_ext.keys():
gid_extgauss = gid + gid_dict['extgauss'][0]
nc_dict = {
'pos_src': pos_dict['extgauss'][gid],
# index 0 for ampa weight (nmda not yet used in Gauss)
'A_weight': p_ext['L2_pyramidal'][0],
'A_delay': p_ext['L2_pyramidal'][2], # index 2 for delay
'lamtha': p_ext['lamtha'],
'threshold': p_ext['threshold'],
'type_src': type
}
self.ncfrom_extgauss.append(self.parconnect_from_src(
gid_extgauss, nc_dict, self.basal2_ampa))
self.ncfrom_extgauss.append(self.parconnect_from_src(
gid_extgauss, nc_dict, self.basal3_ampa))
self.ncfrom_extgauss.append(self.parconnect_from_src(
gid_extgauss, nc_dict, self.apicaloblique_ampa))
elif type == 'extpois':
if self.celltype in p_ext.keys():
gid_extpois = gid + gid_dict['extpois'][0]
nc_dict = {
'pos_src': pos_dict['extpois'][gid],
# index 0 for ampa weight
'A_weight': p_ext[self.celltype][0],
'A_delay': p_ext[self.celltype][2], # index 2 for delay
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
self.ncfrom_extpois.append(self.parconnect_from_src(
gid_extpois, nc_dict, self.basal2_ampa))
self.ncfrom_extpois.append(self.parconnect_from_src(
gid_extpois, nc_dict, self.basal3_ampa))
self.ncfrom_extpois.append(self.parconnect_from_src(
gid_extpois, nc_dict, self.apicaloblique_ampa))
if p_ext[self.celltype][1] > 0.0:
# index 1 for nmda weight
nc_dict['A_weight'] = p_ext[self.celltype][1]
self.ncfrom_extpois.append(self.parconnect_from_src(
gid_extpois, nc_dict, self.basal2_nmda))
self.ncfrom_extpois.append(self.parconnect_from_src(
gid_extpois, nc_dict, self.basal3_nmda))
self.ncfrom_extpois.append(self.parconnect_from_src(
gid_extpois, nc_dict, self.apicaloblique_nmda))
else:
print("Warning, ext type def does not exist in L2Pyr")
# Units for e: mV
# Units for gbar: S/cm^2 unless otherwise noted
# units for taur: ms
class L5Pyr(Pyr):
"""Layer 5 Pyramidal class.
Attributes
----------
name : str
The name of the cell
dends : dict
The dendrites. The key is the name of the dendrite
and the value is an instance of h.Section.
list_dend : list of h.Section
List of dendrites.
"""
def __init__(self, gid=-1, pos=-1, p={}):
"""Get default L5Pyr params and update them with
corresponding params in p."""
p_all_default = get_L5Pyr_params_default()
self.p_all = compare_dictionaries(p_all_default, p)
# Get somatic, dendirtic, and synapse properties
p_soma = self.__get_soma_props(pos)
Pyr.__init__(self, gid, p_soma)
p_dend = self._get_dend_props()
p_syn = self._get_syn_props()
self.celltype = 'L5_pyramidal'
# Geometry
# dend Cm and dend Ra set using soma Cm and soma Ra
self.create_dends(p_dend) # just creates the sections
self.topol() # sets the connectivity between sections
# sets geom properties; adjusted after translation from
# hoc (2009 model)
self.geom(p_dend)
# biophysics
self.__biophys_soma()
self.__biophys_dends()
# Dictionary of length scales to calculate dipole without
# 3d shape. Comes from Pyr().
# dipole_insert() comes from Cell()
self.yscale = self.get_sectnames()
self.dipole_insert(self.yscale)
# create synapses
self._synapse_create(p_syn)
# insert iclamp
self.list_IClamp = []
# run record current soma, defined in Cell()
self.record_current_soma()
def basic_shape(self):
"""The shape of the neuron."""
# THESE AND LENGHTHS MUST CHANGE TOGETHER!!!
pt3dclear = h.pt3dclear
pt3dadd = h.pt3dadd
dend = self.list_dend
pt3dclear(sec=self.soma)
pt3dadd(0, 0, 0, 1, sec=self.soma)
pt3dadd(0, 23, 0, 1, sec=self.soma)
pt3dclear(sec=dend[0])
pt3dadd(0, 23, 0, 1, sec=dend[0])
pt3dadd(0, 83, 0, 1, sec=dend[0])
pt3dclear(sec=dend[1])
pt3dadd(0, 83, 0, 1, sec=dend[1])
pt3dadd(-150, 83, 0, 1, sec=dend[1])
pt3dclear(sec=dend[2])
pt3dadd(0, 83, 0, 1, sec=dend[2])
pt3dadd(0, 483, 0, 1, sec=dend[2])
pt3dclear(sec=dend[3])
pt3dadd(0, 483, 0, 1, sec=dend[3])
pt3dadd(0, 883, 0, 1, sec=dend[3])
pt3dclear(sec=dend[4])
pt3dadd(0, 883, 0, 1, sec=dend[4])
pt3dadd(0, 1133, 0, 1, sec=dend[4])
pt3dclear(sec=dend[5])
pt3dadd(0, 0, 0, 1, sec=dend[5])
pt3dadd(0, -50, 0, 1, sec=dend[5])
pt3dclear(sec=dend[6])
pt3dadd(0, -50, 0, 1, sec=dend[6])
pt3dadd(-106, -156, 0, 1, sec=dend[6])
pt3dclear(sec=dend[7])
pt3dadd(0, -50, 0, 1, sec=dend[7])
pt3dadd(106, -156, 0, 1, sec=dend[7])
def geom(self, p_dend):
"""The geometry."""
soma = self.soma
dend = self.list_dend
# soma.L = 13 # BUSH 1999 spike amp smaller
soma.L = 39 # Bush 1993
dend[0].L = 102
dend[1].L = 255
dend[2].L = 680 # default 400
dend[3].L = 680 # default 400
dend[4].L = 425
dend[5].L = 85
dend[6].L = 255 # default 150
dend[7].L = 255 # default 150
# soma.diam = 18.95 # Bush 1999
soma.diam = 28.9 # Bush 1993
dend[0].diam = 10.2
dend[1].diam = 5.1
dend[2].diam = 7.48 # default 4.4
dend[3].diam = 4.93 # default 2.9
dend[4].diam = 3.4
dend[5].diam = 6.8
dend[6].diam = 8.5
dend[7].diam = 8.5
# resets length,diam,etc. based on param specification
self.set_dend_props(p_dend)
def __get_soma_props(self, pos):
"""Sets somatic properties. Returns dictionary."""
return {
'pos': pos,
'L': self.p_all['L5Pyr_soma_L'],
'diam': self.p_all['L5Pyr_soma_diam'],
'cm': self.p_all['L5Pyr_soma_cm'],
'Ra': self.p_all['L5Pyr_soma_Ra'],
'name': 'L5Pyr',
}
def topol(self):
"""Connects sections of this cell together."""
# child.connect(parent, parent_end, {child_start=0})
# Distal (apical)
self.dends['apical_trunk'].connect(self.soma, 1, 0)
self.dends['apical_1'].connect(self.dends['apical_trunk'], 1, 0)
self.dends['apical_2'].connect(self.dends['apical_1'], 1, 0)
self.dends['apical_tuft'].connect(self.dends['apical_2'], 1, 0)
# apical_oblique comes off distal end of apical_trunk
self.dends['apical_oblique'].connect(self.dends['apical_trunk'], 1, 0)
# Proximal (basal)
self.dends['basal_1'].connect(self.soma, 0, 0)
self.dends['basal_2'].connect(self.dends['basal_1'], 1, 0)
self.dends['basal_3'].connect(self.dends['basal_1'], 1, 0)
self.basic_shape() # translated from original hoc (2009 model)
# adds biophysics to soma
def __biophys_soma(self):
# set soma biophysics specified in Pyr
# self.pyr_biophys_soma()
# Insert 'hh2' mechanism
self.soma.insert('hh2')
self.soma.gkbar_hh2 = self.p_all['L5Pyr_soma_gkbar_hh2']
self.soma.gnabar_hh2 = self.p_all['L5Pyr_soma_gnabar_hh2']
self.soma.gl_hh2 = self.p_all['L5Pyr_soma_gl_hh2']
self.soma.el_hh2 = self.p_all['L5Pyr_soma_el_hh2']
# insert 'ca' mechanism
# Units: pS/um^2
self.soma.insert('ca')
self.soma.gbar_ca = self.p_all['L5Pyr_soma_gbar_ca']
# insert 'cad' mechanism
# units of tau are ms
self.soma.insert('cad')
self.soma.taur_cad = self.p_all['L5Pyr_soma_taur_cad']
# insert 'kca' mechanism
# units are S/cm^2?
self.soma.insert('kca')
self.soma.gbar_kca = self.p_all['L5Pyr_soma_gbar_kca']
# Insert 'km' mechanism
# Units: pS/um^2
self.soma.insert('km')
self.soma.gbar_km = self.p_all['L5Pyr_soma_gbar_km']
# insert 'cat' mechanism
self.soma.insert('cat')
self.soma.gbar_cat = self.p_all['L5Pyr_soma_gbar_cat']
# insert 'ar' mechanism
self.soma.insert('ar')
self.soma.gbar_ar = self.p_all['L5Pyr_soma_gbar_ar']
def __biophys_dends(self):
# set dend biophysics specified in Pyr()
# self.pyr_biophys_dends()
# set dend biophysics not specified in Pyr()
for key in self.dends:
# Insert 'hh2' mechanism
self.dends[key].insert('hh2')
self.dends[key].gkbar_hh2 = self.p_all['L5Pyr_dend_gkbar_hh2']
self.dends[key].gl_hh2 = self.p_all['L5Pyr_dend_gl_hh2']
self.dends[key].gnabar_hh2 = self.p_all['L5Pyr_dend_gnabar_hh2']
self.dends[key].el_hh2 = self.p_all['L5Pyr_dend_el_hh2']
# Insert 'ca' mechanims
# Units: pS/um^2
self.dends[key].insert('ca')
self.dends[key].gbar_ca = self.p_all['L5Pyr_dend_gbar_ca']
# Insert 'cad' mechanism
self.dends[key].insert('cad')
self.dends[key].taur_cad = self.p_all['L5Pyr_dend_taur_cad']
# Insert 'kca' mechanism
self.dends[key].insert('kca')
self.dends[key].gbar_kca = self.p_all['L5Pyr_dend_gbar_kca']
# Insert 'km' mechansim
# Units: pS/um^2
self.dends[key].insert('km')
self.dends[key].gbar_km = self.p_all['L5Pyr_dend_gbar_km']
# insert 'cat' mechanism
self.dends[key].insert('cat')
self.dends[key].gbar_cat = self.p_all['L5Pyr_dend_gbar_cat']
# insert 'ar' mechanism
self.dends[key].insert('ar')
# set gbar_ar
# Value depends on distance from the soma. Soma is set as
# origin by passing self.soma as a sec argument to h.distance()
# Then iterate over segment nodes of dendritic sections
# and set gbar_ar depending on h.distance(seg.x), which returns
# distance from the soma to this point on the CURRENTLY ACCESSED
# SECTION!!!
h.distance(sec=self.soma)
for key in self.dends:
self.dends[key].push()
for seg in self.dends[key]:
seg.gbar_ar = 1e-6 * np.exp(3e-3 * h.distance(seg.x))
h.pop_section()
# parallel connection function FROM all cell types TO here
def parconnect(self, gid, gid_dict, pos_dict, p):
postsyns = [self.apicaloblique_ampa, self.basal2_ampa,
self.basal3_ampa]
self._connect(gid, gid_dict, pos_dict, p,
'L5_pyramidal', 'L5Pyr', lamtha=3., receptor='ampa',
postsyns=postsyns, autapses=False)
postsyns = [self.apicaloblique_nmda, self.basal2_nmda,
self.basal3_nmda]
self._connect(gid, gid_dict, pos_dict, p,
'L5_pyramidal', 'L5Pyr', lamtha=3., receptor='nmda',
postsyns=postsyns, autapses=False)
self._connect(gid, gid_dict, pos_dict, p,
'L5_basket', 'L5Basket', lamtha=70., receptor='gabaa',
postsyns=[self.synapses['soma_gabaa']])
self._connect(gid, gid_dict, pos_dict, p,
'L5_basket', 'L5Basket', lamtha=70., receptor='gabab',
postsyns=[self.synapses['soma_gabab']])
postsyns = [self.basal2_ampa, self.basal3_ampa, self.apicaltuft_ampa,
self.apicaloblique_ampa]
self._connect(gid, gid_dict, pos_dict, p,
'L2_pyramidal', 'L2Pyr', lamtha=3., postsyns=postsyns)
self._connect(gid, gid_dict, pos_dict, p,
'L2_basket', 'L2Basket', lamtha=50.,
postsyns=[self.apicaltuft_gabaa])
# receive from external inputs
def parreceive(self, gid, gid_dict, pos_dict, p_ext):
for gid_src, p_src, pos in zip(gid_dict['extinput'],
p_ext, pos_dict['extinput']):
# Check if AMPA params defined in p_src
if 'L5Pyr_ampa' in p_src.keys():
nc_dict_ampa = {
'pos_src': pos,
'A_weight': p_src['L5Pyr_ampa'][0],
'A_delay': p_src['L5Pyr_ampa'][1],
'lamtha': p_src['lamtha'],
'threshold': p_src['threshold'],
'type_src': 'ext'
}
# Proximal feed AMPA synapses
if p_src['loc'] == 'proximal':
# basal2_ampa, basal3_ampa, apicaloblique_ampa
self.ncfrom_extinput.append(
self.parconnect_from_src(gid_src, nc_dict_ampa,
self.basal2_ampa))
self.ncfrom_extinput.append(
self.parconnect_from_src(gid_src, nc_dict_ampa,
self.basal3_ampa))
self.ncfrom_extinput.append(
self.parconnect_from_src(gid_src, nc_dict_ampa,
self.apicaloblique_ampa))
# Distal feed AMPA synsapes
elif p_src['loc'] == 'distal':
# apical tuft
self.ncfrom_extinput.append(
self.parconnect_from_src(gid_src, nc_dict_ampa,
self.apicaltuft_ampa))
# Check if NMDA params defined in p_src
if 'L5Pyr_nmda' in p_src.keys():
nc_dict_nmda = {
'pos_src': pos,
'A_weight': p_src['L5Pyr_nmda'][0],
'A_delay': p_src['L5Pyr_nmda'][1],
'lamtha': p_src['lamtha'],
'threshold': p_src['threshold'],
'type_src': 'ext'
}
# Proximal feed NMDA synapses
if p_src['loc'] == 'proximal':
# basal2_nmda, basal3_nmda, apicaloblique_nmda
self.ncfrom_extinput.append(
self.parconnect_from_src(
gid_src, nc_dict_nmda, self.basal2_nmda))
self.ncfrom_extinput.append(
self.parconnect_from_src(
gid_src, nc_dict_nmda, self.basal3_nmda))
self.ncfrom_extinput.append(
self.parconnect_from_src(
gid_src, nc_dict_nmda, self.apicaloblique_nmda))
# Distal feed NMDA synsapes
elif p_src['loc'] == 'distal':
# apical tuft
self.ncfrom_extinput.append(
self.parconnect_from_src(
gid_src, nc_dict_nmda, self.apicaltuft_nmda))
# one parreceive function to handle all types of external parreceives
# types must be defined explicitly here
def parreceive_ext(self, type, gid, gid_dict, pos_dict, p_ext):
if type.startswith(('evprox', 'evdist')):
if self.celltype in p_ext.keys():
gid_ev = gid + gid_dict[type][0]
nc_dict_ampa = {
'pos_src': pos_dict[type][gid],
# index 0 for ampa weight
'A_weight': p_ext[self.celltype][0],
'A_delay': p_ext[self.celltype][2], # index 2 for delay
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
nc_dict_nmda = {
'pos_src': pos_dict[type][gid],
# index 1 for nmda weight
'A_weight': p_ext[self.celltype][1],
'A_delay': p_ext[self.celltype][2], # index 2 for delay
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
if p_ext['loc'] == 'proximal':
self.ncfrom_ev.append(
self.parconnect_from_src(
gid_ev, nc_dict_ampa, self.basal2_ampa))
self.ncfrom_ev.append(
self.parconnect_from_src(
gid_ev, nc_dict_ampa, self.basal3_ampa))
self.ncfrom_ev.append(
self.parconnect_from_src(
gid_ev, nc_dict_ampa, self.apicaloblique_ampa))
# NEW: note that default/original is 0 nmda weight
# for these proximal dends
self.ncfrom_ev.append(
self.parconnect_from_src(
gid_ev, nc_dict_nmda, self.basal2_nmda))
self.ncfrom_ev.append(
self.parconnect_from_src(
gid_ev, nc_dict_nmda, self.basal3_nmda))
self.ncfrom_ev.append(
self.parconnect_from_src(
gid_ev, nc_dict_nmda, self.apicaloblique_nmda))
elif p_ext['loc'] == 'distal':
# apical tuft
self.ncfrom_ev.append(
self.parconnect_from_src(
gid_ev, nc_dict_ampa, self.apicaltuft_ampa))
self.ncfrom_ev.append(
self.parconnect_from_src(
gid_ev, nc_dict_nmda, self.apicaltuft_nmda))
elif type == 'extgauss':
# gid is this cell's gid
# gid_dict is the whole dictionary, including the
# gids of the extgauss
# pos_dict is also the pos of the extgauss (net origin)
# p_ext_gauss are the params (strength, etc.)
# doesn't matter if this doesn't do anything
# gid shift is based on L2_pyramidal cells NOT L5
# I recognize this is ugly (hack)
# gid_shift = gid_dict['extgauss'][0] - gid_dict['L2_pyramidal'][0]
if 'L5_pyramidal' in p_ext.keys():
gid_extgauss = gid + gid_dict['extgauss'][0]
nc_dict = {
'pos_src': pos_dict['extgauss'][gid],
# index 0 for ampa weight
'A_weight': p_ext['L5_pyramidal'][0],
# index 2 for delay
'A_delay': p_ext['L5_pyramidal'][2],
'lamtha': p_ext['lamtha'],
'threshold': p_ext['threshold'],
'type_src': type
}
self.ncfrom_extgauss.append(
self.parconnect_from_src(
gid_extgauss, nc_dict, self.basal2_ampa))
self.ncfrom_extgauss.append(
self.parconnect_from_src(
gid_extgauss, nc_dict, self.basal3_ampa))
self.ncfrom_extgauss.append(
self.parconnect_from_src(
gid_extgauss, nc_dict, self.apicaloblique_ampa))
elif type == 'extpois':
if self.celltype in p_ext.keys():
gid_extpois = gid + gid_dict['extpois'][0]
nc_dict = {
'pos_src': pos_dict['extpois'][gid],
# index 0 for ampa weight
'A_weight': p_ext[self.celltype][0],
# index 2 for delay
'A_delay': p_ext[self.celltype][2],
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
self.ncfrom_extpois.append(
self.parconnect_from_src(
gid_extpois, nc_dict, self.basal2_ampa))
self.ncfrom_extpois.append(
self.parconnect_from_src(
gid_extpois, nc_dict, self.basal3_ampa))
self.ncfrom_extpois.append(
self.parconnect_from_src(
gid_extpois, nc_dict, self.apicaloblique_ampa))
if p_ext[self.celltype][1] > 0.0:
# index 1 for nmda weight
nc_dict['A_weight'] = p_ext[self.celltype][1]
self.ncfrom_extpois.append(
self.parconnect_from_src(
gid_extpois, nc_dict, self.basal2_nmda))
self.ncfrom_extpois.append(
self.parconnect_from_src(
gid_extpois, nc_dict, self.basal3_nmda))
self.ncfrom_extpois.append(
self.parconnect_from_src(
gid_extpois, nc_dict, self.apicaloblique_nmda))
<file_sep>/hnn_core/tests/test_feed.py
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
from copy import deepcopy
import os.path as op
import hnn_core
from hnn_core import read_params, Network
def test_external_rhythmic_feeds():
"""Test external rhythmic feeds to proximal and distal dendrites."""
hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
params_fname = op.join(hnn_core_root, 'param', 'default.json')
params = read_params(params_fname)
# default parameters have no rhythmic inputs (distal or proximal),
params.update({'input_dist_A_weight_L2Pyr_ampa': 5.4e-5,
'input_dist_A_weight_L5Pyr_ampa': 5.4e-5,
't0_input_dist': 50,
'input_prox_A_weight_L2Pyr_ampa': 5.4e-5,
'input_prox_A_weight_L5Pyr_ampa': 5.4e-5,
't0_input_prox': 50})
with Network(deepcopy(params)) as net:
net._create_all_src()
assert len(net.extinput_list) == 2 # (distal & proximal)
for ei in net.extinput_list:
# XXX: need to rename ei.ty to 'rhythmic'
assert ei.ty == 'extinput'
assert ei.eventvec.hname().startswith('Vector')
# not sure why this is 40 for both, just test > 0
assert len(ei.eventvec.as_numpy()) > 0
# check that ei.p_ext matches params
loc = ei.p_ext['loc'][:4] # loc=prox or dist
for layer in ['L2', 'L5']:
key = 'input_{}_A_weight_{}Pyr_ampa'.format(loc, layer)
assert ei.p_ext[layer + 'Pyr_ampa'][0] == params[key]
<file_sep>/examples/plot_simulate_evoked.py
"""
===============
Simulate dipole
===============
This example demonstrates how to simulate a dipole for evoked-like
waveforms using HNN-core.
"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import os.path as op
###############################################################################
# Let us import hnn_core
import hnn_core
from hnn_core import simulate_dipole, read_params, Network
hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
###############################################################################
# Then we read the parameters file
params_fname = op.join(hnn_core_root, 'param', 'default.json')
params = read_params(params_fname)
print(params)
###############################################################################
# This is a lot of parameters! We can also filter the
# parameters using unix-style wildcard characters
print(params['L2Pyr_soma*'])
###############################################################################
# Now let's simulate the dipole
# You can simulate multiple trials in parallel by using n_jobs > 1
net = Network(params)
dpls = simulate_dipole(net, n_jobs=1, n_trials=2)
###############################################################################
# and then plot it
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 6))
for dpl in dpls:
dpl.plot(ax=axes[0], layer='agg')
net.plot_input(ax=axes[1])
###############################################################################
# Finally, we can also plot the spikes.
net.plot_spikes()
###############################################################################
# Now, let us try to make the exogenous driving inputs to the cells
# synchronous and see what happens
params.update({'sync_evinput': True})
net_sync = Network(params)
dpls_sync = simulate_dipole(net_sync, n_jobs=1, n_trials=1)
dpls_sync[0].plot()
net_sync.plot_input()
<file_sep>/hnn_core/tests/test_cell.py
import matplotlib
import os.path as op
import hnn_core
from hnn_core import read_params, Network
matplotlib.use('agg')
def test_dipole():
"""Test params object."""
hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
params_fname = op.join(hnn_core_root, 'param', 'default.json')
params = read_params(params_fname)
with Network(params) as net:
net.build()
net.cells[0].plot_voltage()
<file_sep>/CONTRIBUTING.rst
Contributions
-------------
Contributions are welcome in the form of pull requests.
Once the implementation of a piece of functionality is considered to be bug
free and properly documented (both API docs and an example script),
it can be incorporated into the master branch.
To help developing ``hnn-core``, you will need a few adjustments to your
installation as shown below.
Running tests
=============
To run the tests using `pytest`, you need to have the git cloned `hnn-core`
repository with an editable pip install::
$ git clone https://github.com/jonescompneurolab/hnn-core --depth 1
$ cd hnn-core
$ python setup.py develop
Then, install the following python packages::
$ pip install flake8 pytest pytest-cov
Updating documentation
======================
Update `doc/api.rst` and `doc/whats_new.rst` as appropriate.
Building the documentation
~~~~~~~~~~~~~~~~~~~~~~~~~~
The documentation can be built using sphinx. For that, please additionally
install the following::
$ pip install matplotlib sphinx numpydoc sphinx-gallery sphinx_bootstrap_theme pillow
You can build the documentation locally using the command::
$ cd doc/
$ make html
While MNE is not needed to install hnn-core, as a developer you will need to install it
to run all the examples and tests successfully. Please find
the installation instructions on the `MNE website <https://mne.tools/stable/install/mne_python.html>`_.
If you want to build the documentation locally without running all the examples,
use the command::
$ make html-noplot
<file_sep>/hnn_core/basket.py
"""Model for inhibitory cell class."""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
from .cell import _Cell
# Units for e: mV
# Units for gbar: S/cm^2 unless otherwise noted
class BasketSingle(_Cell):
"""Inhibitory cell class."""
def __init__(self, gid, pos, cell_name='Basket'):
self.props = self.__set_props(cell_name, pos)
_Cell.__init__(self, gid, self.props)
# store cell name for later
self.name = cell_name
# Define 3D shape and position of cell. By default neuron uses xy plane
# for height and xz plane for depth. This is opposite for model as a
# whole, but convention is followed in this function ease use of gui.
self.shape_soma()
def _biophysics(self):
self.soma.insert('hh2')
def __set_props(self, cell_name, pos):
return {
'pos': pos,
'L': 39.,
'diam': 20.,
'cm': 0.85,
'Ra': 200.,
'name': cell_name,
}
# creation of synapses
def _synapse_create(self):
# creates synapses onto this cell
self.soma_ampa = self.syn_ampa_create(self.soma(0.5))
self.soma_gabaa = self.syn_gabaa_create(self.soma(0.5))
self.soma_nmda = self.syn_nmda_create(self.soma(0.5))
class L2Basket(BasketSingle):
"""Class for layer 2 basket cells."""
def __init__(self, gid=-1, pos=-1):
# BasketSingle.__init__(self, pos, L, diam, Ra, cm)
# Note: Basket cell properties set in BasketSingle())
BasketSingle.__init__(self, gid, pos, 'L2Basket')
self.celltype = 'L2_basket'
self._synapse_create()
self._biophysics()
# par connect between all presynaptic cells
# no connections from L5Pyr or L5Basket to L2Baskets
def parconnect(self, gid, gid_dict, pos_dict, p):
self._connect(gid, gid_dict, pos_dict, p, 'L2_pyramidal', 'L2Pyr',
postsyns=[self.soma_ampa])
self._connect(gid, gid_dict, pos_dict, p, 'L2_basket', 'L2Basket',
lamtha=20., postsyns=[self.soma_gabaa])
# this function might make more sense as a method of net?
# par: receive from external inputs
def parreceive(self, gid, gid_dict, pos_dict, p_ext):
# for some gid relating to the input feed:
for gid_src, p_src, pos in zip(gid_dict['extinput'],
p_ext, pos_dict['extinput']):
# check if AMPA params are defined in the p_src
if 'L2Basket_ampa' in p_src.keys():
# create an nc_dict
nc_dict_ampa = {
'pos_src': pos,
'A_weight': p_src['L2Basket_ampa'][0],
'A_delay': p_src['L2Basket_ampa'][1],
'lamtha': p_src['lamtha'],
'threshold': p_src['threshold'],
'type_src': 'ext'
}
# AMPA synapse
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_ampa, self.soma_ampa))
# Check if NMDA params are defined in p_src
if 'L2Basket_nmda' in p_src.keys():
nc_dict_nmda = {
'pos_src': pos,
'A_weight': p_src['L2Basket_nmda'][0],
'A_delay': p_src['L2Basket_nmda'][1],
'lamtha': p_src['lamtha'],
'threshold': p_src['threshold'],
'type_src': 'ext'
}
# NMDA synapse
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_nmda, self.soma_nmda))
# one parreceive function to handle all types of external parreceives
# types must be defined explicitly here
def parreceive_ext(self, type, gid, gid_dict, pos_dict, p_ext):
"""Receive external inputs."""
if type.startswith(('evprox', 'evdist')):
if self.celltype in p_ext.keys():
gid_ev = gid + gid_dict[type][0]
nc_dict_ampa = {
'pos_src': pos_dict[type][gid],
# index 0 is ampa weight
'A_weight': p_ext[self.celltype][0],
'A_delay': p_ext[self.celltype][2], # index 2 is delay
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
nc_dict_nmda = {
'pos_src': pos_dict[type][gid],
# index 1 is nmda weight
'A_weight': p_ext[self.celltype][1],
'A_delay': p_ext[self.celltype][2], # index 2 is delay
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
# connections depend on location of input - why only
# for L2 basket and not L5 basket?
if p_ext['loc'] == 'proximal':
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_ampa, self.soma_ampa))
# NEW: note that default/original is 0 nmda weight for
# the soma (for prox evoked)
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_nmda, self.soma_nmda))
elif p_ext['loc'] == 'distal':
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_ampa, self.soma_ampa))
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_nmda, self.soma_nmda))
elif type == 'extgauss':
# gid is this cell's gid
# gid_dict is the whole dictionary, including the gids
# of the extgauss
# pos_list is also the pos of the extgauss (net origin)
# p_ext_gauss are the params (strength, etc.)
# I recognize this is ugly (hack)
if self.celltype in p_ext.keys():
# since gid ids are unique, then these will all be shifted.
# if order of extgauss random feeds ever matters (likely)
# then will have to preserve order
# of creation based on gid ids of the cells
# this is a dumb place to put this information
gid_extgauss = gid + gid_dict['extgauss'][0]
# gid works here because there are as many pos
# items in pos_dict['extgauss'] as there are cells
nc_dict = {
'pos_src': pos_dict['extgauss'][gid],
# index 0 is ampa weight
'A_weight': p_ext[self.celltype][0],
'A_delay': p_ext[self.celltype][1], # index 2 is delay
'lamtha': p_ext['lamtha'],
'threshold': p_ext['threshold'],
'type_src': type
}
self.ncfrom_extgauss.append(self.parconnect_from_src(
gid_extgauss, nc_dict, self.soma_ampa))
elif type == 'extpois':
if self.celltype in p_ext.keys():
gid_extpois = gid + gid_dict['extpois'][0]
nc_dict = {
'pos_src': pos_dict['extpois'][gid],
# index 0 is ampa weight
'A_weight': p_ext[self.celltype][0],
'A_delay': p_ext[self.celltype][2], # index 2 is delay
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
self.ncfrom_extpois.append(self.parconnect_from_src(
gid_extpois, nc_dict, self.soma_ampa))
if p_ext[self.celltype][1] > 0.0:
# index 1 for nmda weight
nc_dict['A_weight'] = p_ext[self.celltype][1]
self.ncfrom_extpois.append(self.parconnect_from_src(
gid_extpois, nc_dict, self.soma_nmda))
else:
print("Warning, type def not specified in L2Basket")
class L5Basket(BasketSingle):
def __init__(self, gid=-1, pos=-1):
# Note: Cell properties are set in BasketSingle()
BasketSingle.__init__(self, gid, pos, 'L5Basket')
self.celltype = 'L5_basket'
self._synapse_create()
self._biophysics()
# connections FROM other cells TO this cell
# there are no connections from the L2Basket cells. congrats!
def parconnect(self, gid, gid_dict, pos_dict, p):
self._connect(gid, gid_dict, pos_dict, p, 'L5_basket', 'L5Basket',
lamtha=20., autapses=False,
postsyns=[self.soma_gabaa])
self._connect(gid, gid_dict, pos_dict, p, 'L5_pyramidal', 'L5Pyr',
postsyns=[self.soma_ampa])
self._connect(gid, gid_dict, pos_dict, p, 'L2_pyramidal', 'L2Pyr',
postsyns=[self.soma_ampa])
# parallel receive function parreceive()
def parreceive(self, gid, gid_dict, pos_dict, p_ext):
"""Receive."""
for gid_src, p_src, pos in zip(gid_dict['extinput'], p_ext,
pos_dict['extinput']):
# Check if AMPA params are define in p_src
if 'L5Basket_ampa' in p_src.keys():
nc_dict_ampa = {
'pos_src': pos,
'A_weight': p_src['L5Basket_ampa'][0],
'A_delay': p_src['L5Basket_ampa'][1], # right index??
'lamtha': p_src['lamtha'],
'threshold': p_src['threshold'],
'type_src': 'ext'
}
# AMPA synapse
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_ampa, self.soma_ampa))
# Check if nmda params are define in p_src
if 'L5Basket_nmda' in p_src.keys():
nc_dict_nmda = {
'pos_src': pos,
'A_weight': p_src['L5Basket_nmda'][0],
'A_delay': p_src['L5Basket_nmda'][1], # right index??
'lamtha': p_src['lamtha'],
'threshold': p_src['threshold'],
'type_src': 'ext'
}
# NMDA synapse
self.ncfrom_extinput.append(self.parconnect_from_src(
gid_src, nc_dict_nmda, self.soma_nmda))
# one parreceive function to handle all types of external parreceives
# types must be defined explicitly here
def parreceive_ext(self, type, gid, gid_dict, pos_dict, p_ext):
"""Recieve external inputs."""
# shouldn't this just check for evprox?
if type.startswith(('evprox', 'evdist')):
if self.celltype in p_ext.keys():
gid_ev = gid + gid_dict[type][0]
nc_dict_ampa = {
'pos_src': pos_dict[type][gid],
# index 0 is ampa weight
'A_weight': p_ext[self.celltype][0],
'A_delay': p_ext[self.celltype][2], # index 2 is delay
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
nc_dict_nmda = {
'pos_src': pos_dict[type][gid],
# index 1 is nmda weight
'A_weight': p_ext[self.celltype][1],
'A_delay': p_ext[self.celltype][2], # index 2 is delay
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_ampa, self.soma_ampa))
# NEW: note that default/original is 0 nmda weight
# for the soma (both prox and distal evoked)
self.ncfrom_ev.append(self.parconnect_from_src(
gid_ev, nc_dict_nmda, self.soma_nmda))
elif type == 'extgauss':
# gid is this cell's gid
# gid_dict is the whole dictionary, including the gids
# of the extgauss
# pos_dict is also the pos of the extgauss (net origin)
# p_ext_gauss are the params (strength, etc.)
if 'L5_basket' in p_ext.keys():
gid_extgauss = gid + gid_dict['extgauss'][0]
nc_dict = {
'pos_src': pos_dict['extgauss'][gid],
# index 0 is ampa weight
'A_weight': p_ext['L5_basket'][0],
'A_delay': p_ext['L5_basket'][2], # index 2 is delay
'lamtha': p_ext['lamtha'],
'threshold': p_ext['threshold'],
'type_src': type
}
self.ncfrom_extgauss.append(self.parconnect_from_src(
gid_extgauss, nc_dict, self.soma_ampa))
elif type == 'extpois':
if self.celltype in p_ext.keys():
gid_extpois = gid + gid_dict['extpois'][0]
nc_dict = {
'pos_src': pos_dict['extpois'][gid],
# index 0 is ampa weight
'A_weight': p_ext[self.celltype][0],
'A_delay': p_ext[self.celltype][2], # index 2 is delay
'lamtha': p_ext['lamtha_space'],
'threshold': p_ext['threshold'],
'type_src': type
}
self.ncfrom_extpois.append(self.parconnect_from_src(
gid_extpois, nc_dict, self.soma_ampa))
if p_ext[self.celltype][1] > 0.0:
# index 1 for nmda weight
nc_dict['A_weight'] = p_ext[self.celltype][1]
self.ncfrom_extpois.append(self.parconnect_from_src(
gid_extpois, nc_dict, self.soma_nmda))
else:
print("Warning, type def not specified in L2Basket")
<file_sep>/doc/whats_new.rst
:orphan:
.. _whats_new:
What's new?
===========
.. currentmodule:: hnn_core
.. _current:
Current
-------
Changelog
~~~~~~~~~
- Add ability to simulate multiple trials in parallel using joblibs, by `Mainak Jas`_ in `#44 <https://github.com/jonescompneurolab/hnn-core/pull/44>`_
- Reader for parameter files, by `<NAME>`_ in `#80 <https://github.com/jonescompneurolab/hnn-core/pull/80>`_
- Add plotting of voltage at soma to inspect firing pattern of cells, by `Mainak Jas`_ in `#86 <https://github.com/jasmainak/hnn-core/pull/86>`_
Bug
~~~
- Fix missing autapses in network construction, by `Mainak Jas`_ in `#50 <https://github.com/jonescompneurolab/hnn-core/pull/50>`_
- Fix rhythmic input feed, by `<NAME>`_ in `#98 <https://github.com/jonescompneurolab/hnn-core/pull/98>`_
- Fix bug introduced into rhythmic input feed and add test, by `<NAME>`_ in `#102 <https://github.com/jonescompneurolab/hnn-core/pull/102>`_
API
~~~
- Make a context manager for Network class, by `Mainak Jas`_ and `Blake Caldwell`_ in `#86 <https://github.com/jasmainak/hnn-core/pull/86>`_
.. _Mainak Jas: http://jasmainak.github.io/
.. _Blake Caldwell: https://github.com/blakecaldwell
.. _<NAME>: https://github.com/rythorpe
.. _<NAME>: https://github.com/cjayb
<file_sep>/hnn_core/parallel.py
"""import NEURON module"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
from warnings import warn
from neuron import h
rank = 0
nhosts = 1
pc = h.ParallelContext(nhosts)
pc.done()
rank = int(pc.id())
cvode = h.CVode()
def create_parallel_context(n_jobs=1):
"""Create parallel context."""
rank = int(pc.id()) # rank or node number (0 will be the master)
if rank == 0:
pc.gid_clear()
def _parallel_func(func, n_jobs):
if n_jobs != 1:
try:
from joblib import Parallel, delayed
except ImportError:
warn('joblib not installed. Cannot run in parallel.')
n_jobs = 1
if n_jobs == 1:
n_jobs = 1
my_func = func
parallel = list
else:
parallel = Parallel(n_jobs)
my_func = delayed(func)
return parallel, my_func
<file_sep>/hnn_core/params.py
"""Handling of parameters."""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import json
import fnmatch
import os.path as op
from copy import deepcopy
from .params_default import get_params_default
# return number of evoked inputs (proximal, distal)
# using dictionary d (or if d is a string, first load the dictionary from
# filename d)
def _count_evoked_inputs(d):
nprox = ndist = 0
for k, v in d.items():
if k.startswith('t_'):
if k.count('evprox') > 0:
nprox += 1
elif k.count('evdist') > 0:
ndist += 1
return nprox, ndist
def _read_json(fname):
"""Read param values from a .json file.
Parameters
----------
fname : str
Full path to the file (.json)
Returns
-------
params_input : dict
Dictionary of parameters
"""
with open(fname) as json_data:
params_input = json.load(json_data)
return params_input
def _read_legacy_params(fname):
"""Read param values from a .param file (legacy).
Parameters
----------
fname : str
Full path to the file (.param)
Returns
-------
params_input : dict
Dictionary of parameters
"""
params_input = {}
with open(fname, 'r') as fp:
for line in fp.readlines():
split_line = line.lstrip().split(':')
key, value = [field.strip() for field in split_line]
try:
if '.' in value or 'e' in value:
params_input[key] = float(value)
else:
params_input[key] = int(value)
except ValueError:
params_input[key] = str(value)
return params_input
def read_params(params_fname):
"""Read param values from a file (.json or .param).
Parameters
----------
params_fname : str
Full path to the file (.param)
Returns
-------
params : an instance of Params
Params containing paramter values from file
"""
split_fname = op.splitext(params_fname)
ext = split_fname[1]
if ext == '.json':
params_dict = _read_json(params_fname)
elif ext == '.param':
params_dict = _read_legacy_params(params_fname)
else:
raise ValueError('Unrecognized extension, expected one of' +
' .json, .param. Got %s' % ext)
if len(params_dict) == 0:
raise ValueError("Failed to read parameters from file: %s" %
op.normpath(params_fname))
params = Params(params_dict)
return params
class Params(dict):
"""Params object.
Parameters
----------
params_input : dict | None
Dictionary of parameters. If None, use default parameters.
"""
def __init__(self, params_input=None):
if params_input is None:
params_input = {}
if isinstance(params_input, dict):
nprox, ndist = _count_evoked_inputs(params_input)
# create default params templated from params_input
params_default = get_params_default(nprox, ndist)
for key in params_default.keys():
if key in params_input:
self[key] = params_input[key]
else:
self[key] = params_default[key]
else:
raise ValueError('params_input must be dict or None. Got %s'
% type(params_input))
def __repr__(self):
"""Display the params nicely."""
return json.dumps(self, sort_keys=True, indent=4)
def __getitem__(self, key):
"""Return a subset of parameters."""
keys = self.keys()
if key in keys:
return dict.__getitem__(self, key)
else:
matches = fnmatch.filter(keys, key)
if len(matches) == 0:
return dict.__getitem__(self, key)
params = self.copy()
for key in keys:
if key not in matches:
params.pop(key)
return params
def __setitem__(self, key, value):
"""Set the value for a subset of parameters."""
keys = self.keys()
if key in keys:
return dict.__setitem__(self, key, value)
else:
matches = fnmatch.filter(keys, key)
if len(matches) == 0:
return dict.__setitem__(self, key, value)
for key in keys:
if key in matches:
self.update({key: value})
def copy(self):
return deepcopy(self)
def write(self, fname):
"""Write param values to a file.
Parameters
----------
fname : str
Full path to the output file (.json)
"""
with open(fname, 'w') as fp:
json.dump(self, fp)
def _feed_validate(p_ext, p_ext_d, tstop):
"""Validate external inputs that are fed to all
cells uniformly (i.e., rather than individually).
For now, this only includes rhythmic inputs.
Parameters
----------
p_ext : list
Cumulative list of dicts where each dict contains
all parameters of an extinput.
p_ext_d : dict
The extinput to validate and append to p_ext.
tstop : float
Stop time of the simulation.
Returns
-------
p_ext : list
Cumulative list of dicts with newly appended
extinput.
"""
# # reset tstop if the specified tstop exceeds the
# # simulation runtime
# if p_ext_d['tstop'] == 0:
# p_ext_d['tstop'] = tstop
if p_ext_d['tstop'] > tstop:
p_ext_d['tstop'] = tstop
# if stdev is zero, increase synaptic weights 5 fold to make
# single input equivalent to 5 simultaneous input to prevent spiking
# <<---- SN: WHAT IS THIS RULE!?!?!?
if not p_ext_d['stdev'] and p_ext_d['distribution'] != 'uniform':
for key in p_ext_d.keys():
if key.endswith('Pyr'):
p_ext_d[key] = (p_ext_d[key][0] * 5., p_ext_d[key][1])
elif key.endswith('Basket'):
p_ext_d[key] = (p_ext_d[key][0] * 5., p_ext_d[key][1])
# if L5 delay is -1, use same delays as L2 unless L2 delay is 0.1 in
# which case use 1. <<---- SN: WHAT IS THIS RULE!?!?!?
if p_ext_d['L5Pyr_ampa'][1] == -1:
for key in p_ext_d.keys():
if key.startswith('L5'):
if p_ext_d['L2Pyr'][1] != 0.1:
p_ext_d[key] = (p_ext_d[key][0], p_ext_d['L2Pyr'][1])
else:
p_ext_d[key] = (p_ext_d[key][0], 1.)
p_ext.append(p_ext_d)
return p_ext
def check_evoked_synkeys(p, nprox, ndist):
# make sure ampa,nmda gbar values are in the param dict for evoked
# inputs(for backwards compatibility)
# evoked distal target cell types
lctprox = ['L2Pyr', 'L5Pyr', 'L2Basket', 'L5Basket']
# evoked proximal target cell types
lctdist = ['L2Pyr', 'L5Pyr', 'L2Basket']
lsy = ['ampa', 'nmda'] # synapse types used in evoked inputs
for nev, pref, lct in zip([nprox, ndist], ['evprox_', 'evdist_'],
[lctprox, lctdist]):
for i in range(nev):
skey = pref + str(i + 1)
for sy in lsy:
for ct in lct:
k = 'gbar_' + skey + '_' + ct + '_' + sy
# if the synapse-specific gbar not present, use the
# existing weight for both ampa,nmda
if k not in p:
p[k] = p['gbar_' + skey + '_' + ct]
#
def check_pois_synkeys(p):
# make sure ampa,nmda gbar values are in the param dict for Poisson inputs
# (for backwards compatibility)
lct = ['L2Pyr', 'L5Pyr', 'L2Basket', 'L5Basket'] # target cell types
lsy = ['ampa', 'nmda'] # synapse types used in Poisson inputs
for ct in lct:
for sy in lsy:
k = ct + '_Pois_A_weight_' + sy
# if the synapse-specific weight not present, set it to 0 in p
if k not in p:
p[k] = 0.0
# creates the external feed params based on individual simulation params p
def create_pext(p, tstop):
"""Indexable Python list of param dicts for parallel.
Turn off individual feeds by commenting out relevant line here.
always valid, no matter the length.
Parameters
----------
p : dict
The parameters returned by ExpParams(f_psim).return_pdict()
"""
p_ext = []
# p_unique is a dict of input param types that end up going to each cell
# uniquely
p_unique = {}
# default params for proximal rhythmic inputs
feed_prox = {
'f_input': p['f_input_prox'],
't0': p['t0_input_prox'],
'tstop': p['tstop_input_prox'],
'stdev': p['f_stdev_prox'],
'L2Pyr_ampa': (p['input_prox_A_weight_L2Pyr_ampa'],
p['input_prox_A_delay_L2']),
'L2Pyr_nmda': (p['input_prox_A_weight_L2Pyr_nmda'],
p['input_prox_A_delay_L2']),
'L5Pyr_ampa': (p['input_prox_A_weight_L5Pyr_ampa'],
p['input_prox_A_delay_L5']),
'L5Pyr_nmda': (p['input_prox_A_weight_L5Pyr_nmda'],
p['input_prox_A_delay_L5']),
'L2Basket_ampa': (p['input_prox_A_weight_L2Basket_ampa'],
p['input_prox_A_delay_L2']),
'L2Basket_nmda': (p['input_prox_A_weight_L2Basket_nmda'],
p['input_prox_A_delay_L2']),
'L5Basket_ampa': (p['input_prox_A_weight_L5Basket_ampa'],
p['input_prox_A_delay_L5']),
'L5Basket_nmda': (p['input_prox_A_weight_L5Basket_nmda'],
p['input_prox_A_delay_L5']),
'events_per_cycle': p['events_per_cycle_prox'],
'prng_seedcore': int(p['prng_seedcore_input_prox']),
'distribution': p['distribution_prox'],
'lamtha': 100.,
'loc': 'proximal',
'repeats': p['repeats_prox'],
't0_stdev': p['t0_input_stdev_prox'],
'threshold': p['threshold']
}
# ensures time interval makes sense
p_ext = _feed_validate(p_ext, feed_prox, tstop)
# default params for distal rhythmic inputs
feed_dist = {
'f_input': p['f_input_dist'],
't0': p['t0_input_dist'],
'tstop': p['tstop_input_dist'],
'stdev': p['f_stdev_dist'],
'L2Pyr_ampa': (p['input_dist_A_weight_L2Pyr_ampa'],
p['input_dist_A_delay_L2']),
'L2Pyr_nmda': (p['input_dist_A_weight_L2Pyr_nmda'],
p['input_dist_A_delay_L2']),
'L5Pyr_ampa': (p['input_dist_A_weight_L5Pyr_ampa'],
p['input_dist_A_delay_L5']),
'L5Pyr_nmda': (p['input_dist_A_weight_L5Pyr_nmda'],
p['input_dist_A_delay_L5']),
'L2Basket_ampa': (p['input_dist_A_weight_L2Basket_ampa'],
p['input_dist_A_delay_L2']),
'L2Basket_nmda': (p['input_dist_A_weight_L2Basket_nmda'],
p['input_dist_A_delay_L2']),
'events_per_cycle': p['events_per_cycle_dist'],
'prng_seedcore': int(p['prng_seedcore_input_dist']),
'distribution': p['distribution_dist'],
'lamtha': 100.,
'loc': 'distal',
'repeats': p['repeats_dist'],
't0_stdev': p['t0_input_stdev_dist'],
'threshold': p['threshold']
}
p_ext = _feed_validate(p_ext, feed_dist, tstop)
nprox, ndist = _count_evoked_inputs(p)
# print('nprox,ndist evoked inputs:', nprox, ndist)
# NEW: make sure all evoked synaptic weights present
# (for backwards compatibility)
# could cause differences between output of param files
# since some nmda weights should be 0 while others > 0
check_evoked_synkeys(p, nprox, ndist)
# Create proximal evoked response parameters
# f_input needs to be defined as 0
for i in range(nprox):
skey = 'evprox_' + str(i + 1)
p_unique['evprox' + str(i + 1)] = {
't0': p['t_' + skey],
'L2_pyramidal': (p['gbar_' + skey + '_L2Pyr_ampa'],
p['gbar_' + skey + '_L2Pyr_nmda'],
0.1, p['sigma_t_' + skey]),
'L2_basket': (p['gbar_' + skey + '_L2Basket_ampa'],
p['gbar_' + skey + '_L2Basket_nmda'],
0.1, p['sigma_t_' + skey]),
'L5_pyramidal': (p['gbar_' + skey + '_L5Pyr_ampa'],
p['gbar_' + skey + '_L5Pyr_nmda'],
1., p['sigma_t_' + skey]),
'L5_basket': (p['gbar_' + skey + '_L5Basket_ampa'],
p['gbar_' + skey + '_L5Basket_nmda'],
1., p['sigma_t_' + skey]),
'prng_seedcore': int(p['prng_seedcore_' + skey]),
'lamtha_space': 3.,
'loc': 'proximal',
'sync_evinput': p['sync_evinput'],
'threshold': p['threshold'],
'numspikes': p['numspikes_' + skey]
}
# Create distal evoked response parameters
# f_input needs to be defined as 0
for i in range(ndist):
skey = 'evdist_' + str(i + 1)
p_unique['evdist' + str(i + 1)] = {
't0': p['t_' + skey],
'L2_pyramidal': (p['gbar_' + skey + '_L2Pyr_ampa'],
p['gbar_' + skey + '_L2Pyr_nmda'],
0.1, p['sigma_t_' + skey]),
'L5_pyramidal': (p['gbar_' + skey + '_L5Pyr_ampa'],
p['gbar_' + skey + '_L5Pyr_nmda'],
0.1, p['sigma_t_' + skey]),
'L2_basket': (p['gbar_' + skey + '_L2Basket_ampa'],
p['gbar_' + skey + '_L2Basket_nmda'],
0.1, p['sigma_t_' + skey]),
'prng_seedcore': int(p['prng_seedcore_' + skey]),
'lamtha_space': 3.,
'loc': 'distal',
'sync_evinput': p['sync_evinput'],
'threshold': p['threshold'],
'numspikes': p['numspikes_' + skey]
}
# this needs to create many feeds
# (amplitude, delay, mu, sigma). ordered this way to preserve compatibility
# NEW: note double weight specification since only use ampa for gauss
# inputs
p_unique['extgauss'] = {
'stim': 'gaussian',
'L2_basket': (p['L2Basket_Gauss_A_weight'],
p['L2Basket_Gauss_A_weight'],
1., p['L2Basket_Gauss_mu'],
p['L2Basket_Gauss_sigma']),
'L2_pyramidal': (p['L2Pyr_Gauss_A_weight'],
p['L2Pyr_Gauss_A_weight'],
0.1, p['L2Pyr_Gauss_mu'], p['L2Pyr_Gauss_sigma']),
'L5_basket': (p['L5Basket_Gauss_A_weight'],
p['L5Basket_Gauss_A_weight'],
1., p['L5Basket_Gauss_mu'], p['L5Basket_Gauss_sigma']),
'L5_pyramidal': (p['L5Pyr_Gauss_A_weight'],
p['L5Pyr_Gauss_A_weight'],
1., p['L5Pyr_Gauss_mu'], p['L5Pyr_Gauss_sigma']),
'lamtha': 100.,
'prng_seedcore': int(p['prng_seedcore_extgauss']),
'loc': 'proximal',
'threshold': p['threshold']
}
check_pois_synkeys(p)
# Poisson distributed inputs to proximal
# NEW: setting up AMPA and NMDA for Poisson inputs; why delays differ?
p_unique['extpois'] = {
'stim': 'poisson',
'L2_basket': (p['L2Basket_Pois_A_weight_ampa'],
p['L2Basket_Pois_A_weight_nmda'],
1., p['L2Basket_Pois_lamtha']),
'L2_pyramidal': (p['L2Pyr_Pois_A_weight_ampa'],
p['L2Pyr_Pois_A_weight_nmda'],
0.1, p['L2Pyr_Pois_lamtha']),
'L5_basket': (p['L5Basket_Pois_A_weight_ampa'],
p['L5Basket_Pois_A_weight_nmda'],
1., p['L5Basket_Pois_lamtha']),
'L5_pyramidal': (p['L5Pyr_Pois_A_weight_ampa'],
p['L5Pyr_Pois_A_weight_nmda'],
1., p['L5Pyr_Pois_lamtha']),
'lamtha_space': 100.,
'prng_seedcore': int(p['prng_seedcore_extpois']),
't_interval': (p['t0_pois'], p['T_pois']),
'loc': 'proximal',
'threshold': p['threshold']
}
return p_ext, p_unique
# Takes two dictionaries (d1 and d2) and compares the keys in d1 to those in d2
# if any match, updates the (key, value) pair of d1 to match that of d2
# not real happy with variable names, but will have to do for now
def compare_dictionaries(d1, d2):
# iterate over intersection of key sets (i.e. any common keys)
for key in d1.keys() and d2.keys():
# update d1 to have same (key, value) pair as d2
d1[key] = d2[key]
return d1
# debug test function
if __name__ == '__main__':
fparam = 'param/debug.param'
<file_sep>/examples/README.txt
hnn-core examples
-------------------
Some introductory examples to get started with hnn-core
<file_sep>/doc/api.rst
:orphan:
.. _api_documentation:
=================
API Documentation
=================
Simulation (:py:mod:`hnn_core`):
.. currentmodule:: hnn_core
.. autosummary::
:toctree: generated/
L2Pyr
L5Pyr
L2Basket
L5Basket
ExtFeed
simulate_dipole
Network
.. currentmodule:: hnn_core.params
.. autosummary::
:toctree: generated/
Params
read_params
<file_sep>/hnn_core/utils.py
"""Utils."""
# Authors: <NAME> <<EMAIL>>
import platform
import os.path as op
from neuron import h
def load_custom_mechanisms():
if platform.system() == 'Windows':
mech_fname = op.join(op.dirname(__file__), '..', 'mod', 'nrnmech.dll')
else:
mech_fname = op.join(op.dirname(__file__), '..', 'mod', 'x86_64',
'.libs', 'libnrnmech.so')
h.nrn_load_dll(mech_fname)
print('Loading custom mechanism files from %s' % mech_fname)
<file_sep>/examples/plot_simulate_gamma.py
"""
======================
Simulate gamma rhythms
======================
This example demonstrates how to simulate gamma rhythms using hnn-core.
Replicates: https://jonescompneurolab.github.io/hnn-tutorials/gamma/gamma
"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import os.path as op
###############################################################################
# Let us import hnn_core
import hnn_core
from hnn_core import simulate_dipole, read_params, Network
hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
###############################################################################
# Then we read the parameters file
params_fname = op.join(hnn_core_root, 'param', 'gamma_L5weak_L2weak.json')
params = read_params(params_fname)
print(params)
###############################################################################
# Now let's simulate the dipole
# You can simulate multiple trials in parallel by using n_jobs > 1
net = Network(params)
dpls = simulate_dipole(net, n_jobs=1, n_trials=1)
###############################################################################
# We can plot the time-frequency response using MNE
import numpy as np
import matplotlib.pyplot as plt
from mne.time_frequency import tfr_array_multitaper
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 6))
dpls[0].plot(ax=axes[0], layer='agg')
sfreq = 1000. / params['dt']
time_bandwidth = 4.0
freqs = np.arange(20., 100., 1.)
n_cycles = freqs / 4.
# MNE expects an array of shape (n_trials, n_channels, n_times)
data = dpls[0].dpl['agg'][None, None, :]
power = tfr_array_multitaper(data, sfreq=sfreq, freqs=freqs,
n_cycles=n_cycles,
time_bandwidth=time_bandwidth,
output='power')
# stop = params['tstop'] + params['dt'] so last point is included
times = np.arange(0, params['tstop'] + params['dt'], params['dt'])
axes[1].pcolormesh(times, freqs, power[0, 0, ...], cmap='RdBu_r')
axes[1].set_xlabel('Time (ms)')
axes[1].set_ylabel('Frequency (Hz)')
plt.xlim((0, params['tstop']))
<file_sep>/examples/plot_simulate_alpha.py
"""
====================
Simulate alpha waves
====================
This example demonstrates how to simulate alpha waves using
HNN-core.
"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import os.path as op
###############################################################################
# Let us import hnn_core
import hnn_core
from hnn_core import simulate_dipole, read_params, Network
###############################################################################
# Then we setup the directories and Neuron
hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
###############################################################################
# Then we read the default parameters file
params_fname = op.join(hnn_core_root, 'param', 'default.json')
params = read_params(params_fname)
print(params)
###############################################################################
# Now, we update a few parameters
params.update({
'dipole_scalefctr': 150000.0,
'dipole_smooth_win': 0,
'tstop': 710.0,
't0_input_prox': 2000.0,
'tstop_input_prox': 710.0,
't0_input_dist': 50.0,
'tstop_input_dist': 1001.0,
't_evprox_1': 1000,
'sigma_t_evprox_1': 2.5,
't_evprox_2': 2000.0,
'sigma_t_evprox_2': 7.0,
't_evdist_1': 2000.0,
'sigma_t_evdist_1': 6.0,
'input_dist_A_weight_L2Pyr_ampa': 5.4e-5,
'input_dist_A_weight_L5Pyr_ampa': 5.4e-5,
'sync_evinput': 1
})
###############################################################################
# And we update all the conductances gbar related to the inputs
# by using the pattern gbar_ev*
params['gbar_ev*'] = 0.0
###############################################################################
# Now let's simulate the dipole and plot it
net = Network(params)
dpl = simulate_dipole(net)
dpl[0].plot()
###############################################################################
# We can confirm that what we simulate is indeed 10 Hz activity.
import matplotlib.pyplot as plt
from scipy.signal import spectrogram
import numpy as np
sfreq = 1000. / params['dt']
n_fft = 1024 * 8
freqs, _, psds = spectrogram(
dpl[0].dpl['agg'], sfreq, window='hamming', nfft=n_fft,
nperseg=n_fft, noverlap=0)
plt.figure()
plt.plot(freqs, np.mean(psds, axis=-1))
plt.xlim((0, 40))
plt.xlabel('Frequency (Hz)')
plt.ylabel('PSD')
plt.show()
<file_sep>/hnn_core/dipole.py
"""Class to handle the dipoles."""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import numpy as np
from numpy import convolve, hamming
from .parallel import _parallel_func
def _hammfilt(x, winsz):
"""Convolve with a hamming window."""
win = hamming(winsz)
win /= sum(win)
return convolve(x, win, 'same')
def _clone_and_simulate(params, trial_idx):
from .network import Network
if trial_idx != 0:
params['prng_*'] = trial_idx
net = Network(params, n_jobs=1)
net.build()
return _simulate_single_trial(net)
def _simulate_single_trial(net):
"""Simulate one trial."""
from .parallel import rank, nhosts, pc, cvode
from neuron import h
h.load_file("stdrun.hoc")
# Now let's simulate the dipole
if rank == 0:
print("running on %d cores" % nhosts)
# global variables, should be node-independent
h("dp_total_L2 = 0.")
h("dp_total_L5 = 0.")
# Set tstop before instantiating any classes
h.tstop = net.params['tstop']
h.dt = net.params['dt'] # simulation duration and time-step
h.celsius = net.params['celsius'] # 37.0 - set temperature
# We define the arrays (Vector in numpy) for recording the signals
t_vec = h.Vector()
t_vec.record(h._ref_t) # time recording
dp_rec_L2 = h.Vector()
dp_rec_L2.record(h._ref_dp_total_L2) # L2 dipole recording
dp_rec_L5 = h.Vector()
dp_rec_L5.record(h._ref_dp_total_L5) # L5 dipole recording
# sets the default max solver step in ms (purposefully large)
pc.set_maxstep(10)
# initialize cells to -65 mV, after all the NetCon
# delays have been specified
h.finitialize()
def simulation_time():
print('Simulation time: {0} ms...'.format(round(h.t, 2)))
if rank == 0:
for tt in range(0, int(h.tstop), 10):
cvode.event(tt, simulation_time)
h.fcurrent()
# set state variables if they have been changed since h.finitialize
h.frecord_init()
# actual simulation - run the solver
pc.psolve(h.tstop)
pc.barrier()
# these calls aggregate data across procs/nodes
pc.allreduce(dp_rec_L2, 1)
# combine dp_rec on every node, 1=add contributions together
pc.allreduce(dp_rec_L5, 1)
# aggregate the currents independently on each proc
net.aggregate_currents()
# combine net.current{} variables on each proc
pc.allreduce(net.current['L5Pyr_soma'], 1)
pc.allreduce(net.current['L2Pyr_soma'], 1)
pc.barrier() # get all nodes to this place before continuing
dpl_data = np.c_[np.array(dp_rec_L2.to_python()) +
np.array(dp_rec_L5.to_python()),
np.array(dp_rec_L2.to_python()),
np.array(dp_rec_L5.to_python())]
pc.gid_clear()
pc.done()
dpl = Dipole(np.array(t_vec.to_python()), dpl_data)
if rank == 0:
if net.params['save_dpl']:
dpl.write('rawdpl.txt')
dpl.baseline_renormalize(net.params)
dpl.convert_fAm_to_nAm()
dpl.scale(net.params['dipole_scalefctr'])
dpl.smooth(net.params['dipole_smooth_win'] / h.dt)
return dpl, net.spiketimes.to_python(), net.spikegids.to_python()
def simulate_dipole(net, n_trials=1, n_jobs=1):
"""Simulate a dipole given the experiment parameters.
Parameters
----------
net : Network object
The Network object specifying how cells are
connected.
n_trials : int
The number of trials to simulate.
n_jobs : int
The number of jobs to run in parallel.
Returns
-------
dpl: list | instance of Dipole
The dipole object or list of dipole objects if n_trials > 1
"""
parallel, myfunc = _parallel_func(_clone_and_simulate, n_jobs=n_jobs)
out = parallel(myfunc(net.params, idx) for idx in range(n_trials))
dpl, spiketimes, spikegids = zip(*out)
net.spiketimes = spiketimes
net.spikegids = spikegids
return dpl
class Dipole(object):
"""Dipole class.
Parameters
----------
times : array (n_times,)
The time vector
data : array (n_times x 3)
The data. The first column represents 'agg',
the second 'L2' and the last one 'L5'
Attributes
----------
t : array
The time vector
dpl : dict of array
The dipole with keys 'agg', 'L2' and 'L5'
"""
def __init__(self, times, data): # noqa: D102
self.units = 'fAm'
self.N = data.shape[0]
self.t = times
self.dpl = {'agg': data[:, 0], 'L2': data[:, 1], 'L5': data[:, 2]}
def convert_fAm_to_nAm(self):
""" must be run after baseline_renormalization()
"""
for key in self.dpl.keys():
self.dpl[key] *= 1e-6
self.units = 'nAm'
def scale(self, fctr):
for key in self.dpl.keys():
self.dpl[key] *= fctr
return fctr
def smooth(self, winsz):
# XXX: add check to make sure self.t is
# not smaller than winsz
if winsz <= 1:
return
for key in self.dpl.keys():
self.dpl[key] = _hammfilt(self.dpl[key], winsz)
def plot(self, ax=None, layer='agg', show=True):
"""Simple layer-specific plot function.
Parameters
----------
ax : instance of matplotlib figure | None
The matplotlib axis
layer : str
The layer to plot. Can be one of
'agg', 'L2', and 'L5'
show : bool
If True, show the figure
Returns
-------
fig : instance of plt.fig
The matplotlib figure handle.
"""
import matplotlib.pyplot as plt
if ax is None:
fig, ax = plt.subplots(1, 1)
if layer in self.dpl.keys():
ax.plot(self.t, self.dpl[layer])
ax.set_xlabel('Time (ms)')
ax.set_title(layer)
if show:
plt.show()
return ax.get_figure()
def baseline_renormalize(self, params):
"""Only baseline renormalize if the units are fAm.
Parameters
----------
params : dict
The parameters
"""
if self.units != 'fAm':
print("Warning, no dipole renormalization done because units"
" were in %s" % (self.units))
return
N_pyr_x = params['N_pyr_x']
N_pyr_y = params['N_pyr_y']
# N_pyr cells in grid. This is PER LAYER
N_pyr = N_pyr_x * N_pyr_y
# dipole offset calculation: increasing number of pyr
# cells (L2 and L5, simultaneously)
# with no inputs resulted in an aggregate dipole over the
# interval [50., 1000.] ms that
# eventually plateaus at -48 fAm. The range over this interval
# is something like 3 fAm
# so the resultant correction is here, per dipole
# dpl_offset = N_pyr * 50.207
dpl_offset = {
# these values will be subtracted
'L2': N_pyr * 0.0443,
'L5': N_pyr * -49.0502
# 'L5': N_pyr * -48.3642,
# will be calculated next, this is a placeholder
# 'agg': None,
}
# L2 dipole offset can be roughly baseline shifted over
# the entire range of t
self.dpl['L2'] -= dpl_offset['L2']
# L5 dipole offset should be different for interval [50., 500.]
# and then it can be offset
# slope (m) and intercept (b) params for L5 dipole offset
# uncorrected for N_cells
# these values were fit over the range [37., 750.)
m = 3.4770508e-3
b = -51.231085
# these values were fit over the range [750., 5000]
t1 = 750.
m1 = 1.01e-4
b1 = -48.412078
# piecewise normalization
self.dpl['L5'][self.t <= 37.] -= dpl_offset['L5']
self.dpl['L5'][(self.t > 37.) & (self.t < t1)] -= N_pyr * \
(m * self.t[(self.t > 37.) & (self.t < t1)] + b)
self.dpl['L5'][self.t >= t1] -= N_pyr * \
(m1 * self.t[self.t >= t1] + b1)
# recalculate the aggregate dipole based on the baseline
# normalized ones
self.dpl['agg'] = self.dpl['L2'] + self.dpl['L5']
def write(self, fname):
"""Write dipole values to a file.
Parameters
----------
fname : str
Full path to the output file (.txt)
"""
X = np.r_[[self.t, self.dpl['agg'], self.dpl['L2'], self.dpl['L5']]].T
np.savetxt('dpl2.txt', X, fmt=['%3.3f', '%5.4f', '%5.4f', '%5.4f'],
delimiter='\t')
<file_sep>/examples/plot_firing_pattern.py
"""
===================
Plot firing pattern
===================
This example demonstrates how to inspect the firing
pattern of cells in the HNN model.
"""
# Authors: <NAME> <<EMAIL>>
import os.path as op
###############################################################################
# Let us import hnn_core
import hnn_core
from hnn_core import read_params, Network
hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
###############################################################################
# Then we read the parameters file
params_fname = op.join(hnn_core_root, 'param', 'default.json')
params = read_params(params_fname)
###############################################################################
# Now let's build the network
import matplotlib.pyplot as plt
with Network(params) as net:
net.build()
# The cells are stored in the network object as a list
cells = net.cells
print(cells[:5])
# We have different kinds of cells with different cell IDs (gids)
gids = [0, 35, 135, 170]
for gid in gids:
print(cells[gid].name)
# We can plot the firing pattern of individual cells
net.cells[0].plot_voltage()
plt.title('%s (gid=%d)' % (cells[0].name, gid))
###############################################################################
# Let's do this for the rest of the cell types with a new Network object
with Network(params) as net:
net.build()
fig, axes = plt.subplots(1, 2, sharey=True, figsize=(8, 4))
for gid, ax in zip([35, 170], axes):
net.cells[gid].plot_voltage(ax)
ax.set_title('%s (gid=%d)' % (cells[gid].name, gid))
<file_sep>/hnn_core/tests/test_dipole.py
import matplotlib
import os.path as op
import numpy as np
import hnn_core
from hnn_core import read_params
from hnn_core.dipole import Dipole
matplotlib.use('agg')
def test_dipole():
"""Test params object."""
hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
params_fname = op.join(hnn_core_root, 'param', 'default.json')
params = read_params(params_fname)
times = np.random.random(6000)
data = np.random.random((6000, 3))
dipole = Dipole(times, data)
dipole.baseline_renormalize(params)
dipole.convert_fAm_to_nAm()
dipole.scale(params['dipole_scalefctr'])
dipole.smooth(params['dipole_smooth_win'] / params['dt'])
dipole.plot(layer='agg')
dipole.write('/tmp/dpl1.txt')
<file_sep>/hnn_core/cell.py
"""Establish class def for general cell features."""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import numpy as np
from neuron import h
# global variables, should be node-independent
h("dp_total_L2 = 0.")
h("dp_total_L5 = 0.") # put here since these variables used in cells
# Units for e: mV
# Units for gbar: S/cm^2
class _Cell(object):
"""Create a cell object.
Parameters
----------
gid : int
The cell ID
soma_props : dict
The properties of the soma. Must contain
keys 'L', 'diam', and 'pos'
Attributes
----------
pos : list of length 3
The position of the cell.
"""
def __init__(self, gid, soma_props):
self.gid = gid
# variable for the list_IClamp
self.list_IClamp = None
self.soma_props = soma_props
self.create_soma()
# par: create arbitrary lists of connections FROM other cells
# TO this cell instantiation
# these lists are allowed to be empty
# this should be a dict
self.ncfrom_L2Pyr = []
self.ncfrom_L2Basket = []
self.ncfrom_L5Pyr = []
self.ncfrom_L5Basket = []
self.ncfrom_extinput = []
self.ncfrom_extgauss = []
self.ncfrom_extpois = []
self.ncfrom_ev = []
def __repr__(self):
class_name = self.__class__.__name__
soma_props = self.soma_props
s = ('soma: L %f, diam %f, Ra %f, cm %f' %
(soma_props['L'], soma_props['diam'],
soma_props['Ra'], soma_props['cm']))
return '<%s | %s>' % (class_name, s)
def create_soma(self):
"""Create soma and set geometry."""
# make L_soma and diam_soma elements of self
# Used in shape_change() b/c func clobbers self.soma.L, self.soma.diam
soma_props = self.soma_props
self.L = soma_props['L']
self.diam = soma_props['diam']
self.pos = soma_props['pos']
self.soma = h.Section(cell=self, name=soma_props['name'] + '_soma')
self.soma.L = soma_props['L']
self.soma.diam = soma_props['diam']
self.soma.Ra = soma_props['Ra']
self.soma.cm = soma_props['cm']
def get_sections(self):
"""Get sections."""
return [self.soma]
def get3dinfo(self):
"""Get 3d info."""
ls = self.get_sections()
lx, ly, lz, ldiam = [], [], [], []
for s in ls:
for i in range(s.n3d()):
lx.append(s.x3d(i))
ly.append(s.y3d(i))
lz.append(s.z3d(i))
ldiam.append(s.diam3d(i))
return lx, ly, lz, ldiam
def getbbox(self):
"""Get cell's bounding box."""
lx, ly, lz, ldiam = self.get3dinfo()
minx, miny, minz = 1e9, 1e9, 1e9
maxx, maxy, maxz = -1e9, -1e9, -1e9
for x, y, z in zip(lx, ly, lz):
minx = min(x, minx)
miny = min(y, miny)
minz = min(z, minz)
maxx = max(x, maxx)
maxy = max(y, maxy)
maxz = max(z, maxz)
return ((minx, maxx), (miny, maxy), (minz, maxz))
def translate3d(self, dx, dy, dz):
"""Translate 3d."""
for s in self.get_sections():
for i in range(s.n3d()):
h.pt3dchange(i, s.x3d(i) + dx, s.y3d(i) + dy,
s.z3d(i) + dz, s.diam3d(i), sec=s)
def translate_to(self, x, y, z):
"""Translate to position."""
x0 = self.soma.x3d(0)
y0 = self.soma.y3d(0)
z0 = self.soma.z3d(0)
dx = x - x0
dy = y - y0
dz = z - z0
# print('dx:',dx,'dy:',dy,'dz:',dz)
self.translate3d(dx, dy, dz)
def move_to_pos(self):
"""Move cell to position."""
self.translate_to(self.pos[0] * 100, self.pos[2], self.pos[1] * 100)
def _connect(self, gid, gid_dict, pos_dict, p, type_src, name_src,
lamtha=3., receptor=None, postsyns=None, autapses=True):
for gid_src, pos in zip(gid_dict[type_src],
pos_dict[type_src]):
if not autapses and gid_src == gid:
continue
if receptor is not None:
A_weight = p['gbar_%s_%s_%s' %
(name_src, self.name, receptor)]
else:
A_weight = p['gbar_%s_%s' % (name_src, self.name)]
nc_dict = {
'pos_src': pos,
'A_weight': A_weight,
'A_delay': 1.,
'lamtha': lamtha,
'threshold': p['threshold'],
'type_src': type_src
}
for postsyn in postsyns:
getattr(self, 'ncfrom_%s' % name_src).append(
self.parconnect_from_src(
gid_src, nc_dict, postsyn))
# two things need to happen here for h:
# 1. dipole needs to be inserted into each section
# 2. a list needs to be created with a Dipole (Point Process) in each
# section at position 1
# In Cell() and not Pyr() for future possibilities
def dipole_insert(self, yscale):
"""Insert dipole into each section of this cell."""
# dends must have already been created!!
# it's easier to use wholetree here, this includes soma
seclist = h.SectionList()
seclist.wholetree(sec=self.soma)
# create a python section list list_all
self.list_all = [sec for sec in seclist]
for sect in self.list_all:
sect.insert('dipole')
# Dipole is defined in dipole_pp.mod
self.dipole_pp = [h.Dipole(1, sec=sect) for sect in self.list_all]
# setting pointers and ztan values
for sect, dpp in zip(self.list_all, self.dipole_pp):
# assign internal resistance values to dipole point process (dpp)
dpp.ri = h.ri(1, sec=sect)
# sets pointers in dipole mod file to the correct locations
# h.setpointer(ref, ptr, obj)
h.setpointer(sect(0.99)._ref_v, 'pv', dpp)
if self.celltype.startswith('L2'):
h.setpointer(h._ref_dp_total_L2, 'Qtotal', dpp)
elif self.celltype.startswith('L5'):
h.setpointer(h._ref_dp_total_L5, 'Qtotal', dpp)
# gives INTERNAL segments of the section, non-endpoints
# creating this because need multiple values simultaneously
loc = np.array([seg.x for seg in sect])
# these are the positions, including 0 but not L
pos = np.array([seg.x for seg in sect.allseg()])
# diff in yvals, scaled against the pos np.array. y_long as
# in longitudinal
y_scale = (yscale[sect.name()] * sect.L) * pos
# y_long = (h.y3d(1, sec=sect) - h.y3d(0, sec=sect)) * pos
# diff values calculate length between successive section points
y_diff = np.diff(y_scale)
# y_diff = np.diff(y_long)
# doing range to index multiple values of the same
# np.array simultaneously
for i in range(len(loc)):
# assign the ri value to the dipole
sect(loc[i]).dipole.ri = h.ri(loc[i], sec=sect)
# range variable 'dipole'
# set pointers to previous segment's voltage, with
# boundary condition
if i:
h.setpointer(sect(loc[i - 1])._ref_v,
'pv', sect(loc[i]).dipole)
else:
h.setpointer(sect(0)._ref_v, 'pv', sect(loc[i]).dipole)
# set aggregate pointers
h.setpointer(dpp._ref_Qsum, 'Qsum', sect(loc[i]).dipole)
if self.celltype.startswith('L2'):
h.setpointer(h._ref_dp_total_L2, 'Qtotal',
sect(loc[i]).dipole)
elif self.celltype.startswith('L5'):
h.setpointer(h._ref_dp_total_L5, 'Qtotal',
sect(loc[i]).dipole)
# add ztan values
sect(loc[i]).dipole.ztan = y_diff[i]
# set the pp dipole's ztan value to the last value from y_diff
dpp.ztan = y_diff[-1]
def record_current_soma(self):
"""Record current at soma."""
# a soma exists at self.soma
self.rec_i = h.Vector()
try:
# assumes that self.synapses is a dict that exists
list_syn_soma = [key for key in self.synapses.keys()
if key.startswith('soma_')]
# matching dict from the list_syn_soma keys
self.dict_currents = dict.fromkeys(list_syn_soma)
# iterate through keys and record currents appropriately
for key in self.dict_currents:
self.dict_currents[key] = h.Vector()
self.dict_currents[key].record(self.synapses[key]._ref_i)
except:
print(
"Warning in Cell(): record_current_soma() was called,"
" but no self.synapses dict was found")
pass
# General fn that creates any Exp2Syn synapse type
# requires dictionary of synapse properties
def syn_create(self, secloc, p):
"""Create an h.Exp2Syn synapse.
Parameters
----------
p : dict
Should contain keys
- 'e' (reverse potential)
- 'tau1' (rise time)
- 'tau2' (decay time)
Returns
-------
syn : instance of h.Exp2Syn
A two state kinetic scheme synapse.
"""
syn = h.Exp2Syn(secloc)
syn.e = p['e']
syn.tau1 = p['tau1']
syn.tau2 = p['tau2']
return syn
# For all synapses, section location 'secloc' is being explicitly supplied
# for clarity, even though they are (right now) always 0.5.
# Might change in future
# creates a RECEIVING inhibitory synapse at secloc
def syn_gabaa_create(self, secloc):
"""Create gabaa receiving synapse.
Parameters
----------
secloc : float (0 to 1.0)
The section location
"""
syn_gabaa = h.Exp2Syn(secloc)
syn_gabaa.e = -80
syn_gabaa.tau1 = 0.5
syn_gabaa.tau2 = 5.
return syn_gabaa
# creates a RECEIVING slow inhibitory synapse at secloc
# called: self.soma_gabab = syn_gabab_create(self.soma(0.5))
def syn_gabab_create(self, secloc):
"""Create gabab receiving synapse.
Parameters
----------
secloc : float (0 to 1.0)
The section location.
"""
syn_gabab = h.Exp2Syn(secloc)
syn_gabab.e = -80
syn_gabab.tau1 = 1
syn_gabab.tau2 = 20.
return syn_gabab
# creates a RECEIVING excitatory synapse at secloc
# def syn_ampa_create(self, secloc, tau_decay, prng_obj):
def syn_ampa_create(self, secloc):
"""Create ampa receiving synapse.
Parameters
----------
secloc : float (0 to 1.0)
The section location.
"""
syn_ampa = h.Exp2Syn(secloc)
syn_ampa.e = 0.
syn_ampa.tau1 = 0.5
syn_ampa.tau2 = 5.
return syn_ampa
# creates a RECEIVING nmda synapse at secloc
# this is a pretty fast NMDA, no?
def syn_nmda_create(self, secloc):
"""Create nmda receiving synapse.
Parameters
----------
secloc : float (0 to 1.0)
The section location.
"""
syn_nmda = h.Exp2Syn(secloc)
syn_nmda.e = 0.
syn_nmda.tau1 = 1.
syn_nmda.tau2 = 20.
return syn_nmda
def connect_to_target(self, target, threshold):
"""Connect_to_target created for pc, used in Network()
these are SOURCES of spikes.
Parameters
----------
target : POINT_PROCESS | ARTIFICIAL_CELL | None
The target passed to connect to using h.NetCon
threshold : float
The voltage threshold for action potential.
"""
nc = h.NetCon(self.soma(0.5)._ref_v, target, sec=self.soma)
nc.threshold = threshold
return nc
def parconnect_from_src(self, gid_presyn, nc_dict, postsyn):
"""Parallel receptor-centric connect FROM presyn TO this cell,
based on GID.
Parameters
----------
gid_presyn : int
The cell ID of the presynaptic neuron
nc_dict : dict
Dictionary with keys: pos_src, A_weight, A_delay, lamtha
Defines the connection parameters
postsyn : str
The postsynaptic cell object.
Returns
-------
nc : instance of h.NetCon
A network connection object.
"""
from .parallel import pc
nc = pc.gid_connect(gid_presyn, postsyn)
# calculate distance between cell positions with pardistance()
d = self._pardistance(nc_dict['pos_src'])
# set props here
nc.threshold = nc_dict['threshold']
nc.weight[0] = nc_dict['A_weight'] * \
np.exp(-(d**2) / (nc_dict['lamtha']**2))
nc.delay = nc_dict['A_delay'] / \
(np.exp(-(d**2) / (nc_dict['lamtha']**2)))
return nc
# pardistance function requires pre position, since it is
# calculated on POST cell
def _pardistance(self, pos_pre):
dx = self.pos[0] - pos_pre[0]
dy = self.pos[1] - pos_pre[1]
return np.sqrt(dx**2 + dy**2)
def shape_soma(self):
"""Define 3D shape of soma.
.. warning:: needed for gui representation of cell
DO NOT need to call h.define_shape() explicitly!
"""
h.pt3dclear(sec=self.soma)
# h.ptdadd(x, y, z, diam) -- if this function is run, clobbers
# self.soma.diam set above
h.pt3dadd(0, 0, 0, self.diam, sec=self.soma)
h.pt3dadd(0, self.L, 0, self.diam, sec=self.soma)
def plot_voltage(self, ax=None, delay=2, duration=100, dt=0.2,
amplitude=1, show=True):
"""Plot voltage on soma for an injected current
Parameters
----------
ax : instance of matplotlib axis | None
An axis object from matplotlib. If None,
a new figure is created.
delay : float (in ms)
The start time of the injection current.
duration : float (in ms)
The duration of the injection current.
dt : float (in ms)
The integration time step
amplitude : float (in nA)
The amplitude of the injection current.
show : bool
Call plt.show() if True. Set to False if working in
headless mode (e.g., over a remote connection).
"""
import matplotlib.pyplot as plt
from neuron import h
h.load_file('stdrun.hoc')
soma = self.soma
h.tstop = duration
h.dt = dt
h.celsius = 37
iclamp = h.IClamp(soma(0.5))
iclamp.delay = delay
iclamp.dur = duration
iclamp.amp = amplitude
v_membrane = h.Vector().record(self.soma(0.5)._ref_v)
times = h.Vector().record(h._ref_t)
print('Simulating soma voltage')
h.finitialize()
def simulation_time():
print('Simulation time: {0} ms...'.format(round(h.t, 2)))
for tt in range(0, int(h.tstop), 10):
h.CVode().event(tt, simulation_time)
h.continuerun(duration)
print('[Done]')
if ax is None:
fig, ax = plt.subplots(1, 1)
ax.plot(times, v_membrane)
ax.set_xlabel('Time (ms)')
ax.set_ylabel('Voltage (mV)')
if show:
plt.show()
<file_sep>/Makefile
# Makefile for model - compiles mod files for use by NEURON
# first rev: (SL: created)
# make rules
all: modl
modl:
cd $(PWD)/mod/ && nrnivmodl
# clean
.PHONY: clean
clean :
rm -f x86_64/*
<file_sep>/hnn_core/__init__.py
from .utils import load_custom_mechanisms
load_custom_mechanisms()
from .dipole import simulate_dipole
from .feed import ExtFeed
from .params import Params, read_params
from .network import Network
from .pyramidal import L2Pyr, L5Pyr
from .basket import L2Basket, L5Basket
| 0e50e0970cc9f6f6b9faabca84b807cea824b403 | [
"Makefile",
"Python",
"Text",
"reStructuredText"
]
| 26 | reStructuredText | jessfeld/hnn-core | 917aff4dac7704a3fb08a62833a8a07a38798999 | 3fcae77844fe33eb688a492d8fc3ca35ef33b9a0 |
refs/heads/master | <repo_name>Anassanjalawi/final-project2<file_sep>/app/src/main/java/com/example/aloos/finalproject2/HelperClass/Questions.java
package com.example.aloos.finalproject2.HelperClass;
import java.io.Serializable;
public class Questions implements Serializable {
private String question;
private String T_A;
private String F_A1;
private String F_A2;
private String F_A3;
private String timer;
public String getTimer() {
return timer;
}
public void setTimer(String timer) {
this.timer = timer;
}
public String getFlag() {
return Flag;
}
public void setFlag(String flag) {
Flag = flag;
}
private String Flag;
public String getF_A2() {
return F_A2;
}
public void setF_A2(String f_A2) {
F_A2 = f_A2;
}
public String getF_A1() {
return F_A1;
}
public void setF_A1(String f_A1) {
F_A1 = f_A1;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getT_A() {
return T_A;
}
public void setT_A(String t_A) {
T_A = t_A;
}
public String getF_A3() {
return F_A3;
}
public void setF_A3(String f_A3) {
F_A3 = f_A3;
}
@Override
public String toString(){
return getQuestion() + " " + getT_A() + " " + getF_A1() + " " + getF_A2() + " "+getF_A3();
}
}
<file_sep>/app/src/main/java/com/example/aloos/finalproject2/Adapters/RecycleAdapter.java
package com.example.aloos.finalproject2.Adapters;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.renderscript.RenderScript;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.aloos.finalproject2.HelperClass.ShowQuiz;
import com.example.aloos.finalproject2.R;
import com.example.aloos.finalproject2.Services.config;
import com.example.aloos.finalproject2.activites.QuastionType;
import com.example.aloos.finalproject2.activites.Showquestions;
import com.example.aloos.finalproject2.activites.Signup;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.viewitem> {
ArrayList<ShowQuiz> items;
Context context;
String quizid2;
public RecycleAdapter(Context c, ArrayList<ShowQuiz> item)
{
items=item;
context=c;
}
//The View Item part responsible for connecting the row.xml with
// each item in the RecyclerView
//make declare and initalize
class viewitem extends RecyclerView.ViewHolder
{
//Declare
TextView name,quizid,quizd;
// ImageView image;
Button btn,btn2,delete;
//initialize
public viewitem(View itemView) {
super(itemView);
name= itemView.findViewById(R.id.quiznametxt);
quizid=itemView.findViewById(R.id.quizidtxt);
delete=itemView.findViewById(R.id.del);
// image= itemView.findViewById(R.id.img);
quizd= itemView.findViewById(R.id.quizdurationtxt);
btn=itemView.findViewById(R.id.addQ);
btn2=itemView.findViewById(R.id.showquastion);
btn2.setText(R.string.myquastions);
}
}
//onCreateViewHolder used to HAndle on Clicks
@Override
public viewitem onCreateViewHolder(final ViewGroup parent, int viewType) {
//the itemView now is the row
//We will add 2 onClicks
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row, parent, false);
//this on click is for the row
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
//this on click is for the button
/* itemView.findViewById(R.id.btnBuy).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(parent.getContext(),"Sa7a wa Hana",Toast.LENGTH_SHORT).show();
Intent i=new Intent(context,A2.class);
context.startActivity(i);
}
});*/
return new viewitem(itemView);
}
//to fill each item with data from the array depending on position
@Override
public void onBindViewHolder(final viewitem holder, final int position) {
holder.name.setText(holder.name.getText().toString()+ items.get(position).getQuizname());
holder.quizid.setText(holder.quizid.getText().toString()+ items.get(position).getQuizid());
holder.quizd.setText(holder.quizd.getText().toString()+ items.get(position).getQuizduration());
quizid2 = holder.quizid.getText().toString();
holder.btn.setText(R.string.addquastion);
holder.btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String Qid = items.get(position).getQuizid();
Toast.makeText(context, items.get(position).getQuizname(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, QuastionType.class);
i.putExtra("qid", Qid);
context.startActivity(i);
}
});
holder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
quizid2=items.get(position).getQuizid();
del(position).show();
}
});
holder.btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
quizid2=items.get(position).getQuizid();
Intent i = new Intent(context, Showquestions.class);
i.putExtra("Quizidshow",quizid2);
context.startActivity(i);
}
});
}
private AlertDialog del(final int position){
Toast.makeText(context,position +"",Toast.LENGTH_SHORT).show();
AlertDialog alertDialog =new AlertDialog.Builder(context)
.setTitle("Delete")
.setMessage("Do you want to Delete")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
deleteQuiz();
items.remove(position);
notifyDataSetChanged();
dialog.dismiss();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
return alertDialog;
}
@Override
public int getItemCount() {
return items.size();
}
public void deleteQuiz(){
final ProgressDialog pd;
pd = new ProgressDialog(context);
pd.setTitle("Loading");
pd.setMessage("Please wait...");
pd.show();
RequestQueue queue = Volley.newRequestQueue(context);
String url = config.URL + "deleteQuiz.php";
StringRequest req = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
// Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
JSONObject o=new JSONObject(s);
String data=o.getString("result");
if(data.equals("1"))
{
Toast.makeText(context,"Delete Quiz Successfully",Toast.LENGTH_LONG).show();}
else
{Toast.makeText(context,"Failed",Toast.LENGTH_LONG).show();}
} catch (JSONException e) {
e.printStackTrace();
}
pd.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
pd.dismiss();
String errorDescription = "";
if( volleyError instanceof NetworkError) {
errorDescription="Network Error";
} else if( volleyError instanceof ServerError) {
errorDescription="Server Error";
} else if( volleyError instanceof AuthFailureError) {
errorDescription="AuthFailureError";
} else if( volleyError instanceof ParseError) {
errorDescription="Parse Error";
} else if( volleyError instanceof NoConnectionError) {
errorDescription="No Conenction";
} else if( volleyError instanceof TimeoutError) {
errorDescription="Time Out";
}else
{
errorDescription="Connection Error";
}
Toast.makeText(context, errorDescription,Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<String,String>();
param.put("quizid",quizid2);
return param;
}
};
req.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(req);
}
}
<file_sep>/app/src/main/java/com/example/aloos/finalproject2/activites/FinalScore.java
package com.example.aloos.finalproject2.activites;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.aloos.finalproject2.R;
import com.example.aloos.finalproject2.Services.config;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class FinalScore extends AppCompatActivity {
int score , size;
TextView txt;
String sname,sid,qid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_score);
txt = findViewById(R.id.Score);
score = getIntent().getExtras().getInt("score");
size = getIntent().getExtras().getInt("size");
sname=getIntent().getExtras().getString("sname");
sid=getIntent().getExtras().getString("sid");
qid=getIntent().getExtras().getString("qid");
txt.setText(""+score +"/" +size);
Toast.makeText(this,sname + "" + sid + ""+qid,Toast.LENGTH_SHORT).show();
setmatk();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i=new Intent(FinalScore.this,LogInActivity.class);
startActivity(i);
finish();
}
}, 3000);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK);
return false;
// Disable back button..............
}
public void setmatk(){
RequestQueue queue = Volley.newRequestQueue(FinalScore.this);
String url = config.URL + "addmark.php";
StringRequest req = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
// Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
JSONObject o=new JSONObject(s);
String data=o.getString("result");
if(data.equals("1"))
{
Toast.makeText(FinalScore.this,"submit ",Toast.LENGTH_LONG).show();}
else
{Toast.makeText(FinalScore.this,"Failed",Toast.LENGTH_LONG).show();}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
String errorDescription = "";
if( volleyError instanceof NetworkError) {
errorDescription="Network Error";
} else if( volleyError instanceof ServerError) {
errorDescription="Server Error";
} else if( volleyError instanceof AuthFailureError) {
errorDescription="AuthFailureError";
} else if( volleyError instanceof ParseError) {
errorDescription="Parse Error";
} else if( volleyError instanceof NoConnectionError) {
errorDescription="No Conenction";
} else if( volleyError instanceof TimeoutError) {
errorDescription="Time Out";
}else
{
errorDescription="Connection Error";
}
Toast.makeText(FinalScore.this, errorDescription,Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<String,String>();
param.put("stdid",sid);
param.put("stdname",sname);
param.put("score",score+"/"+size);
param.put("quizid",qid);
return param;
}
};
req.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(req);
}
}
<file_sep>/app/src/main/java/com/example/aloos/finalproject2/fragment/FillBlankFrag.java
package com.example.aloos.finalproject2.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.example.aloos.finalproject2.R;
/**
* A simple {@link Fragment} subclass.
*/
public class FillBlankFrag extends Fragment {
String Q , t;
TextView Question;
EditText answer1;
public static String answer;
public static boolean isAnswer ;
public FillBlankFrag() {
// Required empty public constructor
answer="";
isAnswer = false;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_fill_blank, container, false);
answer1= v.findViewById(R.id.answer);
Question=v.findViewById(R.id.QuestionF);
Q=getArguments().getString("Question");
t=getArguments().getString("trueanswer");
Question.setText(Q);
answer1.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
isAnswer=true;
if(answer1.getText().toString() != null)
answer = answer1.getText().toString();
else
answer = "";
}
});
return v;
}
}
<file_sep>/app/src/main/java/com/example/aloos/finalproject2/fragment/DoctorFrag.java
package com.example.aloos.finalproject2.fragment;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.aloos.finalproject2.R;
import com.example.aloos.finalproject2.Services.config;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
* A simple {@link Fragment} subclass.
*/
public class DoctorFrag extends Fragment {
TextInputEditText doctorname,doctorusername,doctorpass,doctorEmail;
public String jareer ;
ImageView doctorimg;
final int CAMERA_REQUEST = 1;
final int PICK_FROM_GALLERY = 2;
byte imageInByteGlobal[];
String encodedImage;
ProgressDialog pd;
Button doc;
public DoctorFrag() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_doctor, container, false);
doctorname=v.findViewById(R.id.doctorname);
doctorusername=v.findViewById(R.id.doctorusername);
doctorpass=v.findViewById(R.id.doctorpass);
doctorEmail=v.findViewById(R.id.doctoremail);
doctorimg=v.findViewById(R.id.studentimg);
doc = v.findViewById(R.id.DocBtn);
doc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!isValidPassword(doctorpass.getText().toString())) {
doctorpass.setError("Password must be from 8 to 24 character and Dont have special character");
}
if(!isValidEmailAddress(doctorEmail.getText().toString()))
doctorEmail.setError("Enter a Valid Email");
}
});
setManyPermissions();
doctorimg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takePicture(v);
}
});
return v;
}
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
public boolean isValidEmailAddress(String email) {
String ePattern = "^[a-zA-Z0-9_-]+@((\\[[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,}))$";
java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
java.util.regex.Matcher m = p.matcher(email);
return m.matches();
}
public static boolean isValidPassword(String s) {
Pattern PASSWORD_PATTERN
= Pattern.compile(
"[a-zA-Z0-9]{8,24}");
return !TextUtils.isEmpty(s) && PASSWORD_PATTERN.matcher(s).matches();
}
private void setManyPermissions()
{
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
if(!hasPermissions(getActivity(), PERMISSIONS)){
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, PERMISSION_ALL);
}
}
public void callCamera() {
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// i.putExtra("crop", "true");
// i.putExtra("aspectX", 0);
// i.putExtra("aspectY", 0);
// i.putExtra("outputX", 200);
// i.putExtra("outputY", 150);
startActivityForResult(i,CAMERA_REQUEST );
}
/**
* open gallery method
*/
public void callGallery() {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.putExtra("crop", "true");
i.putExtra("aspectX", 0);
i.putExtra("aspectY", 0);
i.putExtra("outputX", 200);
i.putExtra("outputY", 150);
i.putExtra("return-data", true);
startActivityForResult(
i,
PICK_FROM_GALLERY);
}
public void takePicture(View v)
{
String[] option = new String[] { "Take from Camera",
"Select from Gallery" };
ArrayAdapter<String> a = new ArrayAdapter<String>(getActivity(),
android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Option");
builder.setAdapter(a, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== Activity.RESULT_CANCELED)
{
return;
}
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap yourImage = extras.getParcelable("data");
doctorimg.setImageBitmap(yourImage);
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] =stream.toByteArray();
imageInByteGlobal=imageInByte;
String encodedString = Base64.encodeToString(imageInByte, 0);
encodedImage=encodedString;
// jareer = encodedString.toString() ;
}
break;
case PICK_FROM_GALLERY:
final Uri imageUri = data.getData();
InputStream imageStream = null;
try {
imageStream = this.getActivity().getContentResolver().openInputStream(imageUri);
jareer = imageStream.toString() ;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
doctorimg.setImageBitmap(selectedImage);
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// selectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
// byte imageInByte[] =stream.toByteArray();
// imageInByteGlobal=imageInByte;
// String encodedString = Base64.encodeToString(imageInByte, 0);
// encodedImage=encodedString;
break;
}
}
public void addDoctor()
{
pd = new ProgressDialog(getActivity());
pd.setTitle("Loading");
pd.setMessage("Please wait...");
pd.show();
RequestQueue queue = Volley.newRequestQueue(getActivity());
String url = config.URL + "addDoctor.php";
StringRequest req = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
// Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
JSONObject o=new JSONObject(s);
String data=o.getString("result");
if(data.equals("1"))
{
Toast.makeText(getActivity(),"Sign Up Successfully",Toast.LENGTH_LONG).show();}
else
{Toast.makeText(getActivity(),"Failed",Toast.LENGTH_LONG).show();}
} catch (JSONException e) {
e.printStackTrace();
}
pd.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
pd.dismiss();
String errorDescription = "";
if( volleyError instanceof NetworkError) {
errorDescription="Network Error";
} else if( volleyError instanceof ServerError) {
errorDescription="Server Error";
} else if( volleyError instanceof AuthFailureError) {
errorDescription="AuthFailureError";
} else if( volleyError instanceof ParseError) {
errorDescription="Parse Error";
} else if( volleyError instanceof NoConnectionError) {
errorDescription="No Conenction";
} else if( volleyError instanceof TimeoutError) {
errorDescription="Time Out";
}else
{
errorDescription="Connection Error";
}
Toast.makeText(getActivity(), errorDescription,Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<String,String>();
param.put("doctorname",doctorname.getText().toString());
param.put("doctorpass", doctorpass.getText().toString());
param.put("doctorid", doctorusername.getText().toString());
param.put("doctorEmail", doctorEmail.getText().toString());
param.put("studentimg", encodedImage);
return param;
}
};
req.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(req);
}
}
<file_sep>/app/src/main/java/com/example/aloos/finalproject2/fragment/FillFrag.java
package com.example.aloos.finalproject2.fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.aloos.finalproject2.Services.config;
import com.example.aloos.finalproject2.R;
import com.example.aloos.finalproject2.activites.QuastionType;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* A simple {@link Fragment} subclass.
*/
public class FillFrag extends Fragment {
TextInputEditText QuastionFill,TrueAnswerFill;
Button btn;
String Flag;
String id;
ProgressDialog pd;
public FillFrag() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_fillintheblank, container, false);
QuastionType a = new QuastionType();
FillFrag results = a.newInstance1();
a.newInstance();
if (results.getArguments() != null) {
id = results.getArguments().getString("Qid");
}
QuastionFill=v.findViewById(R.id.FillQuastion);
TrueAnswerFill=v.findViewById(R.id.FillTrueAnswer);
Flag="B";
btn=v.findViewById(R.id.btnfill);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(QuastionFill.getText().toString().equals(""))
QuastionFill.setError("Question is required");
else if (TrueAnswerFill.getText().toString().equals(""))
TrueAnswerFill.setError("True Answer Required");
else {
AddQuastions();
Toast.makeText(getActivity(), "Add Question successfully", Toast.LENGTH_SHORT).show();
TrueAnswerFill.setText("");
QuastionFill.setText("");
} }
});
return v;
}
public void AddQuastions(){
pd = new ProgressDialog(getActivity());
pd.setTitle("Loading");
pd.setMessage("Please wait...");
pd.show();
RequestQueue queue = Volley.newRequestQueue(getActivity());
String url = config.URL + "addQuastion.php";
StringRequest req = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
// Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
JSONObject o=new JSONObject(s);
String data=o.getString("result");
if(data.equals("1"))
{
Toast.makeText(getActivity(),"Add Question Successfully",Toast.LENGTH_LONG).show();}
else
{Toast.makeText(getActivity(),"Failed",Toast.LENGTH_LONG).show();}
} catch (JSONException e) {
e.printStackTrace();
}
pd.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
pd.dismiss();
String errorDescription = "";
if( volleyError instanceof NetworkError) {
errorDescription="Network Error";
} else if( volleyError instanceof ServerError) {
errorDescription="Server Error";
} else if( volleyError instanceof AuthFailureError) {
errorDescription="AuthFailureError";
} else if( volleyError instanceof ParseError) {
errorDescription="Parse Error";
} else if( volleyError instanceof NoConnectionError) {
errorDescription="No Conenction";
} else if( volleyError instanceof TimeoutError) {
errorDescription="Time Out";
}else
{
errorDescription="Connection Error";
}
Toast.makeText(getActivity(), errorDescription,Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<String,String>();
param.put("question",QuastionFill.getText().toString());
param.put("trueanswer", TrueAnswerFill.getText().toString());
param.put("flag", Flag.toString());
param.put("quizid",id.toString());
return param;
}
};
req.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(req);
}
}
<file_sep>/app/src/main/java/com/example/aloos/finalproject2/activites/LogInActivity.java
package com.example.aloos.finalproject2.activites;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.aloos.finalproject2.Services.config;
import com.example.aloos.finalproject2.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LogInActivity extends AppCompatActivity {
TextInputEditText username,password;
TextView t1 , t2;
ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
username=findViewById(R.id.username);
password=findViewById(R.id.password);
t1 = findViewById(R.id.txt);
t2=findViewById(R.id.textView);
Typeface tt = Typeface.createFromAsset(getAssets() , "fonts/abc.TTF");
t1.setTypeface(tt);
t2.setTypeface(tt);
}
public void goTosignup(View view) {
Intent i = new Intent(this,Signup.class);
startActivity(i);
}
public void Login(View view) {
getUser();
}
public void getUser()
{
pd = new ProgressDialog(this);
pd.setTitle("Loading");
pd.setMessage("Please wait...");
pd.show();
RequestQueue queue = Volley.newRequestQueue(this);
String url = config.URL + "getUser.php";
StringRequest req = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
// Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
JSONObject o = new JSONObject(s);
JSONArray arr = o.getJSONArray("result");
if(arr.length() == 0)
Toast.makeText(LogInActivity.this,"Username or Password Not correct ",Toast.LENGTH_LONG).show();
else {
JSONObject ob = arr.getJSONObject(0);
String name=ob.getString("name");
String mail=ob.getString("email");
String img = ob.getString("img");
String type = ob.getString("type");
String docid=ob.getString("id");
if (type.equals("D")) {
// Toast.makeText(LogInActivity.this, ob.getString("type")+""+name+""+mail, Toast.LENGTH_LONG).show();
Intent i = new Intent(LogInActivity.this, NavDoctor.class);
i.putExtra("Dusername",name.toString());
i.putExtra("email",mail.toString());
i.putExtra("img",img.toString());
i.putExtra("id",docid);
// byte[] decodedString = Base64.decode(img, Base64.URL_SAFE );
// i.putExtra("img",decodedString);
/* Bundle b = new Bundle();
b.putString("id",docid);
CreateQuiz_Frag fragobj= new CreateQuiz_Frag();
fragobj.setArguments(b);
startActivity(i);*/
startActivity(i);
finish();
} else if (type.equals("S")) {
Intent i = new Intent(LogInActivity.this, SolveQuiz.class);
i.putExtra("stdname",name.toString());
i.putExtra("stdid",docid.toString());
i.putExtra("stdimg",img);
startActivity(i);
finish();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
pd.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
pd.dismiss();
String errorDescription = "";
if( volleyError instanceof NetworkError) {
errorDescription="Network Error";
} else if( volleyError instanceof ServerError) {
errorDescription="Server Error";
} else if( volleyError instanceof AuthFailureError) {
errorDescription="AuthFailureError";
} else if( volleyError instanceof ParseError) {
errorDescription="Parse Error";
} else if( volleyError instanceof NoConnectionError) {
errorDescription="No Conenction";
} else if( volleyError instanceof TimeoutError) {
errorDescription="Time Out";
}else
{
errorDescription="Connection Error";
}
Toast.makeText(LogInActivity.this, errorDescription,Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<String,String>();
param.put("name",username.getText().toString());
param.put("pass", <PASSWORD>.getText().toString());
//param.put("studentimg", encodedImage);
return param;
}
};
req.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(req);
}
private AlertDialog Exit(){
AlertDialog alertDialog =new AlertDialog.Builder(LogInActivity.this)
.setTitle("Exit")
.setMessage("Do you want to Exit ?")
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
android.os.Process.killProcess(android.os.Process.myPid());
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
return alertDialog;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK)
Exit().show();
return false;
// Disable back button..............
}
}
| 6bab77faee2683c20015dad130b1fd22b54ef4a7 | [
"Java"
]
| 7 | Java | Anassanjalawi/final-project2 | a43e910b1bd040d25e518c98ec2bf6b97a7955dc | 16e3d103e7ea0006d9eecafad6a9828cdc5d2446 |
refs/heads/master | <repo_name>sayxiasama/masterSlaves<file_sep>/src/main/java/com/ago/masterslaves/config/DynamicDataSourceContextHolder.java
package com.ago.masterslaves.config;
import com.ago.masterslaves.constant.DataSourceEnum;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @ClassName: DynamicDataSourceContextHolder(动态数据源上下文保持器)
* @Describe: 该类负责处理多数据源切换
* @Data: 2020/3/1915:58
* @Author: Ago
* @Version 1.0
*/
public class DynamicDataSourceContextHolder {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);
/* 用户切换数据源时不会被其他程序修改 */
private static Lock lock = new ReentrantLock();
/* 用户轮询的计数器 */
private static int count = 0;
/* 为每个线程维护变量,以避免影响其他线程 */
private static final ThreadLocal<Object> CONTEXT_HOLDER = ThreadLocal.withInitial(DataSourceEnum.MASTER);
// /* 为每个线程维护变量,以避免影响其他线程 */
// private static final ThreadLocal<Object> CONTEXT_HOLDER = new ThreadLocal<Object>();
/* 所有数据源集合 */
public static List<Object> dataSourceKeys = Lists.newArrayList();
/* 所有从库数据源 */
public static List<Object> slavesSourceKey = Lists.newArrayList();
/**
* 选择数据源
*
* @param key
*/
public static void setKey(String key) {
CONTEXT_HOLDER.set(key);
}
/**
* 默认选择主数据源
*/
public static void userMaster() {
CONTEXT_HOLDER.set(DataSourceEnum.MASTER);
}
/**
* 轮询的方式使用从库
*/
public static void userSlavesDataSource() {
lock.lock();
try {
int dataSourceIndex = count % slavesSourceKey.size();
CONTEXT_HOLDER.set(slavesSourceKey.get(dataSourceIndex));
count++;
} catch (Exception e) {
logger.error(" change slaves fail , change master");
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static Object getDatasourceKey() {
return CONTEXT_HOLDER.get();
}
public static void clearDataSource() {
CONTEXT_HOLDER.remove();
}
public static boolean containDataSourceKey(String key) {
return dataSourceKeys.contains(key);
}
}
<file_sep>/src/main/java/com/ago/masterslaves/config/DynamicDataSourceRoute.java
package com.ago.masterslaves.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* @ClassName:DynamicDataSourceRoute
* @Describe: 数据库路由
* @Data:2020/3/1915:55
* @Author:Ago
* @Version 1.0
*/
public class DynamicDataSourceRoute extends AbstractRoutingDataSource {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRoute.class);
@Override
protected Object determineCurrentLookupKey() {
logger.info(" into dynamicDataSourceRote ----------------------------------{}",DynamicDataSourceContextHolder.getDatasourceKey());
return DynamicDataSourceContextHolder.getDatasourceKey();
}
}
<file_sep>/src/main/java/com/ago/masterslaves/service/UserService.java
package com.ago.masterslaves.service;
import com.ago.masterslaves.bean.User;
import java.util.List;
public interface UserService {
void save(User user);
void update(User user);
List<User> selectAll(User user);
List<User> selectByCondition(User user);
}
| 6c8d85a5331f7eed89f6873565d25bea5545dca0 | [
"Java"
]
| 3 | Java | sayxiasama/masterSlaves | ebe518e43b544dfeffe82950ddf41e743028e9d2 | 1d47adc589a755e4618fa3d30d60bf611d9ef815 |
refs/heads/master | <repo_name>Mkishore7/Guest_House_Online_Portal<file_sep>/login.php
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$hostname = "localhost";
$username1 = "root";
$password1 = "";
$dbname = "innovation";
$dbc = mysqli_connect($hostname, $username1, $password1, $dbname) OR die("could not connect to database, ERROR: ".mysqli_connect_error());
mysqli_set_charset($dbc, "utf8");
$query1 = "SELECT password FROM guest_users WHERE username = '$username'";
$query2 = "SELECT username FROM guest_users WHERE password = '$<PASSWORD>'";
$result1 = mysqli_query($dbc,$query1);
$result2 = mysqli_query($dbc,$query2);
$row1 = mysqli_fetch_array($result1,MYSQLI_ASSOC);
$row2 = mysqli_fetch_array($result2,MYSQLI_ASSOC);
$count1 = mysqli_num_rows($result1);
$count2 = mysqli_num_rows($result2);
if($count1==1 && $row1["password"]==$password){
echo "login successful";
}
else{
if($count1==0){
echo "username don't exist"."<br>";
}
else if($count1==1){
echo "incorrect password"."<br>";
}
}
?>
| 401299239d983634d53bba6bf1baa97d62c89502 | [
"PHP"
]
| 1 | PHP | Mkishore7/Guest_House_Online_Portal | 1fbc6a00b9e302f183ca8f582a7a48621cd09e4d | 56a81d0ecbf6bc5768ddb7ecd3e5b14348b56e25 |
refs/heads/master | <repo_name>alexanderyanque/paralelo<file_sep>/Trabajo de Pthreads 2/strtok_r.cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
const int MAX = 1000;
int threads = 2;
sem_t* sems;
void Usage(char* prog_name);
void *Tokenize(void* rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
thread_handles = (pthread_t*) new pthread_t[threads];
sems = (sem_t*) new sem_t[threads];
sem_init(&sems[0], 0, 1);
for (thread = 1; thread < threads; thread++)
sem_init(&sems[thread], 0, 0);
std::cout<<"String : "<<std::endl;
for (thread = 0; thread < threads; thread++)
pthread_create(&thread_handles[thread], (pthread_attr_t*) NULL,
Tokenize, (void*) thread);
for (thread = 0; thread < threads; thread++) {
pthread_join(thread_handles[thread], NULL);
}
for (thread=0; thread < threads; thread++)
sem_destroy(&sems[thread]);
delete[] sems;
delete[] thread_handles;
return 0;
}
void *Tokenize(void* rank) {
long my_rank = (long) rank;
int count;
int next = (my_rank + 1) % threads;
char *fg_rv;
char my_line[MAX];
char *my_string;
char *saveptr;
sem_wait(&sems[my_rank]);
fg_rv = fgets(my_line, MAX, stdin);
sem_post(&sems[next]);
while (fg_rv != NULL) {
printf("Thread %ld > my line = %s", my_rank, my_line);
count = 0;
my_string = strtok_r(my_line, " \t", &saveptr);
while ( my_string != NULL ) {
count++;
printf("Thread %ld > string %d = %s\n", my_rank, count, my_string);
my_string = strtok_r(NULL, " \t\n", &saveptr);
}
sem_wait(&sems[my_rank]);
fg_rv = fgets(my_line, MAX, stdin);
sem_post(&sems[next]);
}
return NULL;
}
<file_sep>/Trabajo de Pthreads 2/mat_array.cpp
#include <iostream>
#include <pthread.h>
#include <random>
#include <time.h>
using namespace std;
int m = 8;
int n = 8000000;
int limites = 4;
int **A;
int *x;
int *y;
int threads = 1;
void* funcion(void* rank){
long my_rank = (long) rank;
int i, j;
int local_m = m/threads;
int my_first_row = my_rank*local_m;
int my_last_row = (my_rank+1)*local_m - 1;
for (int i = my_first_row; i <= my_last_row; i++) {
y[i] = 0.0;
for (j = 0; j < n; j++)
y[i] += A[i][j]*x[j];
}
return NULL;
}
int main() {
long thread;
srand(time(NULL));
pthread_t* thread_handles;
thread_handles = new pthread_t[threads];
A = new int*[m];
for (int i = 0; i < m; ++i)
A[i] = new int[n];
x=new int[n];
y=new int[m];
for(long i=0;i<m;++i){
for(long j=0;j<n;++j){
A[i][j]=rand()%limites;
}
}
for(long i=0;i<n;++i){
x[i]=rand()%limites;
}
clock_t start = clock();
for (thread = 0; thread < threads; thread++){
pthread_create(&thread_handles[thread], NULL,
funcion, (void*) thread);
}
for (thread = 0; thread < threads; thread++)
pthread_join(thread_handles[thread], NULL);
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
delete[] thread_handles;
cout<<seconds<<endl;
for (int i = 0; i < m; ++i)
delete [] A[i];
delete[] A;
delete[] x;
delete[] y;
return 0;
}<file_sep>/Trabajo de Pthreads 1/barrier_sem.cpp
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <iostream>
#include <semaphore.h>
using namespace std;
int threads = 10;
int flag=0;
long n=10;
sem_t count_sem;
sem_t barrier_sem;
int counter=0;
void* Thread(void * rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
sem_init(&barrier_sem, 0, 0);
sem_init(&count_sem, 0, 1);
thread_handles = new pthread_t[threads];
// malloc(threads*sizeof(pthread_t));
for (thread = 0; thread < threads; thread++){
pthread_create(&thread_handles[thread], NULL,
Thread, (void*) thread);
}
// printf("hi from main\n");
clock_t start = clock();
/*Do something*/
for (thread = 0; thread < threads; thread++)
pthread_join(thread_handles[thread], NULL);
//printf("%f",sum);
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
delete[] thread_handles;
printf("%f segundos",seconds);
return 0;
}
void* Thread(void* rank){
long my_rank = (long) rank;
cout<<"hice algo #"<<my_rank<<endl;
sem_wait(&count_sem);
if (counter == threads - 1) {
counter = 0;
sem_post(&count_sem);
for (int j = 0; j < threads-1; j++)
sem_post(&barrier_sem);
}
else {
counter++;
cout<<"espero #"<<my_rank<<endl;
sem_post(&count_sem);
sem_wait(&barrier_sem);
}
cout<<"fin #"<<my_rank<<endl;
return NULL;
}<file_sep>/Trabajo de Pthreads 2/list.cpp
#include <iostream>
using namespace std;
struct node {
int data;
struct node* next;
node(){
next=NULL;
data=-1;
}
void print(){
cout<<data<<" ";
if(next!=NULL){
next->print();
}
}
};
int Member(int value, struct node* head_p) {
struct node* curr_p = head_p;
while (curr_p != NULL && curr_p->data < value)
curr_p = curr_p->next;
if (curr_p == NULL || curr_p->data > value) {
return 0;
}
else {
return 1;
}
}
int Insert(int value, struct node** head_p) {
struct node* curr_p = *head_p;
struct node* pred_p = NULL;
struct node* temp_p;
while (curr_p != NULL && curr_p->data < value) {
pred_p = curr_p;
curr_p = curr_p->next;
}
if (curr_p == NULL || curr_p->data > value) {
temp_p = new node;
temp_p->data = value;
temp_p->next = curr_p;
if (pred_p == NULL)
*head_p = temp_p;
else
pred_p->next = temp_p;
return 1;
}
else {
return 0;
}
}
int Delete(int value, struct node** head_p) {
struct node* curr_p = *head_p;
struct node* pred_p = NULL;
while (curr_p != NULL && curr_p->data < value) {
pred_p = curr_p;
curr_p = curr_p->next;
}
if (curr_p != NULL && curr_p->data == value) {
if (pred_p == NULL) {
*head_p = curr_p->next;
delete curr_p;
}
else {
pred_p->next = curr_p->next;
delete curr_p;
}
return 1;
}
else {
return 0;
}
}
void Print(struct node* head_p) {
struct node* curr_p;
printf("list = ");
curr_p = head_p;
while (curr_p != NULL) {
printf("%d ", curr_p->data);
curr_p = curr_p->next;
}
printf("\n");
}
int main() {
struct node* cabeza=NULL;
Insert(4,&cabeza);
Insert(2,&cabeza);
Insert(5,&cabeza);
Insert(3,&cabeza);
Insert(6,&cabeza);
Print(cabeza);
}<file_sep>/Trabajo de Pthreads 1/prod_cons.cpp
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <iostream>
#include <semaphore.h>
using namespace std;
#define numero 14
int threads = numero;
int flag=0;
long n=10;
sem_t count_sem;
sem_t barrier_sem;
sem_t semaphores[numero];
int counter=0;
void* Send_msg(void * rank);
char* mensajes[numero];
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
thread_handles = new pthread_t[threads];
for(int i=0;i<threads;++i){
mensajes[i]=NULL;
sem_init(&semaphores[i],0,0);
}
for (thread = 0; thread < threads; thread++){
pthread_create(&thread_handles[thread], NULL,
Send_msg, (void*) thread);
}
clock_t start = clock();
for (thread = 0; thread < threads; thread++)
pthread_join(thread_handles[thread], NULL);
//printf("%f",sum);
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
delete[] thread_handles;
// printf("%f segundos",seconds);
return 0;
}
void* Send_msg(void* rank) {
long my_rank = (long) rank;
long dest = (my_rank + 1) % threads;
char* my_msg=new char[200];
sprintf(my_msg, "Hello to %ld from %ld", dest, my_rank);
mensajes[dest] = my_msg;
sem_post(&semaphores[dest]);
sem_wait(&semaphores[my_rank]);
printf("Thread %ld > %s\n", my_rank, mensajes[my_rank]);
return NULL;
} <file_sep>/Trabajo de Pthreads 1/barrier_cond.cpp
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <iostream>
#include <semaphore.h>
using namespace std;
int threads = 6;
int flag=0;
long n=10;
pthread_mutex_t mutex;
pthread_cond_t cond_var;
int counter=0;
void* Thread(void * rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond_var,NULL);
thread_handles = new pthread_t[threads];
// malloc(threads*sizeof(pthread_t));
for (thread = 0; thread < threads; thread++){
pthread_create(&thread_handles[thread], NULL,
Thread, (void*) thread);
}
// printf("hi from main\n");
clock_t start = clock();
/*Do something*/
for (thread = 0; thread < threads; thread++)
pthread_join(thread_handles[thread], NULL);
//printf("%f",sum);
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
delete[] thread_handles;
pthread_cond_destroy(&cond_var);
pthread_mutex_destroy(&mutex);
printf("%f segundos",seconds);
return 0;
}
void* Thread(void* rank){
long my_rank = (long) rank;
cout<<"hice algo #"<<my_rank<<endl;
pthread_mutex_lock(&mutex);
counter++;
if (counter == threads) {
counter = 0;
pthread_cond_broadcast(&cond_var);
}else{
cout<<"Espero #"<<my_rank<<endl;
while (pthread_cond_wait(&cond_var, &mutex) != 0);
}
pthread_mutex_unlock(&mutex);
cout<<"fin #"<<my_rank<<endl;
return NULL;
}<file_sep>/Trabajo de Pthreads 2/list2.cpp
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <iostream>
#include <semaphore.h>
#include <random>
using namespace std;
int ops=5000;
int threads=8;
struct node* cabeza=NULL;
pthread_mutex_t list_mutex;
pthread_mutex_t head_p_mutex;
pthread_rwlock_t rwlock;
struct node {
int data;
struct node* next;
pthread_mutex_t mutex;
node(){
next=NULL;
data=-1;
pthread_mutex_init(&mutex, NULL);
}
};
int Member(int value, struct node* head_p) {
struct node* curr_p = head_p;
while (curr_p != NULL && curr_p->data < value)
curr_p = curr_p->next;
if (curr_p == NULL || curr_p->data > value) {
return 0;
}
else {
return 1;
}
}
int Member2(int value,struct node* head_p) {
struct node* curr_p;
pthread_mutex_lock(&head_p_mutex);
curr_p = head_p;
while (curr_p != NULL && curr_p->data < value) {
if (curr_p->next != NULL)
pthread_mutex_lock(&(curr_p->next->mutex));
if (curr_p == head_p)
pthread_mutex_unlock(&head_p_mutex);
pthread_mutex_unlock(&(curr_p->mutex));
curr_p = curr_p->next;
}
if (curr_p == NULL || curr_p->data > value) {
if (curr_p == head_p)
pthread_mutex_unlock(&head_p_mutex);
if (curr_p != NULL)
pthread_mutex_unlock(&(curr_p->mutex));
return 0;
}
else {
if (curr_p == head_p)
pthread_mutex_unlock(&head_p_mutex);
pthread_mutex_unlock(&(curr_p->mutex));
return 1;
}
}
int Insert(int value, struct node** head_p) {
struct node* curr_p = *head_p;
struct node* pred_p = NULL;
struct node* temp_p;
while (curr_p != NULL && curr_p->data < value) {
pred_p = curr_p;
curr_p = curr_p->next;
}
if (curr_p == NULL || curr_p->data > value) {
temp_p = new node;
temp_p->data = value;
temp_p->next = curr_p;
if (pred_p == NULL)
*head_p = temp_p;
else
pred_p->next = temp_p;
return 1;
}
else {
return 0;
}
}
int Delete(int value, struct node** head_p) {
struct node* curr_p = *head_p;
struct node* pred_p = NULL;
while (curr_p != NULL && curr_p->data < value) {
pred_p = curr_p;
curr_p = curr_p->next;
}
if (curr_p != NULL && curr_p->data == value) {
if (pred_p == NULL) {
*head_p = curr_p->next;
delete curr_p;
}
else {
pred_p->next = curr_p->next;
delete curr_p;
}
return 1;
}
else {
return 0;
}
}
void Free_list(struct node** head_pp) {
struct node* curr;
struct node* sig;
if (head_pp==NULL) return;
curr = *head_pp;
sig = curr->next;
while (sig != NULL) {
delete(curr);
curr = sig;
sig = curr->next;
}
delete(curr);
*head_pp = NULL;
}
void Print(struct node* head) {
struct node* curr;
int temp=0;
curr = head;
while (curr != NULL) {
// cout<< curr->data<<" ";
curr = curr->next;
temp++;
}
cout<<temp<<endl;
}
int def=0;
void* Accion1(void* rank) {
cout<<"mutex por lista"<<endl;
for(int i=0;i<ops/threads;++i){
int temp=rand()%10000;
int acc=rand()%10000;
long my_rank = (long) rank;
pthread_mutex_lock(&list_mutex);
if(acc<=1000)
Insert(temp,&cabeza);
else if(acc<=2000)
Delete(temp,&cabeza);
else
Member(temp,cabeza);
if(acc<=2000)def++;
pthread_mutex_unlock(&list_mutex);
}
return NULL;
}
void* Accion2(void* rank) {
cout<<"mutex por nodo"<<endl;
for(int i=0;i<ops/threads;++i){
int temp=rand()%10000;
int acc=rand()%10000;
long my_rank = (long) rank;
if(acc<=1000){
Insert(temp,&cabeza);
}
else if(acc<=2000){
Delete(temp,&cabeza);
}
else
Member2(temp,cabeza);
if(acc<=2000)def++;
}
return NULL;
}
void* Accion3(void* rank) {
//cout<<"rw_lock"<<endl;
for(int i=0;i<ops/threads;++i){
int temp=rand()%10000;
int acc=rand()%10000;
long my_rank = (long) rank;
if(acc<=1000){
pthread_rwlock_wrlock(&rwlock);
Insert(temp,&cabeza);
pthread_rwlock_unlock(&rwlock);
}
else if(acc<=2000){
pthread_rwlock_wrlock(&rwlock);
Delete(temp,&cabeza);
pthread_rwlock_unlock(&rwlock);}
else{
pthread_rwlock_rdlock(&rwlock);
Member(temp,cabeza);
pthread_rwlock_unlock(&rwlock);
}
if(acc<=2000)def++;
}
return NULL;
}
int main() {
srand(time(NULL));
long thread;
pthread_t* thread_handles;
pthread_mutex_init(&list_mutex, NULL);
pthread_rwlock_init(&rwlock,NULL);
for(int i=0;i<1000;++i){
Insert(rand()%2000,&cabeza);
}
// Print(cabeza);
thread_handles = new pthread_t[threads];
for (thread = 0; thread < threads; thread++){
pthread_create(&thread_handles[thread], NULL,
Accion3, (void*) thread);
}
clock_t start = clock();
for (thread = 0; thread < threads; thread++)
pthread_join(thread_handles[thread], NULL);
//Print(cabeza);
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
cout<<"tiempo = "<<seconds<<" segundos"<<endl;
delete[] thread_handles;
Free_list(&cabeza);
pthread_mutex_destroy(&list_mutex);
pthread_rwlock_destroy(&rwlock);
//cout<<def<<endl;
return 0;
}<file_sep>/mult_matrices/Multiplicacion_matrices.cpp
// Multiplicacion_matrices.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí.
//
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <chrono>
#define A_x 1000
#define A_y 1000
#define B_x 1000
#define B_y 1000
#define max 5
#define tam 400
using namespace std;
using namespace std::chrono;
int A[A_x][A_y];
int B[B_x][B_y];
int res[A_x][B_y];
int ser[A_x][B_y];
void set() {
for (int i = 0; i < A_x; ++i) {
for (int j = 0; j < A_y; ++j) {
A[i][j] = rand() % max;
}
}
for (int i = 0; i < B_x; ++i) {
for (int j = 0; j < B_y; ++j) {
B[i][j] = rand() % max;
}
}
return;
}
void mult_clasica() {
for (int i = 0; i < A_x; ++i) {
for (int j = 0; j < B_y; ++j) {
for (int k = 0; k < A_y; ++k) {
res[i][j] = res[i][j] + (A[i][k]*B[k][j]);
}
}
}
cout << "Resultado Mult_Clasica :" << endl;
for (int i = 0; i < A_x; ++i) {
for (int j = 0; j < B_y; ++j) {
//cout << res[i][j] << " ";
}
// cout << endl;
}
}
void mult_bloques() {
int temp;
int N = A_x;
int s = tam;
for (int jj = 0; jj < N; jj += s) {
for (int kk = 0; kk < N; kk += s) {
for (int i = 0; i < N; i++) {
for (int j = jj; j < ((jj + s) > N ? N : (jj + s)); j++) {
temp = 0;
for (int k = kk; k < ((kk + s) > N ? N : (kk + s)); k++) {
temp += A[i][k] * B[k][j];
}
ser[i][j] += temp;
}
}
}
}
cout << "Resultado Mult_Bloques :" << endl;
for (int i = 0; i < A_x; ++i) {
for (int j = 0; j < B_y; ++j) {
//cout << ser[i][j] << " ";
}
//cout << endl;
}
}
int main()
{
srand(time(NULL));
set();
auto start1 = high_resolution_clock::now();
auto stop1 = high_resolution_clock::now();
auto start2 = high_resolution_clock::now();
auto stop2 = high_resolution_clock::now();
mult_clasica();
stop1 = high_resolution_clock::now();
auto duration1 = duration_cast<microseconds>(stop1 - start1);
cout << "Time taken by function: " << duration1.count() << " microseconds" << endl;
start2 = high_resolution_clock::now();
mult_bloques();
stop2 = high_resolution_clock::now();
auto duration2 = duration_cast<microseconds>(stop2 - start2);
cout << "Time taken by function: " << duration2.count() << " microseconds" << endl;
//mult_bloques();
cout << "A : " << endl;
for (int i = 0; i < A_x; ++i) {
for (int j = 0; j < A_y; ++j) {
// cout << A[i][j] << " ";
}
// cout << endl;
}
cout << endl;
cout << "B : " << endl;
for (int i = 0; i < B_x; ++i) {
for (int j = 0; j < B_y; ++j) {
// cout << B[i][j] << " ";
}
// cout << endl;
}
cout << endl;
return 0;
}
<file_sep>/Trabajo de Pthreads 1/barrier_mutex.cpp
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <iostream>
using namespace std;
int threads = 4;
int flag=0;
long n=10;
pthread_mutex_t barrier_mutex;
int counter=0;
void* Thread(void * rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
thread_handles = new pthread_t[threads];
// malloc(threads*sizeof(pthread_t));
pthread_mutex_init(&barrier_mutex, NULL);
for (thread = 0; thread < threads; thread++){
pthread_create(&thread_handles[thread], NULL,
Thread, (void*) thread);
}
// printf("hi from main\n");
clock_t start = clock();
/*Do something*/
for (thread = 0; thread < threads; thread++)
pthread_join(thread_handles[thread], NULL);
//printf("%f",sum);
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
delete[] thread_handles;
printf("%f segundos",seconds);
pthread_mutex_destroy(&barrier_mutex);
return 0;
}
void* Thread(void* rank){
long my_rank = (long) rank;
cout<<"hice algo #"<<my_rank<<endl;
pthread_mutex_lock(&barrier_mutex);
counter++;
cout<<"espero #"<<my_rank<<endl;
pthread_mutex_unlock(&barrier_mutex);
while (counter < threads);
cout<<"fin #"<<my_rank<<endl;
return NULL;
}<file_sep>/Comparacion_For/For-Comparacion.cpp
// For-Comparacion.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí.
//
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <chrono>
#define max 7500
using namespace std;
using namespace std::chrono;
double A[max][max], x[max], y[max];
void resety() {
for (int i = 0; i < max; ++i) {
y[i] = 0;
}
return;
}
void set() {
for (int i = 0; i < max; ++i) {
double rds = (rand() % 1000 )/100.0;
x[i] = rds;
for (int j = 0; j < max; ++j) {
double rd = (rand() % 1000) / 100.0;
A[i][j] = rd;
}
}
resety();
/*for (int i = 0; i < max; ++i) {
for (int j = 0; j < max; ++j) {
cout<<A[i][j]<<" ";
}
cout << endl;
}
for (int i = 0; i < max; ++i) {
cout << x[i] << " " << y[i] << endl;
}*/
}
void for1() {
for (int i = 0; i < max; ++i) {
for (int j = 0; j < max; ++j) {
y[i] += A[i][j] * x[j];
}
}
return;
}
void for2() {
for (int j = 0; j < max; ++j) {
for (int i = 0; i < max; ++i) {
y[i] += A[i][j] * x[j];
}
}
return;
}
int main()
{
srand(time(NULL));
set();
auto start1 = high_resolution_clock::now();
auto stop1 = high_resolution_clock::now();
auto start2 = high_resolution_clock::now();
auto stop2 = high_resolution_clock::now();
for1();
stop1 = high_resolution_clock::now();
auto duration1 = duration_cast<microseconds>(stop1 - start1);
cout << "Time taken by function: " << duration1.count() << " microseconds" << endl;
resety();
start2 = high_resolution_clock::now();
for2();
stop2 = high_resolution_clock::now();
auto duration2 = duration_cast<microseconds>(stop2 - start2);
cout << "Time taken by function: " << duration2.count() << " microseconds" << endl;
return 0;
}
// Ejecutar programa: Ctrl + F5 o menú Depurar > Iniciar sin depurar
// Depurar programa: F5 o menú Depurar > Iniciar depuración
// Sugerencias para primeros pasos: 1. Use la ventana del Explorador de soluciones para agregar y administrar archivos
// 2. Use la ventana de Team Explorer para conectar con el control de código fuente
// 3. Use la ventana de salida para ver la salida de compilación y otros mensajes
// 4. Use la ventana Lista de errores para ver los errores
// 5. Vaya a Proyecto > Agregar nuevo elemento para crear nuevos archivos de código, o a Proyecto > Agregar elemento existente para agregar archivos de código existentes al proyecto
// 6. En el futuro, para volver a abrir este proyecto, vaya a Archivo > Abrir > Proyecto y seleccione el archivo .sln
<file_sep>/Trabajo de Pthreads 1/busy_mutex.cpp
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
int threads = 32;
int flag=0;
long n=10000000;
float sum;
void *Hello(void* rank);
void *Thread_sumbusy(void* rank);
void* Thread_summutex(void* rank);
pthread_mutex_t mutex;
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
thread_handles = new pthread_t[threads];
// malloc(threads*sizeof(pthread_t));
pthread_mutex_init(&mutex, NULL);
for (thread = 0; thread < threads; thread++){
//pthread_create(&thread_handles[thread], NULL,
//Thread_sumbusy, (void*) thread);
pthread_create(&thread_handles[thread], NULL,
Thread_summutex, (void*) thread);
}
// printf("hi from main\n");
clock_t start = clock();
/*Do something*/
for (thread = 0; thread < threads; thread++)
pthread_join(thread_handles[thread], NULL);
//printf("%f",sum);
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
delete[] thread_handles;
printf("%f segundos",seconds);
pthread_mutex_destroy(&mutex);
return 0;
}
void* Hello(void* rank){
long my_rank = (long) rank;
printf("Hello from thread %ld of %d\n",my_rank,threads);
return NULL;
}
void* Thread_sumbusy(void* rank) {
long my_rank = (long) rank;
double factor,mysum=0.0;
long long i;
long long my_n = n/threads;
long long my_first_i = my_n*my_rank;
long long my_last_i = my_first_i + my_n;
if (my_first_i % 2 == 0)
factor = 1.0;
else
factor = -1.0;
for (i = my_first_i; i < my_last_i; i++, factor = -factor) {
mysum += factor/(2*i+1);
}
while (flag != my_rank);
sum+=mysum;
flag = (flag+1) % threads;
return NULL;
}
void* Thread_summutex(void* rank) {
long my_rank = (long) rank;
double factor,mysum=0.0;
long long i;
long long my_n = n/threads;
long long my_first_i = my_n*my_rank;
long long my_last_i = my_first_i + my_n;
if (my_first_i % 2 == 0)
factor = 1.0;
else
factor = -1.0;
for (i = my_first_i; i < my_last_i; i++, factor = -factor) {
mysum += factor/(2*i+1);
}
pthread_mutex_lock(&mutex);
sum+=mysum;
pthread_mutex_unlock(&mutex);
flag = (flag+1) % threads;
return NULL;
} | 3ff32b8ebddfe09e801d8c179d88707c155af89e | [
"C++"
]
| 11 | C++ | alexanderyanque/paralelo | 8447b9571bd71152edadc61327f94d7f473dd004 | 444feb88f4c8443942ee957a9e8057945411bdc5 |
refs/heads/master | <repo_name>dave-abelson/BruteForce<file_sep>/README.md
# BruteForce
Breaking a specific password for a contest
<file_sep>/puzzle6.py
import itertools
import time
def cksum(v):
a = 0
b = 0
for i in range(len(v)):
a = (a + v[i]) % 0xff
b = (b + a) % 0xff
return (b << 8) | a
def subsetsum(array, num):
if num < 0:
return
if len(array) == 0:
if num == 0:
yield []
return
for solution in subsetsum(array[1:], num):
yield solution
for solution in subsetsum(array[1:], num - array[0]):
yield [array[0]] + solution
field = range(65, 91) + range(97, 123)
def evens():
for y in subsetsum(field, 765):
if len(y) != 8:
continue
for i in itertools.permutations(y):
r = 0
for a in range(len(i)):
r += (len(i) - a) * i[a]
if r % 255 != 0:
continue
yield i
def fours(t):
for x in field:
if x > t:
break
for y in range(max(65, t - x - 122 - 122), 123):
if not y in field:
continue
if x + y > t:
break
for z in range(max(65, t - x - y - 122), 123):
if not z in field:
continue
if x + y + z > t - 65:
break
yield (x, y, z, t - (x + y + z))
t = time.time()
count = 0
for x in evens():
for l in fours(875 - x[0] - x[1] - x[2] - x[3]):
if not l[3] in field:
continue
c = [x[0], l[0], x[1], l[1], x[2], l[2], x[3], l[3]]
if cksum(c) == 0xd06e:
for r in fours(778 - x[4] - x[5] - x[6] - x[7]):
if not r[3] in field:
continue
d = [x[4], r[0], x[5], r[1], x[6], r[2], x[7], r[3]]
if cksum(d) == 0xf00d:
count += 1
print ''.join(chr(a) for a in c + d), count, time.time() - t
for r in fours(523 - x[4] - x[5] - x[6]):
if not r[3] in field:
continue
d = [x[4], r[0], x[5], r[1], x[6], r[2], x[7], r[3]]
if cksum(d) == 0xf00d:
count += 1
print ''.join(chr(a) for a in c + d), count, time.time() - t
for l in fours(620 - x[0] - x[1] - x[2] - x[3]):
if not l[3] in field:
continue
c = [x[0], l[0], x[1], l[1], x[2], l[2], x[3]]
if cksum(c) == 0xd06e:
for r in fours(778 - x[4] - x[5] - x[6] - x[7]):
if not r[3] in field:
continue
d = [x[4], r[0], x[5], r[1], x[6], r[2], x[7], r[3]]
if cksum(d) == 0xf00d:
count += 1
print ''.join(chr(a) for a in c + d), count, time.time() - t
for r in fours(523 - x[4] - x[5] - x[6]):
if not r[3] in field:
continue
d = [x[4], r[0], x[5], r[1], x[6], r[2], x[7], r[3]]
if cksum(d) == 0xf00d:
count += 1
print ''.join(chr(a) for a in c + d), count, time.time() - t
<file_sep>/BruteForceFE.cpp
#include <iostream>
#include <vector>
#include <set>
#include <mutex>
#include <fstream>
#include <iterator>
#include <ctime>
#include <math.h>
#include <unistd.h>
#include <pthread.h>
using namespace std;
#define MAX_THREADS 13
struct thread_data {
string word;
long length;
vector<string>* left;
vector<string>* right;
};
struct status_data {
vector<string>* left;
vector<string>* right;
};
pthread_mutex_t left_mutex;
pthread_mutex_t right_mutex;
pthread_mutex_t finished_mutex;
int finished_threads = 0;
int cksum(string password) {
int a = 0;
int b = 0;
for (int i = 0; i < password.length(); i ++) {
a = (a + password[i]) % 0xff;
b = (b + a) % 0xff;
}
return (b << 8) | a;
}
bool validate_left(string password) {
return (cksum(password) == 0xd06e);
}
bool validate_right(string password) {
return (cksum(password) == 0xf00d);
}
char next_value(char character) {
char newChar = character + 1;
if (newChar == '[') newChar = 'a';
if (newChar == '{') newChar = 'A';
return newChar;
}
void* find_parts(void* threadarg) {
struct thread_data* data = (struct thread_data*) threadarg;
string word = data->word;
long length = data->length;
vector<string>* left = data->left;
vector<string>* right = data->right;
while (length > 0) {
int cursor = 0;
bool wrapped = true;
while (wrapped) {
if (validate_left(word)) {
pthread_mutex_lock(&left_mutex);
left->push_back(word);
pthread_mutex_unlock(&left_mutex);
}
if (validate_right(word)) {
pthread_mutex_lock(&right_mutex);
right->push_back(word);
pthread_mutex_unlock(&right_mutex);
}
char character = word[cursor];
char next_character = next_value(character);
word[cursor] = next_character;
if (next_character != 'A') wrapped = false;
cursor ++;
}
length --;
}
pthread_mutex_lock(&finished_mutex);
finished_threads ++;
pthread_mutex_unlock(&finished_mutex);
pthread_exit(NULL);
}
void* update_status(void* threadarg) {
struct status_data* data = (struct status_data*) threadarg;
vector<string>* left = data->left;
vector<string>* right = data->right;
while (finished_threads < MAX_THREADS) {
cout << "Left: " << to_string(left->size()) << ", Right: " << to_string(right->size()) << endl;
sleep(10);
}
pthread_exit(NULL);
}
int main() {
cout << "Brute forcing with " << to_string(MAX_THREADS) << " threads." << endl;
time_t start_time = time(nullptr);
cout << "Starting time: " << asctime(localtime(&start_time));
vector<string> left, right;
pthread_t threads[MAX_THREADS];
pthread_attr_t attr;
void* status;
struct thread_data td[MAX_THREADS];
int rc;
pthread_mutex_init(&left_mutex, NULL);
pthread_mutex_init(&right_mutex, NULL);
pthread_mutex_init(&finished_mutex, NULL);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
char starting_char = 'A';
int chars_per_thread = (int) ceil(52.0/MAX_THREADS);
for (int i = 0; i < MAX_THREADS; i ++) {
td[i].word = "AAAAA";
td[i].word.push_back(starting_char);
for (int j = 0; j < chars_per_thread; j ++) starting_char = next_value(starting_char);
td[i].length = chars_per_thread * pow(52, 5);
td[i].left = &left;
td[i].right = &right;
rc = pthread_create(&threads[i], NULL, find_parts, (void*)&td[i]);
if (rc) {
exit(-1);
}
}
pthread_t status_thread;
struct status_data sd;
sd.left = &left;
sd.right = &right;
rc = pthread_create(&status_thread, NULL, update_status, (void*)&sd);
if (rc) {
exit(-1);
}
pthread_attr_destroy(&attr);
for (int i = 0; i < MAX_THREADS; i ++) {
rc = pthread_join(threads[i], &status);
if (rc) {
exit(-1);
}
}
pthread_join(status_thread, &status);
cout << "Left (" << to_string(left.size()) << ") and right (" << to_string(right.size()) << ") found." << endl;
time_t found_time = time(nullptr);
cout << "Found in " << to_string(found_time - start_time) << " seconds." << endl;
ofstream left_file("./left");
ostream_iterator<string> left_iterator(left_file, "\n");
copy(left.begin(), left.end(), left_iterator);
ofstream right_file("./right");
ostream_iterator<string> right_iterator(right_file, "\n");
copy(right.begin(), right.end(), right_iterator);
vector<string> left_filtered, right_filtered;
set<int> left_found, right_found;
for (string l : left) {
string even = "";
for (int i = 0; i < l.length(); i ++) {
if (i % 2 == 0) even += l[i];
}
int ck = cksum(even);
if (left_found.find(ck) == left_found.end()) {
left_found.insert(ck);
left_filtered.push_back(l);
}
}
for (string r : right) {
string even = "";
for (int i = 0; i < r.length(); i ++) {
if (i % 2 == 0) even += r[i];
}
int ck = cksum(even);
if (right_found.find(ck) == right_found.end()) {
right_found.insert(ck);
right_filtered.push_back(r);
}
}
for (string l : left_filtered) {
for (string r : right_filtered) {
string word = l + r;
string even = "";
for (int i = 0; i < word.length(); i ++) {
if (i % 2 == 0) even += word[i];
}
if (cksum(even) == 0x0000) {
cout << "Password found: " << l << r << endl;
}
}
}
cout << "All possibilities scanned." << endl;
time_t end_time = time(nullptr);
cout << "Finished in " << to_string(end_time - start_time) << " seconds: " << asctime(localtime(&end_time));
pthread_exit(NULL);
return 0;
}
| 028f3174a16746647bdc25aeb0ffb828a9f152c5 | [
"Markdown",
"Python",
"C++"
]
| 3 | Markdown | dave-abelson/BruteForce | 231aa1da7057e8f68be78118ad75e7f6ab0e25aa | a5ac3053e2f61db85aa4371efccbf0cc1737a3da |
refs/heads/master | <repo_name>Linhos13/dtlu<file_sep>/source/symbolmap.cpp
#include "symbolmap.hpp"
#include <fstream>
#include <map>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdexcept>
namespace LinkerSupports
{
SymbolMap::SymbolMap(std::string findex_file)
{
struct stat info;
if(stat(findex_file.c_str(), &info ) != 0 )
throw std::invalid_argument ("Could not access to file " + findex_file + "\nProbably not a project dir");
else if(!S_ISREG(info.st_mode))
throw std::invalid_argument (findex_file + " is not a FILE");
std::ifstream ifs(findex_file);
function_index = new std::map<std::string, std::vector<std::string*>*>();
while(ifs.good())
{
std::string func_name;
std::string* file_name = new std::string;
ifs >> func_name >> *file_name;
if((*function_index)[func_name] == nullptr)
{
auto vec = new std::vector<std::string*>;
(*function_index)[func_name] = vec;
}
(*function_index)[func_name]->push_back(file_name);
}
ifs.close();
}
SymbolMap::~SymbolMap()
{
for(auto p : *function_index)
{
for(auto f : *(p.second))
{
delete f;
}
delete p.second;
}
delete function_index;
}
std::vector<std::string*>* SymbolMap::getFiles(std::string func_name)
{
auto r = function_index->find(func_name);
return r != function_index->end() ? r->second : nullptr;
}
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.4.3)
project(dtlu)
subdirs(source)
<file_sep>/include/symbolmap.hpp
#ifndef __SYMBOLMAP_H__
#define __SYMBOLMAP_H__
#include <vector>
#include <map>
namespace LinkerSupports
{
class SymbolMap
{
private:
std::map<std::string, std::vector<std::string*>*> *function_index;
public:
SymbolMap(std::string findex_file );
virtual ~SymbolMap();
std::vector<std::string*> *getFiles(std::string func_name);
};
}
#endif
<file_sep>/source/linkersupports.cpp
#include "linkersupports.hpp"
#include <llvm/Support/Casting.h>
#include <llvm/IR/Instruction.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/GlobalValue.h>
#include <list>
#include <memory>
#include <map>
#include <fstream>
namespace LinkerSupports
{
using namespace llvm;
std::list<llvm::Function*> getFunctions(llvm::Module* module, bool defined);
Function* getFunctionFromValue(Module* module, Value* value);
std::list<llvm::Function*> getFunctions(llvm::Module* module, bool defined)
{
auto &fl = module->getFunctionList();
std::list<llvm::Function*> l;
for (auto it = fl.begin(); it != fl.end(); ++it)
{
auto &function = *it;
if ((function.begin() == function.end()) != defined)
{
if(defined)
{
if(!function.hasInternalLinkage())
l.push_back(&function);
}
else
{
l.push_back(&function);
}
}
}
return l;
}
Function* getFunctionFromValue(Module* module, Value* value)
{
if(value == nullptr)
return nullptr;
auto strptr = value->stripPointerCasts();
if(Function* f = dyn_cast<Function>(strptr))
{
if(f != nullptr)
{
Function* pf = module->getFunction(f->getName());
return pf;
}
}
return nullptr;
}
std::list<llvm::Function*> getCalledFunctions(llvm::Function *function)
{
Module* module = function->getParent();
std::list<llvm::Function*> l;
for (auto I = function->begin(), E = function->end(); I != E; ++I)
{
for (llvm::BasicBlock::iterator i = I->begin(), ie = I->end(); i != ie; ++i)
{
//call
if (llvm::CallInst* callInst = llvm::dyn_cast<llvm::CallInst>(&*i))
{
Function* cf = callInst->getCalledFunction();
if(cf != nullptr)
{
l.push_back(cf);
for(unsigned i = 0; i < callInst->getNumArgOperands(); i++)
{
Value* v = callInst->getArgOperand(i);
Function* f = getFunctionFromValue(module, v);
if(f != nullptr)
l.push_back(f);
}
}
}
//invoke -> call
else if (llvm::InvokeInst* invokeInst = llvm::dyn_cast<llvm::InvokeInst>(&*i))
{
l.push_back(invokeInst->getCalledFunction());
}
else if(llvm::ReturnInst* returnInst = llvm::dyn_cast<llvm::ReturnInst>(&*i))
{
Value* v = returnInst->getReturnValue();
Function* f = getFunctionFromValue(module, v);
if(f != nullptr)
l.push_back(f);
}
//store pointer to func on stack
else if(llvm::StoreInst* storeInst = llvm::dyn_cast<llvm::StoreInst>(&*i))
{
Value* v = storeInst->getPointerOperand();
Function* f = getFunctionFromValue(module, v);
if(f != nullptr)
l.push_back(f);
}
//insert ptr to array or struc
else if(llvm::InsertValueInst* insertValueInst = llvm::dyn_cast<llvm::InsertValueInst>(&*i))
{
Value* v = insertValueInst->getInsertedValueOperand();
Function* f = getFunctionFromValue(module, v);
if(f != nullptr)
l.push_back(f);
}
//ptr to other value
else if(llvm::PtrToIntInst* ptrToIntInst = llvm::dyn_cast<llvm::PtrToIntInst>(&*i))
{
Value* v = ptrToIntInst->getPointerOperand();
Function* f = getFunctionFromValue(module, v);
if(f != nullptr)
l.push_back(f);
}
//bicast ?
else if(llvm::BitCastInst* bitCastInst = llvm::dyn_cast<llvm::BitCastInst>(&*i))
{
Value* v = bitCastInst->getOperand(0);
Function* f = getFunctionFromValue(module, v);
if(f != nullptr)
l.push_back(f);
}
//get ptr of ptr
else if(llvm::GetElementPtrInst* getElementPtrInst = llvm::dyn_cast<llvm::GetElementPtrInst>(&*i))
{
Value* v = getElementPtrInst->getPointerOperand();
Function* f = getFunctionFromValue(module, v);
if(f != nullptr)
l.push_back(f);
}
}
}
l.unique();
return l;
}
std::list<llvm::Function*> getDefinedFunctions(llvm::Module* module)
{
return getFunctions(module,true);
}
std::list<llvm::Function*> getNotDefinedFunctions(llvm::Module* module)
{
return getFunctions(module,false);
}
std::list<llvm::GlobalVariable*> getDefinedGlobals(llvm::Module* module)
{
auto& gl = module->getGlobalList();
std::list<llvm::GlobalVariable*> l;
for (auto it = gl.begin(); it != gl.end(); ++it)
{
auto &global = *it;
if(isInicializedAndGlobalAccessible(&global))
l.push_back(&global);
}
return l;
}
std::list<llvm::GlobalVariable*> getUsedGlobals(llvm::Function *function)
{
std::list<llvm::GlobalVariable*> l;
for (auto I = function->begin(), E = function->end(); I != E; ++I)
{
for (llvm::BasicBlock::iterator i = I->begin(), ie = I->end(); i != ie; ++i)
{
for (llvm::Value *op : i->operands())
{
auto s = recursiveGlobals(&*op);
l.splice(l.end(),s);
}
}
}
return l;
}
std::list<llvm::GlobalVariable*> recursiveGlobals(llvm::Value* op)
{
std::list<llvm::GlobalVariable*> l;
if (llvm::GlobalVariable* global = llvm::dyn_cast<llvm::GlobalVariable>(&*op))
{
l.push_back(global);
}
else if (llvm::User* inst = llvm::dyn_cast<llvm::User>(&*op))
{
for (llvm::Value *o : inst->operands())
{
auto s = recursiveGlobals(&*o);
l.splice(l.end(), s);
}
}
return l;
}
std::list<llvm::GlobalAlias*> getUsedGlobalAliases(llvm::Function *function)
{
std::list<llvm::GlobalAlias*> l;
for (auto I = function->begin(), E = function->end(); I != E; ++I)
{
for (llvm::BasicBlock::iterator i = I->begin(), ie = I->end(); i != ie; ++i)
{
for (llvm::Value *op : i->operands())
{
if (llvm::GlobalAlias* global = llvm::dyn_cast<llvm::GlobalAlias>(&*op))
{
l.push_back(global);
}
}
}
}
return l;
}
bool isDefined(llvm::Function* function)
{
return function->begin() != function->end();
}
bool isInicializedAndGlobalAccessible(llvm::GlobalVariable* global)
{
return global->hasInitializer() && !global->hasPrivateLinkage() && !global->hasInternalLinkage();
}
}
<file_sep>/source/projectlinker.cpp
#include "projectlinker.hpp"
#include "symbolmap.hpp"
#include "modulecutter.hpp"
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <algorithm>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
ModuleCutter* ProjectLinker::getOrLoadModule(std::string file_name)
{
ModuleCutter* module = findModuleByName(file_name);
if(!module)
{
module = new ModuleCutter(file_name, this);
modules.insert(module);
}
return module;
}
ProjectLinker::ProjectLinker(std::string main_module, std::string project_dir, std::string llvm_linker)
{
struct stat info;
if(stat(project_dir.c_str(), &info ) != 0)
throw std::invalid_argument("Could not access to project directory " + project_dir);
else if(!S_ISDIR(info.st_mode))
throw std::invalid_argument(project_dir + " is not a directory");
std::string findex_file = joinPath(std::string(project_dir), ".function_index");
functionMap = new LinkerSupports::SymbolMap(findex_file);
std::string gindex_file = joinPath(std::string(project_dir), ".globals_index");
globalMap = new LinkerSupports::SymbolMap(gindex_file);
this->llvm_linker = llvm_linker;
ModuleCutter* main = getOrLoadModule(main_module);
main->addAllDefinedFunctions();
mainModule = main;
processModules();
}
ModuleCutter* ProjectLinker::findModuleByName(std::string file_name)
{
auto it = find_if(modules.begin(), modules.end(), [file_name] (ModuleCutter* obj) {return obj->getName() == file_name;});
if (it != modules.end())
{
return *it;
}
return nullptr;
}
ModuleCutter* ProjectLinker::getModule(llvm::Module* module)
{
auto it = find_if(modules.begin(), modules.end(), [module] ( ModuleCutter* obj) {return obj->getModule() == module;});
{
return *it;
}
return nullptr;
}
void ProjectLinker::processModules()
{
bool status = false;
while(!status)
{
status = true;
for(ModuleCutter* module : modules)
{
bool module_status = module->hasEmptyQueues();
status = status && module_status;
if(!module_status)
{
module->processQueues();
}
}
}
}
void ProjectLinker::useExternalFunction(std::string name)
{
if(mainModule->hasFunction(name))
return;
std::vector<std::string*>* files = functionMap->getFiles(name);
if(!files)
{
notFoundFunctions.insert(name);
}
else
{
if(files->size() == 1)
{
ModuleCutter* mc = getOrLoadModule(*((*files)[0]));
mc->addFunction(name);
}
else
{
//TODO
std::cerr << "more same named functions" << std::endl;
std::exit(2);
}
}
}
void ProjectLinker::useExternalGlobal(std::string name)
{
if(mainModule->hasGlobal(name))
return;
std::vector<std::string*>* files = globalMap->getFiles(name);
if(!files)
{
notFoundGlobals.insert(name);
}
else
{
if(files->size() == 1)
{
ModuleCutter* mc = getOrLoadModule(*((*files)[0]));
mc->addGlobal(name);
}
else
{
//TODO
std::cerr << "more same named globals" << std::endl;
std::exit(2);
}
}
}
void ProjectLinker::linkModulesToFile(std::string& file)
{
std::string command(llvm_linker);
for(ModuleCutter* module : modules)
{
module->cutUnused();
module->writeToBC();
command += " " + module->getName() + ".processed";
}
char* temp = std::tmpnam(nullptr);
if(temp == nullptr)
{
std::cerr << "could not create tmp file";
std::exit(3);
}
command += " -o " + file;
command += " 2>&1 > " + std::string(temp);
int status = std::system(command.c_str());
if(status != 0)
{
std::ifstream tempfile;
tempfile.open(temp);
std::cerr << llvm_linker << " not exist or end with non 0 status" << std::endl;
char output[100];
if (tempfile.is_open())
{
while (!tempfile.eof())
{
tempfile >> output;
std::cerr << output;
}
}
std::exit(2);
}
}
std::string ProjectLinker::joinPath(std::string path, std::string file)
{
if(path[path.size()-1] != '/')
{
path += '/';
}
path += file;
return path;
}
ProjectLinker::~ProjectLinker()
{
for(ModuleCutter* mc : modules)
{
delete mc;
}
delete functionMap;
delete globalMap;
}
void ProjectLinker::printNotFoundFunctions()
{
std::cerr << "Not found functions: " << std::endl;
for(std::string nm : notFoundFunctions)
{
std::cerr << nm << std::endl;
}
}
void ProjectLinker::printNotFoundGlobals()
{
std::cerr << "Not found globals: " << std::endl;
for(std::string nm : notFoundGlobals)
{
std::cerr << nm << std::endl;
}
}
void ProjectLinker::printNotFound()
{
printNotFoundFunctions();
printNotFoundGlobals();
}
<file_sep>/source/dtlu-project-maker
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 27 12:48:13 2016
@author: <NAME>
"""
from __future__ import print_function
import sys, getopt, subprocess, re, os, shlex, time
arguments = "hrm:p:i"
longArguments = ["help","recompile","makefile=","project-directory=,index"]
script_dir = None
REAL_CC = os.getenv('REAL_CC', "cc")
LLVM_CC = os.getenv('LLVM_CC', "clang")
class FilesSet(set):
def __init__(self, project_dir):
set.__init__(self)
self.path = os.path.join(project_dir,".files")
if os.path.isfile(self.path):
files_file = open(self.path, "r")
for line in files_file:
self.add(line.strip())
files_file.close()
def save(self):
files_file = open(self.path, "w")
for line in self:
files_file.write(str.format("{0}\n",line))
files_file.close()
class stcc_helper(object):
import re
INPUT_FILE = 0
OUTPUT_FILE = 1
WORK_DIR = 2
ARGUMENTS = 3
not_supported_by_clang = ["-static-libgcc"]
ex_f_o = re.compile(r"(?<=\W)(-f\S*)|(-O\S*)|(-Wno\S*)")
ex_spaces = re.compile(r"\s+")
@staticmethod
def remove_flags(arguments):
arguments_output, i =stcc_helper.ex_f_o.subn("", arguments) #remove f and o flags
#remove not supported flags by clang
for not_supported in stcc_helper.not_supported_by_clang:
arguments_output = arguments_output.replace(not_supported, "")
arguments_output, i = stcc_helper.ex_spaces.subn(" ", arguments_output) #remove whitespaces
return arguments_output
@staticmethod
def parse_line(line):
parts = line.split("},{")
parts[0] = parts[0][1:]
last = len(parts) - 1
parts[last] = parts[last][0:-2]
#flags prepare
parts[stcc_helper.ARGUMENTS] = stcc_helper.remove_flags(parts[stcc_helper.ARGUMENTS])
return parts
@staticmethod
def parse_file(file_path):
file_input = open(file_path)
list_output = []
for line in file_input:
line_parsed = stcc_helper.parse_line(line)
list_output.append(line_parsed)
file_input.close()
return list_output
def commandExists(name):
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
fullpath = os.path.join(path,name)
if(os.access(fullpath, os.X_OK)):
return True;
return False;
def utility(name):
if(commandExists(name)):
return name
elif(os.access(name, os.X_OK)):
return name
else:
print(name + " not installed and is not in current dir")
exit(2);
def printHelp():
print("Use: dtlu-project-maker -p path/to/project_dir [-m path/to/Makefile -r -i]\nEnviroment variables:\n\tREAL_CC\tDefault - cc\n\tLLVM_CC\tDefault - clang")
print("Examples:")
print("\tdtlu-project-maker -p project_dir -m Makefile")
print("\t\t make, compile and index project")
print("\tdtlu-project-maker -p project_dir -i")
print("\t\t only index files by file .files in project_dir ")
def create_directory_tree(dir_path):
if not os.path.isdir(dir_path):
create_directory_tree(os.path.dirname(dir_path))
os.mkdir(dir_path)
def set_script_dir():
global script_dir
script_dir = os.path.dirname(os.path.abspath(__file__))
def get_source_dir(project_dir):
proj_file = open(os.path.join(project_dir,".project"),"r")
source_dir = proj_file.readline().strip()
proj_file.close()
return source_dir;
def compile_project(project_dir):
if(not commandExists(LLVM_CC)):
print("clang not installed")
exit(2);
CC = LLVM_CC + " -c -g"
LLVM = "-emit-llvm"
stcc_output = os.path.join(project_dir,".stcc_output")
file_set = FilesSet(project_dir)
stcc_parsed_file = stcc_helper.parse_file(stcc_output)
compile_completed = True
source_dir = get_source_dir(project_dir)
i = 1;
c = len(stcc_parsed_file)
for line_parsed in stcc_parsed_file:
if os.path.isabs(line_parsed[stcc_helper.OUTPUT_FILE]):
file_output = line_parsed[stcc_helper.OUTPUT_FILE]
else:
file_output = os.path.join(project_dir,line_parsed[stcc_helper.OUTPUT_FILE])
create_directory_tree(os.path.dirname(file_output))
file_input = line_parsed[stcc_helper.INPUT_FILE]
if(file_output == "/dev/null"):
print(file_input + " output file is /dev/null, not compile")
print(str.format("{0} {1}/{2} \r","compiled", i, c ), end="")
i += 1
continue;
command = str.format("{0} {1} -o {2} {3} {4}", CC, file_input, file_output, line_parsed[stcc_helper.ARGUMENTS], LLVM)
command_splited = shlex.split(command)
p = subprocess.Popen(command_splited, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=source_dir)
p.wait()
if p.returncode != 0:
out, err = p.communicate()
print(str.format("{0} {1} {2}", file_input, "not compiled,", p.returncode))
print(out)
print(err)
compile_completed = False
print(str.format("{0} {1}/{2} \r","compiled", i, c ), end="")
file_set.add(file_output)
i += 1
print("")
file_set.save()
if not compile_completed:
print("Compile ends with error")
sys.exit(2)
def index_functions(project_dir):
indexer = utility("dtlu-indexer")
file_set = FilesSet(project_dir)
index_file = open(os.path.join(project_dir,".function_index"), "w")
index = []
globals_index_file = open(os.path.join(project_dir,".globals_index"), "w")
globals_index = []
for f in file_set:
try:
output = subprocess.check_output([indexer, f])
for func in output.splitlines():
index.append(str.format("{0} {1}\n", func.decode("utf-8").strip(), f))
g_output = subprocess.check_output([indexer, f, "-g"])
for func in g_output.splitlines():
globals_index.append(str.format("{0} {1}\n", func.decode("utf-8").strip(), f))
except subprocess.CalledProcessError as cpe:
print(cpe.output)
print("{0} ends with {1}".format(indexer,cpe.returncode))
print("{0} not indexed".format(f))
index.sort()
globals_index.sort()
for line in index:
index_file.write(line)
for line in globals_index:
globals_index_file.write(line)
index_file.close()
globals_index_file.close()
def remake_project(project_dir):
job_file = os.path.join(project_dir,".stcc_output")
jw = open(job_file, "w")
jw.close()
stcc_env = os.environ.copy()
stcc_env["JOB_FILE"] = job_file
stcc_env["REAL_CC"] = REAL_CC
stcc_loc = utility("stcc")
if(stcc_loc[0] == "."):
stcc_loc = os.path.join(script_dir,"stcc")
source_dir = get_source_dir(project_dir)
makefile = os.path.join(source_dir,"Makefile")
print("Running make")
NULL = open(os.devnull,"w")
try:
subprocess.call(["make","CC=" + stcc_loc, "-f", makefile], env=stcc_env,
cwd=source_dir, stdout=NULL,
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as cpe:
print("Make ends with {0}".format(cpe.returncode))
sys.exit(3)
NULL.close()
print("Make complete\nCompiling project")
compile_project(project_dir)
print("Compile complete\nIndexing project")
index_functions(project_dir)
def make_project(project_dir, makefile):
job_file = os.path.join(project_dir,".stcc_output")
proj = open(os.path.join(project_dir, ".project"),"w")
source_dir = os.path.dirname(os.path.abspath(makefile))
proj.write(str.format("{0}\n", source_dir))
proj.close()
remake_project(project_dir)
def main(argv):
set_script_dir()
makefile = None
outputDirectory = None
recompile = False
only_index = False
try:
opt, args = getopt.getopt(argv,arguments,longArguments)
except getopt.GetoptError as e:
print(str(e))
printHelp()
sys.exit(1)
for o, a in opt:
if o in ("-h", "--help"):
printHelp()
sys.exit()
elif o in ("-m", "--makefile"):
makefile = a
elif o in ("-p", "--project-directory"):
outputDirectory = a
elif o in ("-r", "--recompile"):
recompile = True
elif o in ("-i","--index"):
only_index = True
else:
assert False, "unhandled option"
if not outputDirectory:
print("missing -p project_directory")
printHelp()
sys.exit(1)
outputDirectory = os.path.abspath(outputDirectory)
if not os.path.isdir(outputDirectory):
print(outputDirectory + " not exist or is not a directory")
printHelp()
sys.exit(1)
if makefile and outputDirectory and not recompile:
make_project(outputDirectory, makefile)
elif makefile and outputDirectory and recompile:
remake_project(outputDirectory)
elif outputDirectory and only_index and not recompile and not makefile:
index_functions(outputDirectory)
else:
printHelp()
sys.exit(1)
if __name__ == "__main__":
main(sys.argv[1:])
<file_sep>/include/projectlinker.hpp
#ifndef __PROJECTLINKER_H__
#define __PROJECTLINKER_H__
#include <set>
#include <string>
class ModuleCutter;
namespace LinkerSupports
{
class SymbolMap;
}
namespace llvm
{
class Module;
class Function;
class GlobalVariable;
}
class ProjectLinker
{
private:
//attributes
std::set<ModuleCutter*> modules;
LinkerSupports::SymbolMap* functionMap;
LinkerSupports::SymbolMap* globalMap;
std::set<std::string> notFoundFunctions;
std::set<std::string> notFoundGlobals;
std::string llvm_linker;
ModuleCutter* mainModule;
//functions
ModuleCutter* findModuleByName(std::string file_name);
void printNotFoundFunctions();
void printNotFoundGlobals();
void processModules();
std::string joinPath(std::string path, std::string file);
public:
ProjectLinker(std::string main_module, std::string project_dir, std::string llvm_linker);
ModuleCutter* getOrLoadModule(std::string file_name);
ModuleCutter* getModule(llvm::Module* module);
void useExternalFunction(std::string);
void useExternalGlobal(std::string);
void linkModulesToFile(std::string& file);
ModuleCutter* getMainModule(){ return mainModule; }
void printNotFound();
virtual ~ProjectLinker();
};
#endif
<file_sep>/include/modulecutter.hpp
#ifndef __MODULECUTTER_H__
#define __MODULECUTTER_H__
#include <set>
#include <deque>
#include <list>
#include <string>
class ProjectLinker;
namespace llvm
{
class Module;
class Function;
class GlobalVariable;
class User;
}
class ModuleCutter
{
private:
llvm::Module* module;
ProjectLinker* parent;
std::string name;
std::set<llvm::Function*> usedFunctions;
std::set<llvm::GlobalVariable*> usedGlobals;
std::deque<llvm::Function*> functionProcessQueue;
std::deque<llvm::GlobalVariable*> globalProcessQueue;
void useFunction(llvm::Function* func);
void useGlobal(llvm::GlobalVariable* global);
void useFunctions(std::list<llvm::Function*> list);
void useGlobals(std::list<llvm::GlobalVariable*> list);
void processFunctions();
void processGlobals();
void checkGlobal(llvm::GlobalVariable* global);
void checkFunction(llvm::Function* func);
void cutFunctions();
void cutGlobals();
void recursiveGlobals(llvm::User* user);
void recursiveFunctions(llvm::User* user);
void removeRedefindedFunction(llvm::Function* f);
void removeRedefindedGlobal(llvm::GlobalVariable* g);
public:
ModuleCutter(std::string name, ProjectLinker* parent);
std::string getName() {return this->name;}
llvm::Module* getModule() {return this->module;}
void addAllDefinedFunctions();
void addFunction(std::string func_name);
void addGlobal(std::string global_name);
void processQueues();
bool hasEmptyQueues(){ return functionProcessQueue.empty() && globalProcessQueue.empty();}
void cutUnused();
void writeToBC(std::string fileName = "");
bool hasFunction(std::string name);
bool hasGlobal(std::string name);
virtual ~ModuleCutter();
};
#endif
<file_sep>/source/CMakeLists.txt
find_package(LLVM REQUIRED CONFIG)
message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}")
message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}")
set(CMAKE_CXX_STANDARD 11) # C++11...
set(CMAKE_CXX_STANDARD_REQUIRED ON) #...is required...
set(CMAKE_CXX_EXTENSIONS OFF) #...without compiler extensions like gnu++11
set(CMAKE_BUILD_TYPE Debug)
# Set your project compile flags.
# E.g. if using the C++ header files
# you will need to enable C++11 support
# for your compiler.
include_directories(${LLVM_INCLUDE_DIRS} ${dtlu_SOURCE_DIR}/include)
add_definitions(${LLVM_DEFINITIONS})
# Now build our tools
add_executable(dtlu-indexer function_indexer.cpp)
add_executable(dtlu-linker linker.cpp)
add_library(LinkerSupports STATIC linkersupports.cpp)
add_library(SymbolMap STATIC symbolmap.cpp)
add_library(ModuleCutter STATIC modulecutter.cpp)
add_library(ProjectLinker STATIC projectlinker.cpp)
llvm_map_components_to_libnames(llvm_libs support core irreader bitwriter)
# Link against LLVM libraries
target_link_libraries(dtlu-linker ProjectLinker)
target_link_libraries(dtlu-indexer ${llvm_libs} LinkerSupports)
target_link_libraries(ModuleCutter ${llvm_libs} LinkerSupports)
target_link_libraries(ProjectLinker ModuleCutter SymbolMap ${llvm_libs})
target_link_libraries(LinkerSupports ${llvm_libs})
install(
TARGETS dtlu-linker dtlu-indexer
DESTINATION /usr/bin
)
install(
FILES stcc dtlu-project-maker
PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ
GROUP_READ GROUP_EXECUTE
WORLD_READ WORLD_EXECUTE
DESTINATION /usr/bin
)
<file_sep>/source/function_indexer.cpp
#include <llvm/IR/Module.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/CommandLine.h>
#include <iostream>
#include <list>
#include <memory>
#include "linkersupports.hpp"
int main(int args, char**);
void help();
using namespace llvm;
static cl::OptionCategory IndexerCategory("Indexer Options", "Options for dtlu-indexer.");
static cl::opt<std::string> InputFilename(cl::Positional, cl::Required, cl::desc("<input file>"), cl::cat(IndexerCategory));
static cl::opt<bool> IndexGlobal("g", cl::desc("Get global visible global variables"), cl::cat(IndexerCategory));
int main(int argc, char** argv)
{
cl::HideUnrelatedOptions(IndexerCategory);
cl::ParseCommandLineOptions(argc, argv,"Print global defined function");
LLVMContext& context = llvm::getGlobalContext();
SMDiagnostic error;
std::string file_name = InputFilename;
std::unique_ptr<Module> m = parseIRFile(file_name, error, context);
if(!m)
{
std::cout << error.getMessage().str() << std::endl;
return 2;
}
Module* module = m.release();
if(IndexGlobal)
{
auto l = LinkerSupports::getDefinedGlobals(module);
for(auto b = l.begin(); b != l.end(); ++b)
{
std::cout << (*b)->getName().str() << std::endl;
}
}
else
{
auto l = LinkerSupports::getDefinedFunctions(module);
for(auto b = l.begin(); b != l.end(); ++b)
{
std::cout << (*b)->getName().str() << std::endl;
}
}
delete module;
return 0;
}
<file_sep>/source/linker.cpp
#include <llvm/Support/CommandLine.h>
#include <string>
#include <iostream>
#include <stdexcept>
#include "projectlinker.hpp"
int main(int args, char**);
void help();
using namespace llvm;
static cl::OptionCategory LinkerCategory("Linker Options", "Options for dtlu-linker.");
static cl::opt<std::string> OutputFilename("o", cl::desc("Specify output filename"), cl::value_desc("filename"), cl::cat(LinkerCategory));
static cl::opt<std::string> InputFilename(cl::Positional, cl::Required, cl::desc("<input file>"), cl::cat(LinkerCategory));
static cl::opt<std::string> ProjectDirname("p", cl::desc("Specify project directory"), cl::value_desc("directory"), cl::Required, cl::cat(LinkerCategory));
int main(int argc, char** argv)
{
cl::HideUnrelatedOptions(LinkerCategory);
cl::ParseCommandLineOptions(argc, argv);
std::string llvm_linker("llvm-link");
std::string on;
if(OutputFilename.empty())
{
on = "output.bc";
}
else
{
on = OutputFilename;
}
std::string mainName = InputFilename;
std::string project_dir = ProjectDirname;
try
{
ProjectLinker project(mainName, project_dir, llvm_linker);
project.linkModulesToFile(on);
project.printNotFound();
}
catch (std::invalid_argument& e)
{
std::cerr << e.what() << std::endl;
return 3;
}
}
void help()
{
std::cout << "Use: linker file [-a name]\n";
std::cout << "file must be llvm bytecode\n";
}
<file_sep>/README.md
# dtlu
**Dependency Tracking Linker Utils**
##Install
```
cloned_repository$ mkdir build
cloned_repository$ cd build
cloned_repository/build$ cmake ..
cloned_repository/build$ sudo make install
```
building and indexing project - need clang
dtlu-project-maker -m path/to/Makefile -p project/build/directory
linking module - need llvm-link
input file - LLVM BC or LLVM IR, clang -c -emtt-llvm file.c -o file.bc
dtlu-linker file.bc -o output_file
<file_sep>/source/modulecutter.cpp
#include "modulecutter.hpp"
#include <llvm/IR/Module.h>
#include <llvm/IR/Instruction.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Value.h>
#include <llvm/IR/Verifier.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/Casting.h>
#include <llvm/IR/Constants.h>
#include "linkersupports.hpp"
#include "projectlinker.hpp"
#include <list>
#include <iostream>
using namespace llvm;
ModuleCutter::ModuleCutter(std::string name, ProjectLinker* parent) : parent(parent), name(name)
{
SMDiagnostic error;
std::unique_ptr<Module> m = parseIRFile(StringRef(name), error, getGlobalContext());
if(!m)
{
std::cerr << name << std::endl;
std::cerr << error.getMessage().str() << std::endl;
std::exit(2);
}
module = m.release();
}
void ModuleCutter::useFunction(llvm::Function* func)
{
auto result = usedFunctions.insert(func);
if(result.second)
{
functionProcessQueue.push_back(func);
}
}
void ModuleCutter::useGlobal(llvm::GlobalVariable* global)
{
auto result = usedGlobals.insert(global);
if(result.second)
{
globalProcessQueue.push_back(global);
}
}
void ModuleCutter::addFunction(std::string func_name)
{
Function* f = module->getFunction(StringRef(func_name));
if(f)
{
useFunction(f);
}
}
void ModuleCutter::addGlobal(std::string global_name)
{
GlobalVariable* g = module->getGlobalVariable(StringRef(global_name));
if(g)
{
useGlobal(g);
}
}
void ModuleCutter::addAllDefinedFunctions()
{
std::list<Function*> l = LinkerSupports::getDefinedFunctions(module);
useFunctions(l);
}
void ModuleCutter::processFunctions()
{
while(!functionProcessQueue.empty())
{
Function* func = functionProcessQueue.front();
//debug
//std::cerr << name << "Function " << func->getName().str() << std::endl;
if(!LinkerSupports::isDefined(func))
{
parent->useExternalFunction(func->getName().str());
}
else
{
/*std::list<Function*> called = LinkerSupports::getCalledFunctions(func);
useFunctions(called);
std::list<GlobalVariable*> used = LinkerSupports::getUsedGlobals(func);
useGlobals(used);*/
checkFunction(func);
}
functionProcessQueue.pop_front();
}
}
void ModuleCutter::processGlobals()
{
while(!globalProcessQueue.empty())
{
GlobalVariable* global = globalProcessQueue.front();
if(!global->hasInitializer() && global->hasExternalLinkage())
{
parent->useExternalGlobal(global->getName().str());
}
checkGlobal(global);
globalProcessQueue.pop_front();
}
}
void ModuleCutter::useFunctions(std::list<Function*> l)
{
for(Function * f : l)
{
useFunction(f);
}
}
void ModuleCutter::useGlobals(std::list<GlobalVariable*> l)
{
for(GlobalVariable* g : l)
{
//std::cerr << "Global " << g->getName().str() << std::endl;
useGlobal(g);
}
}
void ModuleCutter::processQueues()
{
while(!hasEmptyQueues())
{
processFunctions();
processGlobals();
}
}
void ModuleCutter::cutUnused()
{
cutFunctions();
cutGlobals();
}
void ModuleCutter::cutFunctions()
{
std::list<std::string> unused;
for(auto it = module->getFunctionList().begin(); it != module->getFunctionList().end(); ++it)
{
auto &f = *it;
if(usedFunctions.find(&f) == usedFunctions.end())
{
unused.push_back(f.getName().str());
}
else
{
removeRedefindedFunction(&f);
}
}
for(auto un : unused)
{
Function * f = module->getFunction(un);
if(f)
{
f->replaceAllUsesWith(UndefValue::get(f->getType()));
f->removeFromParent();
delete f;
}
}
}
void ModuleCutter::cutGlobals()
{
std::list<std::string> unused;
for(auto it = module->global_begin(); it != module->global_end(); ++it)
{
auto &f = *it;
if(usedGlobals.find(&f) == usedGlobals.end())
{
unused.push_back(f.getName().str());
}
else
{
removeRedefindedGlobal(&f);
}
}
for(auto un : unused)
{
module->getGlobalVariable(un, true)->eraseFromParent();
}
}
void ModuleCutter::checkGlobal(GlobalVariable* global)
{
recursiveGlobals(global);
recursiveFunctions(global);
}
void ModuleCutter::checkFunction(Function* function)
{
for (auto I = function->begin(), E = function->end(); I != E; ++I)
{
for (llvm::BasicBlock::iterator i = I->begin(), ie = I->end(); i != ie; ++i)
{
recursiveGlobals(&*i);
recursiveFunctions(&*i);
}
}
}
void ModuleCutter::recursiveGlobals(User* user)
{
for (Value *o : user->operands())
{
if (llvm::GlobalVariable* g = llvm::dyn_cast<llvm::GlobalVariable>(&*o))
{
useGlobal(g);
}
else if(User *u = dyn_cast<User>(&*o))
{
recursiveGlobals(u);
}
}
}
void ModuleCutter::removeRedefindedFunction(Function* f)
{
std::string name = f->getName().str();
if(parent->getMainModule() != this && hasFunction(name) && parent->getMainModule()->hasFunction(name))
{
f->deleteBody();
}
}
void ModuleCutter::removeRedefindedGlobal(GlobalVariable* g)
{
std::string name = g->getName().str();
if(parent->getMainModule() != this && hasGlobal(name) && parent->getMainModule()->hasGlobal(name))
{
g->setInitializer(NULL);
}
}
void ModuleCutter::recursiveFunctions(User* user)
{
for (Value *o : user->operands())
{
if (llvm::Function* g = llvm::dyn_cast<llvm::Function>(&*o))
{
useFunction(g);
}
else if(User *u = dyn_cast<User>(&*o))
{
recursiveFunctions(u);
}
}
}
void ModuleCutter::writeToBC(std::string fileName /* = "" */)
{
//module->dump();
std::string outputString("");
raw_string_ostream errorDesc(outputString);
bool check = verifyModule(*module, &errorDesc);
//std::cerr << module->materializeAll() << std::endl;
if(check)
{
std::cerr <<"Error in module verification " << errorDesc.str() << std::endl;
module->dump();
std::exit(3);
}
if(fileName.empty())
{
fileName = name + ".processed";
}
std::error_code EC;
raw_fd_ostream os(fileName, EC, sys::fs::OpenFlags(0));
WriteBitcodeToFile(module, os);
os.flush();
}
bool ModuleCutter::hasFunction(std::string name)
{
Function* f = module->getFunction(StringRef(name));
if(!f)
return false;
if(!f->hasPrivateLinkage() && !f->hasInternalLinkage())
return LinkerSupports::isDefined(f);
return false;
}
bool ModuleCutter::hasGlobal(std::string name)
{
GlobalVariable* g = module->getGlobalVariable(StringRef(name));
if(!g)
return false;
return LinkerSupports::isInicializedAndGlobalAccessible(g);
}
ModuleCutter::~ModuleCutter()
{
delete module;
}
<file_sep>/include/linkersupports.hpp
#ifndef __LINKERSUPPORTS_H__
#define __LINKERSUPPORTS_H__
#include <list>
#include <memory>
//forward declare
namespace llvm
{
class Function;
class Module;
class GlobalAlias;
class GlobalVariable;
class Value;
}
namespace LinkerSupports
{
std::list<llvm::Function*> getCalledFunctions(llvm::Function* function);
std::list<llvm::Function*> getDefinedFunctions(llvm::Module* module);
std::list<llvm::Function*> getNotDefinedFunctions(llvm::Module* module);
std::list<llvm::GlobalVariable*> getDefinedGlobals(llvm::Module* module);
std::list<llvm::GlobalVariable*> getUsedGlobals(llvm::Function *function);
std::list<llvm::GlobalAlias*> getUsedGlobalAliases(llvm::Function *function);
std::list<llvm::GlobalVariable*> recursiveGlobals(llvm::Value* op);
bool isInicializedAndGlobalAccessible(llvm::GlobalVariable* global);
bool isDefined(llvm::Function* function);
}
#endif
| 567ce3a9cce0dc6045b89366ceb124bbf3f646b7 | [
"Markdown",
"Python",
"CMake",
"C++"
]
| 14 | C++ | Linhos13/dtlu | 8e769f13cf8517269a1f995a37431b9654cf34ff | bb1183f554f4faf71f3bb47f1a93619c181d29c6 |
refs/heads/main | <file_sep>library(dplyr)
# implementando o id3 na unha -------------------------------------------------
#carregando dataset jogar tenis
df <- readr::read_csv(file = "jogar-tenis.csv") %>%
select(-Dia) %>%
rename(Jogartenis=`<NAME>`)
#criando a função definiemodelo
defineformula <- function(dados,formula){
dados <- dados
formula <- formula
atributos <- as.vector(strsplit(x = formula ,split = '~')[[1]])
resposta <- trimws(atributos[1])
preditoras <- as.vector(
trimws(
strsplit(
x = trimws(atributos[2]) ,
split = "[+]"
)[[1]]
)
)
classes <- levels(as.factor(dados[[resposta]]))
return(list(dados = dados, formula = formula,resposta=resposta,preditoras=preditoras, classes=classes))
}
desenho_modelo <- defineformula(df,"Jogartenis~Tempo+Temperatura+Umidade+Vento")
desenho_modelo$dados
desenho_modelo$formula
desenho_modelo$resposta
desenho_modelo$preditoras
desenho_modelo$classes
#definindo a função entropia
entropia <- function(vetor){
entropia_temp = - sum(vetor/sum(vetor) * log2(vetor/sum(vetor)))
entropia_temp
entropia_final <- ifelse(is.nan(entropia_temp),0,entropia_temp)
return(entropia_final)
}
entropia2 <- function(vetor){
tab_vetor <- table(vetor)
entropia_temp = - sum(tab_vetor/sum(tab_vetor) * log2(tab_vetor/sum(tab_vetor)))
entropia_temp
entropia_final <- ifelse(is.nan(entropia_temp),0,entropia_temp)
return(entropia_final)
}
#testando a função entropia
entropia(table(desenho_modelo$dados[[desenho_modelo$resposta]]))
#Criando a função que calcula o ganho de informação
ganhoinfo <- function(dados,variavel,alvo){
return(
entropia(table(dados[,alvo])) -
sum(prop.table(table(dados[,variavel]))*
apply(table(dados[[variavel]],dados[[alvo]]),1,entropia)
)
)
}
#testando a função Ganho de informação
ganhoinfo(desenho_modelo$dados,desenho_modelo$preditoras[1],desenho_modelo$resposta)
#criando vetor auxiliar
pred_restantes <- desenho_modelo$preditoras
pred_restantes
#Calculando ganho de informação de todas as preditodas
ganhodeinformacao <- NULL
for(i in seq_along(pred_restantes)){
ganhodeinformacao[i] <- ganhoinfo(desenho_modelo$dados,pred_restantes[i],desenho_modelo$resposta)
}
names(ganhodeinformacao) <- pred_restantes
ganhodeinformacao
#selecionando informações do atributo com maior ganho de informação
fatiar = list(nome = NULL, classes = NULL, nclasses = NULL)
fatiar[[1]] <- names(ganhodeinformacao[ganhodeinformacao==max(ganhodeinformacao)])
fatiar[[2]] <- levels(as.factor(desenho_modelo$dados[[fatiar[[1]]]]))
fatiar[[3]] <- length(fatiar[[2]])
fatiar
#atualizando pred_restante
pred_restantes <- pred_restantes[pred_restantes!=fatiar[[1]]]
pred_restantes
#construindo a árvore
arvore <- data.frame(
no = as.numeric(1),
profundidade = as.numeric(0),
no_up = as.numeric(0),
var = fatiar[[1]],
rot = "",
int = 1,
n = nrow(desenho_modelo$dados),
entropia = entropia(table(desenho_modelo$dados[[desenho_modelo$resposta]]))
)
arvore$folha <- ifelse(arvore$entropia==0,1,0)
#Atualizando a árvore
arvore_temp <- data.frame(
no = (as.numeric(max(arvore[['no']]))+1):(as.numeric(max(arvore[['no']]))+as.numeric(fatiar[[3]])),
profundidade = as.numeric(1),
no_up = rep(tail(arvore[['no']],1),fatiar[[3]]),
var = rep(fatiar[[1]],fatiar[[3]]),
rot = fatiar[[2]],
int = rep(0,fatiar[[3]]),
n = as.numeric(table(desenho_modelo$dados[[fatiar[[1]]]])),
entropia = tapply(
desenho_modelo$dados[[desenho_modelo$resposta]],
desenho_modelo$dados[[fatiar[[1]]]],
entropia2
)
)
arvore_temp$folha <- ifelse(arvore_temp$entropia==0,1,0)
arvore <- rbind(arvore,arvore_temp)
profundidade <- 1
nomes_no <- unique(arvore[arvore[['profundidade']]==profundidade,'var'])
nomes_no
for (j in seq_along(nomes_no)) {
ramos_no <- arvore[arvore[['var']]==nomes_no[j],'rot']
ramos_no <- ramos_no[ramos_no!=""]
ramos_no
for (k in seq_along(ramos_no)) {
if (arvore[(arvore$var==nomes_no[j]) & (arvore$rot==ramos_no[k]) , 'entropia']!=0){
df_temp <- desenho_modelo$dados[desenho_modelo$dados[[nomes_no]]==ramos_no[k],]
df_temp
#Calculando ganho de informação de todas as preditodas
ganhodeinformacao <- NULL
for(l in seq_along(pred_restantes)){
ganhodeinformacao[l] <- ganhoinfo(df_temp,pred_restantes[l],desenho_modelo$resposta)
}
names(ganhodeinformacao) <- pred_restantes
ganhodeinformacao
novo_no <- names(ganhodeinformacao[ganhodeinformacao==max(ganhodeinformacao)])
novo_no
novos_ramos <- levels(as.factor(desenho_modelo$dados[[novo_no]]))
novos_ramos
n_novos_ramos <- length(novos_ramos)
n_novos_ramos
arvore_temp <- data.frame(
no = (as.numeric(max(arvore[['no']]))+1):(as.numeric(max(arvore[['no']]))+as.numeric(n_novos_ramos)),
profundidade = rep(profundidade+1,n_novos_ramos),
no_up = rep(arvore[(arvore$profundidade==1 & arvore$rot==ramos_no[k]), 'no'],n_novos_ramos),
var = rep(novo_no,n_novos_ramos),
rot = novos_ramos,
int = rep(0,n_novos_ramos),
n = as.numeric(table(df_temp[[novo_no]])),
entropia = tapply(
df_temp[[desenho_modelo$resposta]],
df_temp[[novo_no]],
entropia2
)
)
arvore_temp$folha <- ifelse(arvore_temp$entropia==0,1,0)
arvore <- rbind(arvore,arvore_temp)
pred_restantes <- pred_restantes[pred_restantes!=novo_no]
pred_restantes
}
}
}
View(arvore)
<file_sep>library(dplyr)
# implementando o id3 na unha -------------------------------------------------
#carregando dataset jogar tenis
df <- readr::read_csv(file = "jogar-tenis.csv") %>%
select(-Dia) %>%
rename(Jogartenis=`<NAME>`)
#criando a função definiemodelo
defineformula <- function(dados,formula,profundidade_max){
dados <- dados
formula <- formula
profundidade_max <- profundidade_max
atributos <- as.vector(strsplit(x = formula ,split = '~')[[1]])
resposta <- trimws(atributos[1])
preditoras <- as.vector(
trimws(
strsplit(
x = trimws(atributos[2]) ,
split = "[+]"
)[[1]]
)
)
classes <- levels(as.factor(dados[[resposta]]))
return(list(dados = dados, formula = formula,resposta=resposta,preditoras=preditoras, classes=classes, profundidade_max = profundidade_max))
}
#definindo a função entropia
entropia <- function(vetor){
entropia_temp = - sum(vetor/sum(vetor) * log2(vetor/sum(vetor)))
entropia_temp
entropia_final <- ifelse(is.nan(entropia_temp),0,entropia_temp)
return(entropia_final)
}
entropia2 <- function(vetor){
tab_vetor <- table(vetor)
entropia_temp = - sum(tab_vetor/sum(tab_vetor) * log2(tab_vetor/sum(tab_vetor)))
entropia_temp
entropia_final <- ifelse(is.nan(entropia_temp),0,entropia_temp)
return(entropia_final)
}
#Criando a função que calcula o ganho de informação
ganhoinfo <- function(dados,variavel,alvo){
return(
entropia(table(dados[,alvo])) -
sum(prop.table(table(dados[,variavel]))*
apply(table(dados[[variavel]],dados[[alvo]]),1,entropia)
)
)
}
# testando a função define modelo
desenho_modelo <- defineformula(df,"Jogartenis~Tempo+Temperatura+Umidade+Vento",4)
#testando a função entropia
entropia(table(desenho_modelo$dados[[desenho_modelo$resposta]]))
#testando a função entropia2
entropia2(desenho_modelo$dados[[desenho_modelo$resposta]])
#testando a função Ganho de informação
ganhoinfo(desenho_modelo$dados,desenho_modelo$preditoras[1],desenho_modelo$resposta)
#Definindo raiz -----------------------------------------------------------------------------------
#Definindo a profundidade da arvore
profundidade <- 0
#criando vetor auxiliar
pred_restantes <- desenho_modelo$preditoras
pred_restantes
#Calculando ganho de informação de todas as preditodas
ganhodeinformacao <- NULL
for(i in seq_along(pred_restantes)){
ganhodeinformacao[i] <- ganhoinfo(desenho_modelo$dados,pred_restantes[i],desenho_modelo$resposta)
}
names(ganhodeinformacao) <- pred_restantes
ganhodeinformacao
#selecionando nó raiz pelo atributo com maior ganho de informação
nomes_no <- names(ganhodeinformacao[ganhodeinformacao==max(ganhodeinformacao)])
nomes_no
#construindo a árvore
arvore <- data.frame(
no = as.numeric(1),
profundidade = as.numeric(0),
no_up = as.numeric(NA),
var = nomes_no,
rot = as.character(""),
n = nrow(desenho_modelo$dados),
entropia = entropia(table(desenho_modelo$dados[[desenho_modelo$resposta]]))
)
arvore$folha <- ifelse(arvore$entropia==0,1,0)
arvore$condicao <- ""
str(arvore)
#contruindo ramos da raiz ---------------------------------------------------------------------
profundidade <- 1
#definindo ramos do nó raiz
ramos_no <- levels(as.factor(desenho_modelo$dados[[nomes_no]]))
ramos_no
#definindo número de ramos do nó raiz
n_ramos <- length(ramos_no)
n_ramos
#Atualizando a árvore
arvore_temp <- data.frame(
no = (as.numeric(max(arvore[['no']]))+1):(as.numeric(max(arvore[['no']]))+as.numeric(n_ramos)),
profundidade = rep(profundidade,n_ramos),
no_up = rep(0,n_ramos),
var = rep(nomes_no,n_ramos),
rot = ramos_no,
n = as.numeric(table(desenho_modelo$dados[[nomes_no]])),
entropia = tapply(
desenho_modelo$dados[[desenho_modelo$resposta]],
desenho_modelo$dados[[nomes_no]],
entropia2
),
row.names = NULL
)
arvore_temp$folha <- ifelse(arvore_temp$entropia==0,1,0)
arvore_temp$condicao = paste(arvore_temp$var,"==",arvore_temp$rot)
arvore <- rbind(arvore,arvore_temp)
View(arvore)
#atualizando vetores de preditores restantes
pred_restantes <- pred_restantes[pred_restantes!=nomes_no]
pred_restantes
#Crescendo mais a árvores à partir da profundidade 2 --------------------------
while (profundidade < as.numeric(desenho_modelo$profundidade_max)) {
nomes_no <- unique(arvore[arvore[['profundidade']]==profundidade,'var'])
nomes_no
for (j in seq_along(nomes_no)) {
ramos_no <- arvore[arvore[['var']]==nomes_no[j],'rot']
ramos_no <- ramos_no[ramos_no!=""]
ramos_no
for (k in seq_along(ramos_no)) {
if (arvore[(arvore$var==nomes_no[j]) & (arvore$rot==ramos_no[k]) , 'entropia']!=0){
arvore[(arvore$var==nomes_no[j]) & (arvore$rot==ramos_no[k]),]
df_temp <- desenho_modelo$dados[desenho_modelo$dados[[nomes_no]]==ramos_no[k],]
df_temp
#Calculando ganho de informação de todas as preditodas
ganhodeinformacao <- NULL
for(l in seq_along(pred_restantes)){
ganhodeinformacao[l] <- ganhoinfo(df_temp,pred_restantes[l],desenho_modelo$resposta)
}
names(ganhodeinformacao) <- pred_restantes
ganhodeinformacao
novo_no <- names(ganhodeinformacao[ganhodeinformacao==max(ganhodeinformacao)])
novo_no
novos_ramos <- levels(as.factor(desenho_modelo$dados[[novo_no]]))
novos_ramos
n_novos_ramos <- length(novos_ramos)
n_novos_ramos
arvore_temp <- data.frame(
no = (as.numeric(max(arvore[['no']]))+1):(as.numeric(max(arvore[['no']]))+as.numeric(n_novos_ramos)),
profundidade = rep(profundidade+1,n_novos_ramos),
no_up = rep(arvore[(arvore$profundidade==1 & arvore$rot==ramos_no[k]), 'no'],n_novos_ramos),
var = rep(novo_no,n_novos_ramos),
rot = novos_ramos,
n = as.numeric(table(df_temp[[novo_no]])),
entropia = tapply(
df_temp[[desenho_modelo$resposta]],
df_temp[[novo_no]],
entropia2
),
row.names = NULL
)
arvore_temp$folha <- ifelse(arvore_temp$entropia==0,1,0)
arvore_temp$condicao = paste(
arvore$condicao[arvore$no==arvore_temp$no_up],
"&",arvore_temp$var,"==",arvore_temp$rot
)
arvore <- rbind(arvore,arvore_temp)
pred_restantes <- pred_restantes[pred_restantes!=novo_no]
pred_restantes
}
}
}
profundidade = profundidade + 1
}
View(arvore)
<file_sep>library(dplyr)
# implementando o id3 na unha -------------------------------------------------
#carregando dataset jogar tenis
df <- readr::read_csv(file = "jogar-tenis.csv") %>%
select(-Dia) %>%
rename(Jogartenis=`<NAME>`)
#criando a função definiemodelo
defineformula <- function(dados,formula){
dados <- dados
formula <- formula
atributos <- as.vector(strsplit(x = formula ,split = '~')[[1]])
resposta <- trimws(atributos[1])
preditoras <- as.vector(
trimws(
strsplit(
x = trimws(atributos[2]) ,
split = "[+]"
)[[1]]
)
)
classes <- levels(as.factor(dados[[resposta]]))
return(list(dados = dados, formula = formula,resposta=resposta,preditoras=preditoras, classes=classes))
}
desenho_modelo <- defineformula(df,"Jogartenis~Tempo+Temperatura+Umidade+Vento")
desenho_modelo$dados
desenho_modelo$formula
desenho_modelo$resposta
desenho_modelo$preditoras
desenho_modelo$classes
#definindo a função entropia
entropia <- function(vetor){
entropia_temp = - sum(vetor/sum(vetor) * log2(vetor/sum(vetor)))
entropia_temp
entropia_final <- ifelse(is.nan(entropia_temp),0,entropia_temp)
return(entropia_final)
}
#testando a função entropia
entropia(table(desenho_modelo$dados[[desenho_modelo$resposta]]))
#Criando a função que calcula o ganho de informação
ganhoinfo <- function(dados,variavel,alvo){
return(
entropia(table(dados[,alvo])) -
sum(prop.table(table(dados[,variavel]))*
apply(table(dados[[variavel]],dados[[alvo]]),1,entropia)
)
)
}
#testando a função Ganho de informação
ganhoinfo(desenho_modelo$dados,desenho_modelo$preditoras[1],desenho_modelo$resposta)
#criando vetor auxiliar
pred_restantes <- desenho_modelo$preditoras
#Calculando ganho de informação de todas as preditodas
ganhodeinformacao <- NULL
for(i in seq_along(pred_restantes)){
ganhodeinformacao[i] <- ganhoinfo(desenho_modelo$dados,pred_restantes[i],desenho_modelo$resposta)
}
names(ganhodeinformacao) <- pred_restantes
ganhodeinformacao
#selecionando informações do atributo com maior ganho de informação
fatiar = list(nome = NULL, classes = NULL, nclasses = NULL)
fatiar[[1]] <- names(ganhodeinformacao[ganhodeinformacao==max(ganhodeinformacao)])
fatiar[[2]] <- levels(as.factor(desenho_modelo$dados[[fatiar[[1]]]]))
fatiar[[3]] <- length(fatiar[[2]])
#atualizando pred_restante
pred_restantes <- pred_restantes[pred_restantes!=fatiar[[1]]]
pred_restantes
#construindo a árvore
arvore <- data.frame(
no = 1,
no_up = NA,
var = fatiar[[1]],
rot = NA,
int = 1,
n = nrow(desenho_modelo$dados),
folha = 0
)
# vetor auxiliar de preditores restantes
arvore[arvore[['no']]==1,pred_fatiar]
df_temp <- desenho_modelo$dados[desenho_modelo$dados[[fatiar[[1]]]]==fatiar[[2]][1],]
#Calculando ganho de informação de todas as preditodas
ganhodeinformacao <- NULL
for(i in seq_along(pred_restantes)){
ganhodeinformacao[i] <- ganhoinfo(df_temp,pred_restantes[i],desenho_modelo$resposta)
}
names(ganhodeinformacao) <- pred_restantes
ganhodeinformacao
# entropia_temp = - sum(0/sum(0) * log2(0/sum(0)))
# is.nan(entropia_temp)
# ifelse(is.nan(entropia_temp),5,6)
# entropia(c(1,0))
# entropia2 <- function(vetor){
# tab_vet <- table(vetor)
# return(- sum(tab_vet/sum(tab_vet) * log2(tab_vet/sum(tab_vet))))
# }
#entropia2(df[,"Jogartenis"])
#ganho de informação
# dados <- df
# variavel <- "Vento"
# alvo <- "Jogartenis"
#
# entropia(table(dados[,alvo])) -
# sum(
# prop.table(table(dados[,variavel]))*
# apply(with(dados, table(Vento, Jogartenis)), 1, entropia)
# )
# ganhoinfo <- function(dados,variavel,alvo){
# return(
# entropia(table(dados[,alvo])) -
# sum(prop.table(table(dados[,variavel]))*
# apply(
# table(dplyr::select(dados,variavel,alvo)),
# 1,
# entropia
# )
# )
# )
# }
#apply(
# table(
# # paste0(substitute(data),"$",variavel),
# # paste0(substitute(data),"$",alvo)
# )
# ),
# 1,
# entropia
#)
# teste_substitute <- function(data,variavel){
# print(paste0(substitute(data),"$",variavel))
# }
# teste_apply <- function(dados,variavel,alvo){
# return(
# apply(
# table(
# dplyr::select(dados,variavel,alvo)
# ),
# 1,
# entropia
# )
# )
# }
#
#
# apply(with(dados, table(variavel, alvo)), 1, entropia)
#
# table(select(df,Vento,Jogartenis))
# dados <- df
# variavel <- "Vento"
# alvo <- "Jogartenis"
#
# table(dados[[variavel]],dados[[alvo]])
#
# paste0(substitute(df),"$","Vento") %>% noquote()
#
# ganhoinfo(df,"Vento","Jogartenis")
# utilizando o rpart para ajustar a árvore ------------------------------------
#carregando o dataset
jogartenis <- readr::read_csv(file = "jogar-tenis.csv") %>%
select(-Dia) %>%
rename(Jogartenis=`<NAME>`)
arvore_ajustada <- rpart(
#formula = Jogartenis ~ Tempo+Temperatura+Umidade+Vento,
Jogartenis ~ .,
data = jogartenis,
method="class",
parms=list(split="information")
)
rpart.plot(arvore_ajustada)
<file_sep># id3
Implementando id3 no R
| b2081314ff3ef4bd47ecf3c5e0b8a12cbc6ef36f | [
"Markdown",
"R"
]
| 4 | R | jonates/id3 | f261d84a577d95d02d0b3684cf9b495730810121 | 96900a806be5249363a4c6a8dc33f7425dea5627 |
refs/heads/master | <repo_name>Fork-Read/AndroidApp<file_sep>/ForkRead/src/com/forkread/model/User.java
package com.forkread.model;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import com.bluelinelabs.logansquare.annotation.JsonField;
import com.bluelinelabs.logansquare.annotation.JsonObject;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@JsonObject
public class User {
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String COUNTRY = "country";
public static final String CURRENT_LOCATION = "location";
public static final String EMAIL_KEY = "email";
public static final String FORMATTED_ADDRESS = "formatted_address";
public static final String LATITUDE = "latitude";
public static final String LOCATION = "location";
public static final String LONGITUDE = "longitude";
public static final String NAME_KEY = "name";
public static final String PHONE_NO_KEY = "number";
public static final String POSITION = "position";
public static final String STATE = "state";
public static final String STREET = "street";
@JsonField
public UserLocation location;
@JsonField
public String distance;
@JsonField
public String email;
@JsonField
public String id;
@JsonField
public String name;
@JsonField
public String number;
@JsonField
public String userId;
@JsonField
public String pictureUrl;
@JsonField
public String access_token;
@JsonField
public String role;
@JsonField
public boolean active;
@JsonField
public boolean verified;
@JsonField
public long localId;
@JsonObject
public static class UserLocation {
@JsonField
public Position position;
@JsonField
public UserAddress address;
}
@JsonObject
public static class Position {
@JsonField
public double latitude;
@JsonField
public double longitude;
}
@JsonObject
public static class UserAddress {
@JsonField
public String location;
@JsonField
public String street;
@JsonField
public String city;
@JsonField
public String state;
@JsonField
public String country;
@JsonField
public String zipcode;
@JsonField
public String formatted_address;
}
public ArrayList<Books.Book> books = new ArrayList<>();
public void createLocationJson(Context paramContext, JSONObject userJSONObject) throws JSONException {
JSONObject locationJson;
JSONObject address;
JSONObject position;
Geocoder geocoder;
if (location != null) {
locationJson = new JSONObject();
address = new JSONObject();
position = new JSONObject();
geocoder = new Geocoder(paramContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(location.position.latitude,
location.position.longitude, 1);
if ((addresses == null) || (addresses.size() <= 0)) {
userJSONObject.put("currentLocation", "");
return;
}
Address localAddress = addresses.get(0);
if (localAddress.getMaxAddressLineIndex() > 0) {
String locality = localAddress.getAddressLine(0);
String street = localAddress.getSubLocality();
String city = localAddress.getLocality();
String state = localAddress.getAdminArea();
String country = localAddress.getCountryName();
String formatted_address = String.format("%s, %s, %s, %s, %s", new Object[]{locality, street,
city, state, country});
address.put(LOCATION, locality);
address.put(STREET, street);
address.put(CITY, city);
address.put(STATE, state);
address.put(COUNTRY, country);
address.put(FORMATTED_ADDRESS, formatted_address);
position.put(LATITUDE, location.position.latitude);
position.put(LONGITUDE, location.position.longitude);
locationJson.put(POSITION, position);
locationJson.put(ADDRESS, address);
userJSONObject.put(CURRENT_LOCATION, location);
}
} catch (IOException localIOException) {
userJSONObject.put(CURRENT_LOCATION, "");
} catch (IllegalArgumentException localIllegalArgumentException) {
userJSONObject.put(CURRENT_LOCATION, "");
}
}
}
public JSONObject getJsonString(Context paramContext) {
JSONObject userJsonObject = new JSONObject();
try {
userJsonObject.put(NAME_KEY, name);
userJsonObject.put(EMAIL_KEY, email);
userJsonObject.put(PHONE_NO_KEY, number);
createLocationJson(paramContext, userJsonObject);
return userJsonObject;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}<file_sep>/ForkRead/src/com/forkread/utils/ForkReadUtils.java
package com.forkread.utils;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bluelinelabs.logansquare.LoganSquare;
import com.forkread.application.ForkReadAppController;
import com.forkread.model.Books;
import com.forkread.model.Books.Book.ISBN;
import com.forkread.ui.BooksDetailsActivity;
import com.forkread.ui.HomePageActivity;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class ForkReadUtils {
private static final String TAG = ForkReadUtils.class.getSimpleName();
public static String fetchToken(Context paramContext, String paramString) throws IOException {
try {
String str = GoogleAuthUtil.getToken(paramContext, paramString,
"oauth2:https://www.googleapis.com/auth/books https://www.googleapis.com/auth/userinfo.profile");
return str;
} catch (UserRecoverableAuthException localUserRecoverableAuthException) {
return null;
} catch (GoogleAuthException localGoogleAuthException) {
return null;
}
}
public static void getGoogleBookResultFromISBN(final Context context, String paramString) {
JsonObjectRequest request = new JsonObjectRequest(Method.GET,
"https://www.googleapis.com/books/v1/volumes?q=isbn:" + paramString, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if ((response != null) && (response.length() > 0)) {
Intent localIntent = new Intent(context, BooksDetailsActivity.class);
localIntent.putExtra(BooksDetailsActivity.BUNDLE_KEY_BOOK_VIEW, response.toString());
context.startActivity(localIntent);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
ForkReadAppController.getInstance().addToRequestQueue(request, "tag_json_obj");
}
public static void makeAddBookRequest(final Context context, JSONObject paramJSONObject) {
JsonObjectRequest request = new JsonObjectRequest(Method.POST, "http://www.forkread.com/api/books/save",
paramJSONObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
Toast.makeText(context, "Book has been added in your list!", Toast.LENGTH_LONG).show();
Intent localIntent = new Intent(context, HomePageActivity.class);
context.startActivity(localIntent);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
ForkReadAppController.getInstance().addToRequestQueue(request, "tag_json_obj");
}
private static void onBookSearchResponseReceived(String jsonResponse, Callback callback) throws JSONException {
try {
Books books = LoganSquare.parse(jsonResponse, Books.class);
callback.onSearchResultsParsed(books);
} catch (IOException e) {
}
}
public static void searchBooks(final SearchParams searchParams, final Callback paramCallback) throws UnsupportedEncodingException {
int i = searchParams.mOffset;
JsonObjectRequest request = new JsonObjectRequest(Method.GET, "https://www.googleapis.com/books/v1/volumes?q="
+ URLEncoder.encode(searchParams.mSearchText, "UTF-8") + "&startIndex=" + i + "&maxResults=10", null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
onBookSearchResponseReceived(response.toString(), paramCallback);
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
ForkReadAppController.getInstance().addToRequestQueue(request, "tag_json_obj");
}
public static void searchBooksOnPortal(final ForkReadSearchResultsCallback callback, SearchParams searchParams) {
JsonObjectRequest request = new JsonObjectRequest(Method.POST, "http://www.forkread.com/api/books/search"
, searchParams.getJSONObject(),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
callback.onForkReadServerSearchResultsSuccess(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
callback.onForkReadServerSearchResultsError();
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
ForkReadAppController.getInstance().addToRequestQueue(request, "tag_json_obj");
}
public static interface Callback {
/**
* Callback when books search result from google books api errors out
*/
public void onSearchResultsError();
/**
* Callback when search results are parsed from google books api
*
* @param books
*/
public void onSearchResultsParsed(Books books);
}
public interface ForkReadSearchResultsCallback {
/**
* Callback when books search result from fork read server api errors out
*/
void onForkReadServerSearchResultsError();
/**
* Callback when we get results succesfully from fork read server api
*
* @param serverResponse
*/
void onForkReadServerSearchResultsSuccess(String serverResponse);
}
public static String getDisplayStringFromArray(String[] array) {
if (array != null && array.length > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i == 0) {
sb.append(array[i]);
} else {
sb.append(", ").append(array[i]);
}
}
return sb.toString();
}
return "not known";
}
public static String getIsbnFromIdentifier(ArrayList<ISBN> identifiers) {
if (identifiers != null) {
for (ISBN isbn : identifiers) {
if (Constants.ISBN_13.equalsIgnoreCase(isbn.type)) {
return isbn.identifier;
}
}
if (identifiers.size() > 0) {
return identifiers.get(0).identifier;
}
}
return null;
}
public static boolean isValidMobile(String mobileStr, Context context) {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber phoneNumber;
if (!TextUtils.isEmpty(mobileStr) && mobileStr != null) {
try {
mobileStr = mobileStr.replaceFirst("^0+(?!$)", "");
phoneNumber = phoneUtil.parse(mobileStr, "IN");
} catch (NumberParseException e) {
return false;
}
if (phoneUtil.isValidNumber(phoneNumber)) {
PhoneNumberUtil.PhoneNumberType numberType = phoneUtil.getNumberType(phoneNumber);
if (numberType == PhoneNumberUtil.PhoneNumberType.FIXED_LINE) {
return false;
}
if (numberType == PhoneNumberUtil.PhoneNumberType.FIXED_LINE_OR_MOBILE
|| numberType == PhoneNumberUtil.PhoneNumberType.MOBILE) {
return true;
}
}
// Hack for indian mobile numbers
if (phoneNumber.getCountryCode() == 91
&& String.valueOf(phoneNumber.getNationalNumber()).matches("[789]\\d{9}")) {
return true;
}
return false;
} else {
return false;
}
}
}<file_sep>/ForkRead/src/com/forkread/ui/NavigationFragment.java
package com.forkread.ui;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.book.forkread.R;
import com.forkread.adapters.DrawerItemsAdapter;
import com.forkread.application.ForkReadAppController;
import com.forkread.database.ForkReadDatabaseHelper;
import com.forkread.login.ForkReadLoginActivity;
import com.forkread.model.DrawerItem;
import com.forkread.model.User;
public class NavigationFragment extends ListFragment
{
private TextView emailId;
private DrawerItemsAdapter mListAdapter;
private TextView username;
public void onActivityCreated(Bundle paramBundle)
{
super.onActivityCreated(paramBundle);
User user = ForkReadAppController.getInstance().getUser();
if (user != null) {
username.setText(user.name);
emailId.setText(user.email);
}
String[] arrayOfString = getResources().getStringArray(R.array.drawer_items);
TypedArray localTypedArray = getResources().obtainTypedArray(R.array.drawer_items_icons);
List<DrawerItem> drawerItems = new ArrayList<DrawerItem>();
for (int i = 0; i < arrayOfString.length; i++) {
drawerItems.add(new DrawerItem(arrayOfString[i], localTypedArray.getResourceId(i, R.drawable.ic_launcher)));
}
this.mListAdapter = new DrawerItemsAdapter(getActivity(), drawerItems);
setListAdapter(this.mListAdapter);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (position == 6) {
boolean isDeleted = getActivity().deleteDatabase(ForkReadDatabaseHelper.DATABASE_NAME);
if (isDeleted) {
Intent intent = new Intent(getActivity(), ForkReadLoginActivity.class);
getActivity().startActivity(intent);
Toast.makeText(getActivity(), "Logged out successfully!", Toast.LENGTH_LONG).show();
getActivity().finish();
} else {
Toast.makeText(getActivity(), "Error logging out. Try again!", Toast.LENGTH_LONG).show();
}
}
}
public void onAttach(Activity paramActivity)
{
super.onAttach(paramActivity);
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
}
public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
{
View localView = paramLayoutInflater.inflate(R.layout.naviagtion_drawer_layout, paramViewGroup, false);
username = (TextView) localView.findViewById(R.id.user_name);
emailId = (TextView) localView.findViewById(R.id.user_email_id);
return localView;
}
}<file_sep>/settings.gradle
include ':ForkRead'
<file_sep>/ForkRead/src/com/forkread/model/DrawerItem.java
package com.forkread.model;
public class DrawerItem
{
public int mDrawable;
public String mTitle;
public DrawerItem(String paramString, int paramInt)
{
this.mTitle = paramString;
this.mDrawable = paramInt;
}
}
/* Location: C:\Users\dshah\Downloads\ForkRead_com.forkread_1.0_1\classes_dex2jar.jar
* Qualified Name: com.forkread.model.DrawerItem
* JD-Core Version: 0.6.0
*/<file_sep>/ForkRead/src/com/forkread/ui/SwipeMenuListViewTouchListener.java
package com.forkread.ui;
import com.forkread.ui.SwipeMenuView.SwipeMenuVisibilityCallbacks;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AbsListView;
import android.widget.ListView;
public class SwipeMenuListViewTouchListener implements View.OnTouchListener
{
public static interface SwipeMenuListViewTouchListenerCallbacks
{
public void onSwipingStarted();
public void onSwipingEnded();
}
// private static final String TAG =
// SwipeMenuListViewTouchListener.class.getSimpleName();
private ListView mListView;
private boolean mPaused;
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private int mViewWidth;
private View mDownView;
private float mDownX;
private float mDownY;
private int mDownPosition;
private VelocityTracker mVelocityTracker;
private boolean mSwiping;
private int mSwipingSlop;
private SwipeMenuView mSwipeMenuView;
private boolean mLockSwipe = false;
private SwipeMenuListViewTouchListenerCallbacks mCallbacks;
public SwipeMenuListViewTouchListener(ListView listView)
{
this.mListView = listView;
ViewConfiguration vc = ViewConfiguration.get(listView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mListView = listView;
}
public void setSwipeMenuListViewTouchListenerCallbacks(SwipeMenuListViewTouchListenerCallbacks callbacks)
{
this.mCallbacks = callbacks;
}
public void setSwipeMenuView(SwipeMenuView swipeMenuView)
{
this.mSwipeMenuView = swipeMenuView;
}
public void handleSwipeMenuDismissed()
{
// no-op for now
// Maas360Logger.i(TAG, "Dismissing swipe menu");
}
@Override
public boolean onTouch(View v, MotionEvent motionEvent)
{
if (mLockSwipe) {
return false;
}
if (mViewWidth < 2) {
mViewWidth = mListView.getWidth();
}
switch (motionEvent.getActionMasked())
{
case MotionEvent.ACTION_DOWN: {
if (mPaused) {
return false;
}
// Todo: ensure this is a finger, and set a flag
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mListView.getChildCount();
int[] listViewCoords = new int[2];
mListView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
Rect visibleRect = new Rect();
for (int i = 0; i < childCount; i++) {
child = mListView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y) && child instanceof View) {
child.getGlobalVisibleRect(visibleRect);
if (visibleRect.height() == child.getHeight()) {
mDownView = child;
break;
}
}
}
if (mDownView != null) {
mDownX = motionEvent.getRawX();
mDownY = motionEvent.getRawY();
mDownPosition = mListView.getPositionForView(mDownView);
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
}
return false;
}
case MotionEvent.ACTION_CANCEL: {
if (mVelocityTracker == null) {
break;
}
if (mDownView != null && mSwiping) {
// cancel
mSwipeMenuView.dismissSwipeMenu();
mDownView.setTranslationX(0);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownY = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
if (mCallbacks != null) {
mCallbacks.onSwipingEnded();
}
break;
}
case MotionEvent.ACTION_UP: {
if (mVelocityTracker == null || mDownView == null) {
break;
}
float deltaX = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
dismiss = true;
}
else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
&& absVelocityY < absVelocityX && mSwiping) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityX < 0) == (deltaX < 0);
}
if (dismiss && mDownPosition != ListView.INVALID_POSITION) {
// dismiss
// To do : remove assumption of View
mSwipeMenuView.showListItemMenuTouchable((View) mDownView);
mSwipeMenuView.setSwipeAnimationCallbacks(new SwipeMenuView.SwipeMenuVisibilityCallbacks() {
@Override
public void onSwipeAnimationStarted()
{
// no-op
}
@Override
public void onSwipeAnimationEnded()
{
}
@Override
public void onSwipeAnimationCanceled()
{
notifySwipeEnded();
}
@Override
public void onSwipeMenuDisplayed()
{
}
@Override
public void onSwipeMenuHidden()
{
notifySwipeEnded();
}
});
}
else {
if (mSwiping) {
// cancel
mSwipeMenuView.dismissSwipeMenu();
mDownView.setTranslationX(0);
mSwipeMenuView.setSwipeAnimationCallbacks(new SwipeMenuVisibilityCallbacks() {
@Override
public void onSwipeAnimationStarted()
{
}
@Override
public void onSwipeAnimationEnded()
{
notifySwipeEnded();
}
@Override
public void onSwipeAnimationCanceled()
{
notifySwipeEnded();
}
@Override
public void onSwipeMenuDisplayed()
{
}
@Override
public void onSwipeMenuHidden()
{
notifySwipeEnded();
}
});
}
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownY = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker == null || mPaused || mDownView == null) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
float deltaY = motionEvent.getRawY() - mDownY;
if (deltaX <= 0 && Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
mSwiping = true;
mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
mListView.requestDisallowInterceptTouchEvent(true);
// Cancel ListView's touch (un-highlighting the item)
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL
| (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mListView.onTouchEvent(cancelEvent);
cancelEvent.recycle();
// since swiping started, lets give the callback
if (mCallbacks != null) {
this.mCallbacks.onSwipingStarted();
}
}
if (mSwiping) {
float translationX = deltaX - mSwipingSlop;
if (translationX <= 0) {
mDownView.setTranslationX(translationX);
mSwipeMenuView.showListItemMenu((View) mDownView);
}
return true;
}
break;
}
}
return false;
}
private void notifySwipeEnded()
{
if (mCallbacks != null) {
this.mCallbacks.onSwipingEnded();
}
}
public AbsListView.OnScrollListener makeScrollListener()
{
return new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int scrollState)
{
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
@Override
public void onScroll(AbsListView absListView, int i, int i1, int i2)
{
}
};
}
public void setEnabled(boolean enabled)
{
this.mPaused = !enabled;
if (this.mSwipeMenuView != null) {
this.mSwipeMenuView.hideSwipeMenuWithoutTouch();
}
}
public void lockSwipability()
{
this.mLockSwipe = true;
}
public void unlockSwipability()
{
this.mLockSwipe = false;
}
}
<file_sep>/build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
/*def userHome = System.properties['user.home'];
def isLocal = project.hasProperty("isOnServer") ? false : true;
if (isLocal) {
maven {
url "file://${userHome}/.m2"
}
maven {
url "http://ivy.sysint.local/"
}
} else {
maven {
url "${remoteRepositoryPublishUrl}"
}
}*/
}
}<file_sep>/ForkRead/src/com/forkread/model/ForkReadServerSearchResults.java
package com.forkread.model;
import com.bluelinelabs.logansquare.annotation.JsonField;
import com.bluelinelabs.logansquare.annotation.JsonObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by dipesh on 19/05/15.
*/
@JsonObject
public class ForkReadServerSearchResults {
@JsonField
public List<ForkReadServerSearchResult> results = new ArrayList<ForkReadServerSearchResult>();
}
<file_sep>/ForkRead/src/com/forkread/sync/DataSyncAdapter.java
package com.forkread.sync;
/**
* Created by dipesh on 26/07/15.
*/
public class DataSyncAdapter {
}
<file_sep>/ForkRead/src/com/forkread/database/ForkReadDatabaseHelper.java
package com.forkread.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.forkread.application.ForkReadAppController;
public class ForkReadDatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "ForkRead.db";
public static final int DATABASE_VERSION = 1;
private static ForkReadDatabaseHelper sSingleton = null;
public ForkReadDatabaseHelper(Context paramContext)
{
super(paramContext, DATABASE_NAME, null, DATABASE_VERSION);
}
private void createTableBooks(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE IF NOT EXISTS "
+ Tables.Books + " ("
+ DatabaseContracts.BookColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ DatabaseContracts.BookColumns.BOOK_NAME + " TEXT NOT NULL, "
+ DatabaseContracts.BookColumns.CATEGORY + " TEXT, "
+ DatabaseContracts.BookColumns.ISBN + " TEXT unique, "
+ DatabaseContracts.BookColumns.DESCRIPTION + " TEXT, "
+ DatabaseContracts.BookColumns.BOOK_COVER_URL + " TEXT, "
+ DatabaseContracts.BookColumns.SYNCED_TO_SERVER + " INTEGER DEFAULT 0, "
+ DatabaseContracts.BookColumns.FLAGS + " INTEGER DEFAULT 0, "
+ DatabaseContracts.BookColumns.BOOK_SERVER_ID + " TEXT, "
+ DatabaseContracts.BookColumns.AUTHOR + " TEXT);"
);
}
private void createTableUsers(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE IF NOT EXISTS "
+ Tables.Users + " ("
+ DatabaseContracts.UserColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ DatabaseContracts.UserColumns.NAME + " TEXT NOT NULL, "
+ DatabaseContracts.UserColumns.USER_ID + " INTEGER, "
+ DatabaseContracts.UserColumns.EMAIL_ADDRESS + " TEXT, "
+ DatabaseContracts.UserColumns.GENDER + " TEXT, "
+ DatabaseContracts.UserColumns.PHONE_NO + " TEXT, "
+ DatabaseContracts.UserColumns.LOCATION + " TEXT, "
+ DatabaseContracts.UserColumns.LOGGED_IN_USER + " INTEGER DEFAULT 0, "
+ DatabaseContracts.UserColumns.LAST_MESSAGE_TIME + " INTEGER DEFAULT 0, "
+ DatabaseContracts.UserColumns.UNSEEN_MESSAGE + " INTEGER DEFAULT 0, "
+ DatabaseContracts.UserColumns.AUTH_TOKEN + " TEXT, "
+ DatabaseContracts.UserColumns.IS_ACTIVE + " INTEGER, "
+ DatabaseContracts.UserColumns.IS_VERIFIED + " INTEGER, "
+ DatabaseContracts.UserColumns.PHOTO_URI + " TEXT);"
);
}
private void createTableMessages(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE IF NOT EXISTS "
+ Tables.Messages + " ("
+ DatabaseContracts.MessagesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ DatabaseContracts.MessagesColumns.MESSAGE + " TEXT NOT NULL, "
+ DatabaseContracts.MessagesColumns.RECEIVED + " INTEGER DEFAULT 0, "
+ DatabaseContracts.MessagesColumns.SYNCED + " INTEGER DEFAULT 0, "
+ DatabaseContracts.MessagesColumns.TIME + " INTEGER NOT NULL, "
+ DatabaseContracts.MessagesColumns.FLAG_READ + " INTEGER DEFAULT 0, "
+ DatabaseContracts.MessagesColumns.MESSAGE_SERVER_ID + " INTEGER, "
+ DatabaseContracts.MessagesColumns.USERID + " INTEGER NOT NULL);"
);
}
public static ForkReadDatabaseHelper getInstance(Context paramContext)
{
if (sSingleton == null)
sSingleton = new ForkReadDatabaseHelper(paramContext);
return sSingleton;
}
@Override
public void onCreate(SQLiteDatabase db)
{
createTableUsers(db);
createTableBooks(db);
createTableMessages(db);
}
@Override
public void onUpgrade(SQLiteDatabase paramSQLiteDatabase, int oldVersion, int newVersion)
{
}
public interface Tables
{
String Books = "ForkReadBooks";
String Users = "ForkReadUsers";
String Messages = "Messages";
}
}<file_sep>/ForkRead/src/com/forkread/login/ForkReadLoginActivity.java
package com.forkread.login;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bluelinelabs.logansquare.LoganSquare;
import com.book.forkread.R;
import com.forkread.application.ForkReadAppController;
import com.forkread.database.DatabaseContracts.UserColumns;
import com.forkread.database.DatabaseContracts.Users;
import com.forkread.model.User;
import com.forkread.ui.PhoneNumberVerificationFragment;
import com.forkread.utils.Constants;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import me.zhanghai.android.materialprogressbar.IndeterminateProgressDrawable;
public class ForkReadLoginActivity extends FragmentActivity implements PhoneNumberVerificationFragment.PhoneNumberValidationCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public static final String TAG = ForkReadLoginActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private ProgressDialog mProgressDialog;
private User mUser;
private Location mLastLocation;
private void cancelProgressDialog() {
if (this.mProgressDialog.isShowing()) this.mProgressDialog.cancel();
}
private void fireRegisterRequest() throws JSONException {
JSONObject userJson = new JSONObject();
userJson.put("number", mUser.number);
userJson.put("email", mUser.email);
userJson.put("name", mUser.name);
JsonObjectRequest request = new JsonObjectRequest(Method.POST, "http://api.forkread.com/api/user",
userJson, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
try {
if (!response.getBoolean("already_registered")) {
ContentValues cv = new ContentValues();
cv.put(UserColumns.EMAIL_ADDRESS, mUser.email);
cv.put(UserColumns.PHONE_NO, mUser.number);
cv.put(UserColumns.NAME, mUser.name);
cv.put(UserColumns.IS_ACTIVE, false);
cv.put(UserColumns.IS_VERIFIED, false);
getContentResolver().insert(Users.CONTENT_URI, cv);
loadOtpFragment(mUser.number);
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
cancelProgressDialog();
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
ForkReadAppController.getInstance().addToRequestQueue(request, "tag_json_obj");
}
private void fireLoginRequest() throws JSONException {
JSONObject userJson = new JSONObject();
userJson.put("number", mUser.number);
userJson.put("email", mUser.email);
JsonObjectRequest request = new JsonObjectRequest(Method.POST, "http://api.forkread.com/api/user/login",
userJson, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
try {
User user = LoganSquare.parse(response.toString(), User.class);
if (response.length() > 0) {
ContentValues cv = new ContentValues();
cv.put(UserColumns.EMAIL_ADDRESS, mUser.email);
cv.put(UserColumns.PHONE_NO, mUser.number);
cv.put(UserColumns.NAME, user.name);
cv.put(UserColumns.USER_ID, user.id);
cv.put(UserColumns.IS_ACTIVE, user.active);
cv.put(UserColumns.IS_VERIFIED, user.verified);
getContentResolver().insert(Users.CONTENT_URI, cv);
loadOtpFragment(mUser.number);
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
cancelProgressDialog();
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
ForkReadAppController.getInstance().addToRequestQueue(request, "tag_json_obj");
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setIndeterminateDrawable(new IndeterminateProgressDrawable(this));
loadLoginFragment(null, null);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
public void loadLoginFragment(String email, String number) {
Fragment fragment = LoginFragment.newInstance();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString(LoginFragment.ARGS_EMAIL, email);
args.putString(LoginFragment.ARGS_PHONE, number);
ft.replace(R.id.login_signup_container, fragment);
ft.commit();
}
public void loadSignupFragment() {
Fragment fragment = SignupFragment.newInstance();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.login_signup_container, fragment);
ft.commit();
}
private void loadOtpFragment(String number) {
Fragment fragment = PhoneNumberVerificationFragment.newInstance(number);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.login_signup_container, fragment).commit();
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
}
public void registerUser(Location location, String phoneNo) throws JSONException {
User.UserLocation userLocation = new User.UserLocation();
User.Position position = new User.Position();
position.latitude = location.getLatitude();
position.longitude = location.getLongitude();
userLocation.position = position;
mUser.location = userLocation;
mUser.number = phoneNo;
fireRegisterRequest();
}
@Override
public void onValidationDone(Location location, String phoneNo) {
try {
registerUser(location, phoneNo);
} catch (JSONException e) {
}
}
public void onLoginClicked(String number, String email) {
mUser = new User();
mUser.number = number;
mUser.email = email;
try {
fireLoginRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onRegisterClicked(String name, String email, String number) {
mUser = new User();
mUser.number = number;
mUser.name = name;
mUser.email = email;
try {
fireRegisterRequest();
} catch (JSONException e) {
}
}
@Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
new GetLocation(mLastLocation).execute();
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
private class GetLocation extends AsyncTask<Void, Void, Void> {
private Location mLocation;
public GetLocation (Location location) {
mLocation = location;
}
@Override
protected Void doInBackground(Void... params) {
Geocoder geocoder = new Geocoder(ForkReadLoginActivity.this);
try {
List<Address> results = geocoder.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(), 10);
for (Address address : results) {
address.getLatitude();
if (address.getMaxAddressLineIndex() > 0) {
String country = address.getCountryName();
String city = address.getLocality();
SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREFERENCE_KEY, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.SHARED_PREFERENCE_CITY_KEY, city);
editor.putString(Constants.SHARED_PREFERENCE_COUNTRY_KEY, country);
editor.commit();
}
}
}
catch (Exception e) {
}
return null;
}
}
}<file_sep>/ForkRead/src/com/forkread/database/ForkReadDataProvider.java
package com.forkread.database;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import com.forkread.database.ForkReadDatabaseHelper.Tables;
public class ForkReadDataProvider extends ContentProvider {
public static final String AUTHORITY = "com.forkread.db";
public static final String TAG = ForkReadDataProvider.class.getSimpleName();
private static final int BOOKS = 1;
private static final int BOOKS_ID = 2;
private static final int USERS = 3;
private static final int USERS_ID = 4;
private static final UriMatcher sUriMatcher = new UriMatcher(-1);
private Context mContext;
private SQLiteDatabase mDb;
private ForkReadDatabaseHelper mDbHelper;
static {
sUriMatcher.addURI("com.forkread.db", "books", BOOKS);
sUriMatcher.addURI("com.forkread.db", "books/#", BOOKS_ID);
sUriMatcher.addURI("com.forkread.db", "users", USERS);
sUriMatcher.addURI("com.forkread.db", "users/#", USERS_ID);
}
public int delete(Uri paramUri, String paramString, String[] paramArrayOfString) {
switch (sUriMatcher.match(paramUri)) {
case BOOKS:
return 0;
case BOOKS_ID:
return 0;
case USERS:
return 0;
default:
throw new IllegalArgumentException();
}
}
public String getType(Uri paramUri) {
return null;
}
public Uri insert(Uri uri, ContentValues contentValues) {
long id;
String tableName;
switch (sUriMatcher.match(uri)) {
case BOOKS:
tableName = Tables.Books;
break;
case USERS:
tableName = Tables.Users;
break;
default:
throw new IllegalArgumentException();
}
id = mDb.insert(tableName, null, contentValues);
return ContentUris.withAppendedId(uri, id);
}
public boolean onCreate() {
Log.d(TAG, "initializing provider");
this.mContext = getContext();
this.mDbHelper = ForkReadDatabaseHelper.getInstance(this.mContext);
this.mDb = this.mDbHelper.getWritableDatabase();
return true;
}
public Cursor query(Uri paramUri, String[] paramArrayOfString1, String paramString1, String[] paramArrayOfString2,
String paramString2) {
switch (sUriMatcher.match(paramUri)) {
case BOOKS:
case BOOKS_ID:
return this.mDb.query(Tables.Books, paramArrayOfString1, paramString1, paramArrayOfString2, null, null,
paramString2);
case USERS:
case USERS_ID:
return this.mDb.query(Tables.Users, paramArrayOfString1, paramString1, paramArrayOfString2, null, null,
paramString2);
default:
return null;
}
}
public int update(Uri paramUri, ContentValues contentValues, String paramString, String[] paramArrayOfString) {
String tableName;
switch (sUriMatcher.match(paramUri)) {
case BOOKS:
case BOOKS_ID:
tableName = Tables.Books;
break;
case USERS:
case USERS_ID:
tableName = Tables.Users;
break;
default:
throw new IllegalArgumentException();
}
return mDb.update(tableName, contentValues, paramString, paramArrayOfString);
}
}<file_sep>/ForkRead/src/com/forkread/ui/SwipeMenuView.java
package com.forkread.ui;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class SwipeMenuView extends LinearLayout implements View.OnClickListener
{
public static interface MenuActionCallbacks
{
public void onSwipeActionReadToggled(View item);
public void onSwipeActionFavoriteToggled(View item);
public void onSwipeActionDelete(View item);
public void onSwipeActionMove(View item);
public void onSwipeActionReply(View item);
public void onSwipeActionSnooze(View item);
}
public static interface SwipeMenuVisibilityCallbacks
{
public void onSwipeAnimationStarted();
public void onSwipeAnimationEnded();
public void onSwipeAnimationCanceled();
public void onSwipeMenuDisplayed();
public void onSwipeMenuHidden();
}
private static final String TAG = SwipeMenuView.class.getSimpleName();
public static final int SWIPE_DELETE_ACTION = 1;
public static final int SWIPE_REPLY_ACTION = 2;
public static final int SWIPE_READ_UNREAD_ACTION = 3;
public static final int SWIPE_FAV_ACTION = 4;
public static final int SWIPE_MOVE_ACTION = 5;
public static final int SWIPE_SNOOZE_ACTION = 6;
private WindowManager windowManager;
private Context mContext;
private View listItem;
private boolean isShowingFull = false;
private float mLastTouchDownX = 0;
private float mLastTouchDownY;
private boolean mHoriSwiping;
private static int sScaledTouchSlop = -1;
private static int sMinFlingVelocity;
private static int sMaxFlingVelocity;
private Rect mViewClipBounds = null;
private static final int TOUCH_SLOP = 24;
public static final int SWIPE_ANIMATION_TIME = 150;
private int[] fullShowingLocation = new int[2];
private boolean isWindowAdded = false;
private VelocityTracker mVelocityTracker;
private SwipeMenuListViewTouchListener swipeMenuListViewTouchInterpreter = null;
private SwipeMenuVisibilityCallbacks swipeMenuVisibilityCallbacks = null;
// action buttons
private ImageButton deleteButton;
private ImageButton moveMessagesButton;
private ImageButton readUnreadButton;
private ImageButton favUnfavButton;
private ImageButton replyButton;
private ImageButton snoozeButton;
private MenuActionCallbacks menuActionsCallbacks;
private boolean mIsInterceptScrolling;
private float mLastInterceptTouchDownX;
private boolean mIsAnimating;
private ValueAnimator animator;
private boolean requiresViewClipping = false;
public SwipeMenuView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init(context);
}
public SwipeMenuView(Context context, AttributeSet attrs)
{
super(context, attrs);
init(context);
}
public SwipeMenuView(Context context)
{
super(context);
init(context);
}
private void init(Context context)
{
windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
mContext = context;
}
public void setSwipeMenuTouchListViewInterpreter(SwipeMenuListViewTouchListener swipeMenuListViewTouchListener)
{
if (swipeMenuListViewTouchListener != null) {
this.swipeMenuListViewTouchInterpreter = swipeMenuListViewTouchListener;
this.swipeMenuListViewTouchInterpreter.setSwipeMenuView(this);
}
}
public void setRequiresViewClipping(boolean requiresViewClipping)
{
this.requiresViewClipping = requiresViewClipping;
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
initializeSlop(getContext());
if (!isShowingFull) {
return super.onTouchEvent(event);
}
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
mLastTouchDownX = event.getRawX();
mLastTouchDownY = event.getRawY();
getLocationOnScreen(fullShowingLocation);
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(event);
break;
case MotionEvent.ACTION_MOVE:
if (mVelocityTracker != null) {
mVelocityTracker.addMovement(event);
}
float deltaX = event.getRawX() - mLastTouchDownX;
float deltaY = event.getRawY() - mLastTouchDownY;
if (mLastTouchDownX < event.getRawX() && Math.abs(deltaX) > sScaledTouchSlop
&& Math.abs(deltaY) < Math.abs(deltaX) / 2) {
mHoriSwiping = true;
}
if (mHoriSwiping) {
if (deltaX < 0) {
deltaX = 0;
}
else if (deltaX > listItem.getWidth()) {
deltaX = listItem.getWidth();
}
listItem.setTranslationX(listItem.getLeft() + deltaX);
showListItemMenu(Math.round(deltaX));
}
else {
// ignore..earlier used for logger debugging
}
break;
case MotionEvent.ACTION_UP:
deltaX = event.getRawX() - mLastTouchDownX;
boolean dismiss = false;
if (Math.abs(deltaX) > (listItem.getRight() - listItem.getLeft()) / 4 && deltaX > 0) {
dismiss = true;
}
else {
if (mVelocityTracker != null) {
mVelocityTracker.addMovement(event);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
if (sMinFlingVelocity <= absVelocityX && absVelocityX <= sMaxFlingVelocity
&& absVelocityY < absVelocityX) {
// dismiss only if flinging in the same direction as
// dragging
dismiss = (velocityX > 0) && (deltaX > 0);
}
}
}
if (dismiss) {
dismissSwipeMenu();
}
else {
showListItemMenuTouchable(listItem);
}
mHoriSwiping = false;
mLastTouchDownX = 0;
mLastTouchDownY = 0;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
case MotionEvent.ACTION_OUTSIDE:
hideSwipeMenuWithoutTouch();
break;
default:
return false;
}
return true;
}
private void initializeSlop(Context context)
{
if (sScaledTouchSlop == -1) {
final Resources res = context.getResources();
final Configuration config = res.getConfiguration();
final float density = res.getDisplayMetrics().density;
final float sizeAndDensity;
if (config.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_XLARGE)) {
sizeAndDensity = density * 1.5f;
}
else {
sizeAndDensity = density;
}
sScaledTouchSlop = (int) (sizeAndDensity * TOUCH_SLOP + 0.5f);
ViewConfiguration vc = ViewConfiguration.get(context);
sMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
sMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
}
}
public void hideSwipeMenuWithoutTouch()
{
cancelExistingAnimation();
WindowManager.LayoutParams p = (WindowManager.LayoutParams) getLayoutParams();
setVisibility(View.GONE);
p.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
windowManager.updateViewLayout(this, p);
if (listItem != null) {
listItem.setTranslationX(0);
}
if (swipeMenuListViewTouchInterpreter != null) {
swipeMenuListViewTouchInterpreter.handleSwipeMenuDismissed();
}
if (swipeMenuVisibilityCallbacks != null) {
swipeMenuVisibilityCallbacks.onSwipeMenuHidden();
}
setViewClipBounds(null);
isShowingFull = false;
mIsInterceptScrolling = false;
}
private void cancelExistingAnimation()
{
if (mIsAnimating && animator != null) {
animator.cancel();
animator = null;
mIsAnimating = false;
}
}
protected void dismissSwipeMenu()
{
cancelExistingAnimation();
WindowManager.LayoutParams p = (WindowManager.LayoutParams) getLayoutParams();
final int originalSwipeX = p.x;
isShowingFull = false;
mIsInterceptScrolling = false;
final float originalListItemX = listItem.getX();
animator = ValueAnimator.ofFloat(0, Math.abs(originalListItemX));
animator.setDuration(SWIPE_ANIMATION_TIME);
animator.setInterpolator(new AccelerateInterpolator(1.0f));
animator.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation)
{
mIsAnimating = true;
float value = ((Float) (animation.getAnimatedValue())).floatValue();
listItem.setTranslationX(value + originalListItemX);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) getLayoutParams();
p.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
p.x = originalSwipeX + (int) value;
windowManager.updateViewLayout(SwipeMenuView.this, p);
Rect clipBounds = new Rect(getLeft(), getTop(), getLeft() + (int) Math.abs(value + originalListItemX),
getBottom());
setViewClipBounds(clipBounds);
}
});
animator.addListener(new AnimatorListener() {
@Override
public void onAnimationStart(Animator animation)
{
if (swipeMenuVisibilityCallbacks != null) {
swipeMenuVisibilityCallbacks.onSwipeAnimationStarted();
}
}
@Override
public void onAnimationRepeat(Animator animation)
{
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animator animation)
{
if (swipeMenuVisibilityCallbacks != null) {
swipeMenuVisibilityCallbacks.onSwipeAnimationEnded();
}
resetMenuPositions();
}
@Override
public void onAnimationCancel(Animator animation)
{
if (swipeMenuVisibilityCallbacks != null) {
swipeMenuVisibilityCallbacks.onSwipeAnimationCanceled();
}
resetMenuPositions();
}
});
animator.start();
}
protected void resetMenuPositions()
{
setTranslationX(0);
setVisibility(View.GONE);
listItem.setTranslationX(0);
mIsAnimating = false;
setViewClipBounds(null);
if (swipeMenuListViewTouchInterpreter != null) {
swipeMenuListViewTouchInterpreter.handleSwipeMenuDismissed();
}
if (swipeMenuVisibilityCallbacks != null) {
swipeMenuVisibilityCallbacks.onSwipeMenuHidden();
}
}
public void addToWindowInvisible(int[] viewActions)
{
setVisibility(View.INVISIBLE);
WindowManager.LayoutParams p = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, PixelFormat.TRANSLUCENT);
windowManager.addView(this, p);
isWindowAdded = true;
/* deleteButton = (ImageButton) findViewById(R.id.swipe_menu_delete);
moveMessagesButton = (ImageButton) findViewById(R.id.swipe_menu_move);
readUnreadButton = (ImageButton) findViewById(R.id.swipe_menu_read);
favUnfavButton = (ImageButton) findViewById(R.id.swipe_menu_star);
replyButton = (ImageButton) findViewById(R.id.swipe_menu_reply);
if (isReplyAllDefault()) {
replyButton.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_reply_all));
}
snoozeButton = (ImageButton) findViewById(R.id.swipe_menu_snooze);*/
deleteButton.setOnClickListener(this);
moveMessagesButton.setOnClickListener(this);
readUnreadButton.setOnClickListener(this);
favUnfavButton.setOnClickListener(this);
replyButton.setOnClickListener(this);
snoozeButton.setOnClickListener(this);
setViewActionsVisibility(viewActions);
}
@TargetApi (Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void showListItemMenu(int deltaX)
{
cancelExistingAnimation();
WindowManager.LayoutParams p = (WindowManager.LayoutParams) getLayoutParams();
this.listItem.setTranslationX(listItem.getLeft() - listItem.getRight() + deltaX);
p.x = fullShowingLocation[0] + deltaX;
p.y = fullShowingLocation[1];
p.height = listItem.getHeight();
p.width = listItem.getRight() - listItem.getLeft();
p.flags = WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
p.gravity = Gravity.START | Gravity.TOP;
setVisibility(View.VISIBLE);
windowManager.updateViewLayout(this, p);
Rect clipBounds = new Rect(getLeft(), getTop(), getLeft()
+ Math.abs(listItem.getLeft() - listItem.getRight() + deltaX), getBottom());
setViewClipBounds(clipBounds);
}
public void showListItemMenu(View listItem, int[] actions)
{
setViewActionsVisibility(actions);
showListItemMenu(listItem);
}
@TargetApi (Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void showListItemMenu(View listItem)
{
if (this.listItem != null && this.listItem != listItem) {
this.listItem.setTranslationX(0);
}
cancelExistingAnimation();
this.listItem = listItem;
WindowManager.LayoutParams p = (WindowManager.LayoutParams) getLayoutParams();
int[] location = new int[2];
listItem.getLocationOnScreen(location);
p.x = location[0] + listItem.getRight() - listItem.getLeft();
p.y = location[1];
p.height = listItem.getHeight();
p.width = listItem.getRight() - listItem.getLeft();
p.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
p.gravity = Gravity.START | Gravity.TOP;
setVisibility(View.VISIBLE);
windowManager.updateViewLayout(this, p);
int deltaX = (int) Math.abs(listItem.getLeft() - listItem.getTranslationX());
Rect clipBounds = new Rect(getLeft(), getTop(), getLeft() + Math.abs(deltaX), getBottom());
setViewClipBounds(clipBounds);
isShowingFull = false;
// update out siwpe menu text
/*readUnreadButton.setImageResource(this.listItem.mRead ? R.drawable.ic_menu_mark_unread_holo_light
: R.drawable.ic_menu_mark_read_holo_light);
favUnfavButton.setImageResource(this.listItem.mIsFavorite ? R.drawable.ic_menu_star_off_holo_light
: R.drawable.ic_menu_flagged_holo_light);
snoozeButton.setImageResource(this.listItem.mIsSnoozed ? R.drawable.ic_alarm__cancel_holo_light
: R.drawable.ic_alarm_holo_light);
readUnreadButton.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v)
{
Toast.makeText(
getContext(),
SwipeMenuView.this.listItem.mRead ? R.string.mark_as_unread_action
: R.string.mark_as_read_action, Toast.LENGTH_SHORT).show();
return true;
}
});
favUnfavButton.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v)
{
Toast.makeText(
getContext(),
SwipeMenuView.this.listItem.mIsFavorite ? R.string.mark_as_unfav_action
: R.string.mark_as_fav_action, Toast.LENGTH_SHORT).show();
return true;
}
});
deleteButton.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v)
{
Toast.makeText(getContext(), R.string.delete_action, Toast.LENGTH_SHORT).show();
return true;
}
});
moveMessagesButton.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v)
{
Toast.makeText(getContext(), R.string.move_action, Toast.LENGTH_SHORT).show();
return true;
}
});
replyButton.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v)
{
if (isReplyAllDefault()) {
Toast.makeText(getContext(), R.string.reply_all_action, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getContext(), R.string.reply_action, Toast.LENGTH_SHORT).show();
}
return true;
}
});*/
}
private void setViewActionsVisibility(int[] actions)
{
if (actions != null) {
for (int action : actions) {
if (action == SWIPE_DELETE_ACTION) {
deleteButton.setVisibility(View.VISIBLE);
}
else if (action == SWIPE_FAV_ACTION) {
favUnfavButton.setVisibility(View.VISIBLE);
}
else if (action == SWIPE_MOVE_ACTION) {
moveMessagesButton.setVisibility(View.VISIBLE);
}
else if (action == SWIPE_REPLY_ACTION) {
replyButton.setVisibility(View.VISIBLE);
}
else if (action == SWIPE_READ_UNREAD_ACTION) {
readUnreadButton.setVisibility(View.VISIBLE);
}
else if (action == SWIPE_SNOOZE_ACTION) {
snoozeButton.setVisibility(View.VISIBLE);
}
}
}
}
public void showListItemMenuTouchable(final View listItem, int[] actions)
{
setViewActionsVisibility(actions);
showListItemMenuTouchable(listItem);
}
public void showListItemMenuTouchable(final View listItem)
{
cancelExistingAnimation();
this.listItem = listItem;
mIsInterceptScrolling = false;
final int widthOfListItem = this.listItem.getRight() - this.listItem.getLeft();
final float currentTranslationXOfListItem = this.listItem.getTranslationX();
animator = ValueAnimator.ofFloat(currentTranslationXOfListItem, -1 * widthOfListItem);
animator.setDuration(SWIPE_ANIMATION_TIME);
animator.setInterpolator(new AccelerateInterpolator(1.0f));
animator.addUpdateListener(new AnimatorUpdateListener() {
@TargetApi (Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void onAnimationUpdate(ValueAnimator animation)
{
mIsAnimating = true;
float value = ((Float) (animation.getAnimatedValue())).floatValue();
SwipeMenuView.this.listItem.setTranslationX(value);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) getLayoutParams();
int[] location = new int[2];
listItem.getLocationOnScreen(location);
p.x = location[0] + listItem.getRight() - listItem.getLeft();
p.y = location[1];
p.height = listItem.getHeight();
p.width = listItem.getRight() - listItem.getLeft();
p.gravity = Gravity.START | Gravity.TOP;
p.flags = WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
setVisibility(View.VISIBLE);
windowManager.updateViewLayout(SwipeMenuView.this, p);
int deltaX = (int) Math.abs(listItem.getLeft() - listItem.getTranslationX());
Rect clipBounds = new Rect(getLeft(), getTop(), getLeft() + Math.abs(deltaX), getBottom());
setViewClipBounds(clipBounds);
}
});
animator.addListener(new AnimatorListener() {
@Override
public void onAnimationStart(Animator animation)
{
if (swipeMenuVisibilityCallbacks != null) {
swipeMenuVisibilityCallbacks.onSwipeAnimationStarted();
}
}
@Override
public void onAnimationRepeat(Animator animation)
{
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animator animation)
{
if (swipeMenuVisibilityCallbacks != null) {
swipeMenuVisibilityCallbacks.onSwipeAnimationEnded();
}
mIsAnimating = false;
isShowingFull = true;
setViewClipBounds(null);
}
@Override
public void onAnimationCancel(Animator animation)
{
if (swipeMenuVisibilityCallbacks != null) {
swipeMenuVisibilityCallbacks.onSwipeAnimationCanceled();
}
resetMenuPositions();
}
});
animator.start();
}
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event)
{
// irrespective of any key event -- hide swipe menu
hideSwipeMenuWithoutTouch();
return super.dispatchKeyEventPreIme(event);
}
public void removeSelf()
{
if (isWindowAdded) {
cancelExistingAnimation();
windowManager.removeViewImmediate(this);
isWindowAdded = false;
}
}
public void setMenuActionCallbacks(MenuActionCallbacks callbacks)
{
this.menuActionsCallbacks = callbacks;
}
public void setSwipeAnimationCallbacks(SwipeMenuVisibilityCallbacks callbacks)
{
this.swipeMenuVisibilityCallbacks = callbacks;
}
@Override
public void onClick(View v)
{
if (menuActionsCallbacks != null) {
hideSwipeMenuWithoutTouch();
/*if (v.getId() == R.id.swipe_menu_reply) {
menuActionsCallbacks.onSwipeActionReply(listItem);
}
else if (v.getId() == R.id.swipe_menu_delete) {
menuActionsCallbacks.onSwipeActionDelete(listItem);
}
else if (v.getId() == R.id.swipe_menu_move) {
menuActionsCallbacks.onSwipeActionMove(listItem);
}
else if (v.getId() == R.id.swipe_menu_read) {
menuActionsCallbacks.onSwipeActionReadToggled(listItem);
}
else if (v.getId() == R.id.swipe_menu_star) {
menuActionsCallbacks.onSwipeActionFavoriteToggled(listItem);
}
else if (v.getId() == R.id.swipe_menu_snooze) {
menuActionsCallbacks.onSwipeActionSnooze(listItem);
}*/
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev)
{
// Maas360Logger.i(TAG, "intercepting touch event with previous move" +
// mIsIncerceptScrolling);
initializeSlop(getContext());
final int action = ev.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
if (mIsInterceptScrolling) {
mIsInterceptScrolling = false;
// Maas360Logger.i(TAG,
// "action cancel: not intercepting touch event with previous move");
return true;
}
else {
return false;
}
}
switch (action)
{
case MotionEvent.ACTION_DOWN: {
// Maas360Logger.i(TAG,
// "action down: not intercepting touch event with previous move");
mLastInterceptTouchDownX = ev.getRawX();
mLastTouchDownX = ev.getRawX();
mLastTouchDownY = ev.getRawY();
getLocationOnScreen(fullShowingLocation);
}
case MotionEvent.ACTION_MOVE: {
if (mIsInterceptScrolling) {
// Maas360Logger.i(TAG,
// "action move: returning true as mIsIncerceptScrolling is already true");
return true;
}
// If the user has dragged her finger horizontally more than
// the touch slop, start the scroll
// left as an exercise for the reader
float deltaX = ev.getRawX() - mLastInterceptTouchDownX;
// Touch slop should be calculated using ViewConfiguration
// constants.
if (deltaX > sScaledTouchSlop) {
// Maas360Logger.i(TAG,
// "action move: returning true as deltaX is greater than touch slop");
mIsInterceptScrolling = true;
return true;
}
else {
// Maas360Logger.i(TAG,
// "action move: returning false as mIsIncerceptScrolling is false");
}
break;
}
}
// In general, we don't want to intercept touch events. They should be
// handled by the child view.
return false;
}
@TargetApi (Build.VERSION_CODES.HONEYCOMB)
private void setViewClipBounds(Rect clipBounds)
{
if (clipBounds != null && requiresViewClipping) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
setWillNotDraw(false);
if (clipBounds.equals(mViewClipBounds)) {
return;
}
if (mViewClipBounds == null) {
invalidate();
mViewClipBounds = new Rect(clipBounds);
}
else {
invalidate(Math.min(mViewClipBounds.left, clipBounds.left),
Math.min(mViewClipBounds.top, clipBounds.top),
Math.max(mViewClipBounds.right, clipBounds.right),
Math.max(mViewClipBounds.bottom, clipBounds.bottom));
mViewClipBounds.set(clipBounds);
}
}
else {
setLayerType(View.LAYER_TYPE_HARDWARE, null);
setWillNotDraw(true);
if (mViewClipBounds != null) {
invalidate();
mViewClipBounds = null;
}
}
}
@Override
public void draw(Canvas canvas)
{
if (mViewClipBounds != null) {
canvas.clipRect(mViewClipBounds);
}
super.draw(canvas);
}
}
<file_sep>/ForkRead/src/com/forkread/ui/BooksDetailsActivity.java
package com.forkread.ui;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.bluelinelabs.logansquare.LoganSquare;
import com.book.forkread.R;
import com.forkread.application.ForkReadAppController;
import com.forkread.model.Books;
import com.forkread.model.Books.Book;
import com.forkread.model.User;
import com.forkread.utils.ForkReadUtils;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class BooksDetailsActivity extends ActionBarActivity implements View.OnClickListener
{
public static final String BUNDLE_KEY_BOOK_VIEW = "BUNDLE_KEY_BOOK_VIEW_DETAILS";
private TextView mAuthors;
private Book mBook;
private ImageView mBookImage;
private TextView mCategories;
private TextView mDescription;
private String mJsonData;
private RatingBar mRating;
private Button mSave;
private TextView mTitle;
private User mUser;
private boolean mShowDescription = true;
private void initiateUI()
{
mAuthors = ((TextView) findViewById(R.id.book_details_author));
mCategories = ((TextView) findViewById(R.id.book_details_category));
mDescription = ((TextView) findViewById(R.id.book_details_description));
mRating = ((RatingBar) findViewById(R.id.book_details_rating));
mTitle = ((TextView) findViewById(R.id.book_details_title));
mBookImage = ((ImageView) findViewById(R.id.book_details_thumbnail));
mSave = ((Button) findViewById(R.id.book_details_save));
mSave.setOnClickListener(this);
mTitle.setText(mBook.volumeInfo.title);
mAuthors.setText(getString(R.string.by) + mBook.volumeInfo.authors.toString().replace("[","").replace("]",""));
if (mBook.volumeInfo.genre != null) {
mCategories.setText(getString(R.string.genre_book_detail) + mBook.volumeInfo.toString().replace("[","").replace("]",""));
}
mDescription.setText(mBook.volumeInfo.description);
mDescription.setOnClickListener(this);
mRating.setRating((float) mBook.volumeInfo.averageRating);
if (!TextUtils.isEmpty(mBook.volumeInfo.imageLinks.thumbnail)) {
Picasso.with(this).load(mBook.volumeInfo.imageLinks.thumbnail).fit().into(mBookImage);
}
}
public void onClick(View paramView)
{
if (paramView.getId() == R.id.book_details_description) {
if (mShowDescription) {
mShowDescription = false;
mDescription.setMaxLines(2555);
}
else {
mShowDescription = true;
mDescription.setMaxLines(3);
}
return;
}
JSONObject localJSONObject = new JSONObject();
try {
localJSONObject.put("user", this.mUser.userId);
JSONArray localJSONArray = new JSONArray();
localJSONArray.put(mBook.getJsonObject());
localJSONObject.put("books", localJSONArray);
ForkReadUtils.makeAddBookRequest(this, localJSONObject);
return;
}
catch (JSONException localJSONException) {
localJSONException.printStackTrace();
}
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(R.layout.book_details_view);
mUser = ForkReadAppController.getInstance().getUser();
mJsonData = getIntent().getExtras().getString(BUNDLE_KEY_BOOK_VIEW);
try {
Books books = LoganSquare.parse(mJsonData, Books.class);
mBook = books.items.get(0);
} catch (IOException e) {
}
ActionBar actionbar = getSupportActionBar();
actionbar.setTitle(R.string.scanned_book);
actionbar.setDisplayUseLogoEnabled(false);
actionbar.setIcon(new ColorDrawable(getResources().getColor(R.color.app_theme)));
actionbar.setDisplayHomeAsUpEnabled(true);
initiateUI();
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
if (paramMenuItem.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(paramMenuItem);
}
}<file_sep>/ForkRead/src/com/forkread/ui/GenreSelectionActivity.java
package com.forkread.ui;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.book.forkread.R;
import com.forkread.adapters.GenreSelectionAdapter;
/**
* Created by dipesh on 15/05/16.
*/
public class GenreSelectionActivity extends AppCompatActivity {
private GenreSelectionAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_genre_selection);
mAdapter = new GenreSelectionAdapter(this);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.genre_recycler_view);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(mAdapter);
// request and search pending
}
}
<file_sep>/ForkRead/build.gradle
// apply plugin: 'android-library'
apply plugin: 'com.android.application'
apply plugin: 'android-apt'
apply from: "$project.rootDir/android_common.gradle"
apt {
arguments {
androidManifestFile variant.outputs[0].processResources.manifestFile
resourcePackageName 'com.forkread'
}
}
dependencies {
compile fileTree(include: '*.jar', dir: 'libs')
compile 'com.google.android.gms:play-services:7.5.0'
apt 'com.bluelinelabs:logansquare-compiler:1.1.0'
compile 'com.bluelinelabs:logansquare:1.1.0'
compile 'me.dm7.barcodescanner:zxing:1.8.2'
compile 'com.android.support:design:23.1.1'
compile 'com.github.ksoichiro:android-observablescrollview:1.6.0'
compile 'me.zhanghai.android.materialprogressbar:library:1.1.4'
compile 'com.googlecode.libphonenumber:libphonenumber:7.0.+'
}
<file_sep>/android_common.gradle
android {
compileSdkVersion 23
buildToolsVersion "22.0.1"
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
dexOptions {
jumboMode = true
}
defaultConfig {
minSdkVersion 15
targetSdkVersion 23
}
signingConfigs {
debug {
storeFile file("ForkReadKeystore.jks")
storePassword "<PASSWORD>"
keyAlias "forkread"
keyPassword "<PASSWORD>"
}
release {
storeFile file("ForkReadKeystore.jks")
storePassword "<PASSWORD>"
keyAlias "forkread"
keyPassword "<PASSWORD>"
}
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
jniLibs.srcDirs = ['libs']
}
}
lintOptions {
abortOnError true
check 'NewApi',
'InconsistentArrays',
'WrongViewCast',
'MissingRegistered',
'StyleCycle',
'DuplicateActivity',
'UsesMinSdkAttributes',
'UnknownId',
'DalvikOverride',
'Instantiatable',
'LocalSuppress',
'Deprecated',
'StringFormatCount',
'HardcodedDebugMode',
'WorldReadableFiles',
'WorldWriteableFiles',
'DrawAllocation',
'SecureRandom',
'ViewTag',
'UseValueOf',
'EnforceUTF8'
warningsAsErrors true
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
}
}<file_sep>/ForkRead/src/com/forkread/ui/ForkReadBaseActivity.java
package com.forkread.ui;
import android.app.Activity;
import android.os.Bundle;
public class ForkReadBaseActivity extends Activity
{
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
}
}<file_sep>/ForkRead/src/com/forkread/utils/URLConstants.java
package com.forkread.utils;
/**
* Created by dipesh on 24/04/15.
*/
public class URLConstants {
public static final String BASE_TEST_URL = "http://www.test.forkread.com/api/";
public static final String BASE_PROD_URL = "http://www.forkread.com/api/";
public static final String USER_SAVE_URL = "users/save";
public static final String USER_EXISTS_URL = "users/";
public static final String BOOKS_ADD_URL = "books/save";
}
<file_sep>/ForkRead/src/com/forkread/model/ForkReadServerSearchResult.java
package com.forkread.model;
import com.bluelinelabs.logansquare.annotation.JsonField;
import com.bluelinelabs.logansquare.annotation.JsonObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by dipesh on 05/05/15.
*/
@JsonObject
public class ForkReadServerSearchResult {
@JsonField
public Books.Book book = new Books.Book();
public int mUsersCount;
@JsonField
public List<User> owners = new ArrayList<User>();
}
<file_sep>/ForkRead/src/com/forkread/ui/HomePageActivity.java
package com.forkread.ui;
import com.book.forkread.R;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class HomePageActivity extends AppCompatActivity {
protected int getActionBarSize() {
TypedValue typedValue = new TypedValue();
int[] textSizeAttr = new int[]{R.attr.actionBarSize};
int indexOfAttrTextSize = 0;
TypedArray a = obtainStyledAttributes(typedValue.data, textSizeAttr);
int actionBarSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
a.recycle();
return actionBarSize;
}
public void onBackPressed() {
super.onBackPressed();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_page);
Toolbar localToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(localToolbar);
}
public boolean onCreateOptionsMenu(Menu paramMenu) {
getMenuInflater().inflate(R.menu.main, paramMenu);
return true;
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem) {
if (paramMenuItem.getItemId() == R.id.home_page_add_book) {
startActivity(new Intent(this, AddBookActivity.class));
return true;
}
if (paramMenuItem.getItemId() == R.id.home_page_location) {
startActivity(new Intent(this, ChangeLocationActivity.class));
return true;
}
return super.onOptionsItemSelected(paramMenuItem);
}
protected void onSaveInstanceState(Bundle paramBundle) {
super.onSaveInstanceState(paramBundle);
}
}<file_sep>/ForkRead/src/com/forkread/ui/BookUsersActivity.java
package com.forkread.ui;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.book.forkread.R;
/**
* Created by dipesh on 07/06/15.
*/
public class BookUsersActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_users_owned);
ListView listView = (ListView) findViewById(R.id.users_list);
listView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
<file_sep>/ForkRead/src/com/forkread/ui/WhatsNewFragment.java
package com.forkread.ui;
import com.book.forkread.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WhatsNewFragment extends Fragment
{
private static final String ARG_POSITION = "ARG_POSITION";
private int[] mDrawableIds = { R.drawable.whats_new_image1, R.drawable.whats_new_image2,
R.drawable.whats_new_image3 };
private int mPosition;
private String[] mWhatsNewDescription = { "search books around you", "add books to your own list",
"lend books on your own terms" };
public static Fragment newInstance(int paramInt)
{
WhatsNewFragment localWhatsNewFragment = new WhatsNewFragment();
Bundle localBundle = new Bundle();
localBundle.putInt(ARG_POSITION, paramInt);
localWhatsNewFragment.setArguments(localBundle);
return localWhatsNewFragment;
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
Bundle localBundle = getArguments();
if (localBundle != null) this.mPosition = localBundle.getInt(ARG_POSITION);
}
public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
{
LinearLayout localLinearLayout = (LinearLayout) paramLayoutInflater.inflate(R.layout.whats_new_page,
paramViewGroup, false);
((TextView) localLinearLayout.findViewById(R.id.whatsnew_description))
.setText(this.mWhatsNewDescription[this.mPosition]);
((ImageView) localLinearLayout.findViewById(R.id.whatsnew_image))
.setImageResource(this.mDrawableIds[this.mPosition]);
return localLinearLayout;
}
}<file_sep>/ForkRead/src/com/forkread/utils/Constants.java
package com.forkread.utils;
public class Constants
{
public static final String BOOKS_API_AUTHORS = "authors";
public static final String BOOKS_API_IMAGE_CATEGORIES = "categories";
public static final String BOOKS_API_IMAGE_LINKS = "imageLinks";
public static final String BOOKS_API_ISBN_13_IDENTIFER = "identifier";
public static final String BOOKS_API_ISBN_TYPE = "type";
public static final String BOOKS_API_ISBN_TYPES = "industryIdentifiers";
public static final String BOOKS_API_PUBLISHER = "publisher";
public static final String BOOKS_API_PUBLISHER_DATE = "publishedDate";
public static final String BOOKS_API_RATING = "averageRating";
public static final String BOOKS_API_SCOPE = "oauth2:https://www.googleapis.com/auth/books https://www.googleapis.com/auth/userinfo.profile";
public static final String BOOKS_API_THUMBNAIL_SMALL = "smallThumbnail";
public static final String BOOKS_API_TITLE = "title";
public static final String BOOKS_API_VOLUME_INFO = "volumeInfo";
public static final String EMAIL_KEY = "email";
public static final String GENDER_KEY = "gender";
public static final String LOCATION = "currentLocation";
public static final String NAME_KEY = "given_name";
public static final String PHONE_NO = "contactNo";
public static final String SHARED_PREFERENCE_KEY = "FORK_READ_SHARED_PREFERENCE";
public static final String SHARED_PREFERENCE_CITY_KEY = "shared_preference_city_key";
public static final String SHARED_PREFERENCE_COUNTRY_KEY = "shared_preference_country_key";
public static final String USER_DETAILS_KEY = "USER_DETAILS_KEY";
public static final String ISBN_13 = "ISBN_13";
} | 72059ef2904784423ff4171a67aa298be71e6a9b | [
"Java",
"Gradle"
]
| 24 | Java | Fork-Read/AndroidApp | 48fc7e2d8c506f0834bf3ade5dd1a94ae4cc9f1b | e375e35f874c2a5cb9d1eb437ea9253e9a2e1d56 |
refs/heads/master | <file_sep>// CPP program to demonstrate multithreading
// using three different callables.
#include <iostream>
#include <thread>
#include <atomic>
#include <bits/stdc++.h>
#include <chrono>
using namespace std;
std::atomic<unsigned long long> total {0};
// sum function
void sum(long start, long end)
{
unsigned long long cnt = 0;
for (int i = start; i < end; i++) {
cnt+=i;
}
total+=cnt;
cout << "sum thread ends" << endl;
}
int main()
{
auto start = chrono::high_resolution_clock::now();
// unsync the I/O of C and C++.
ios_base::sync_with_stdio(false);
cout << "main thread starts" << endl;
thread th1(sum, 1,100000000);
thread th2(sum, 100000001,200000000);
thread th3(sum, 200000001,300000000);
thread th4(sum, 300000001,400000000);
thread th5(sum, 400000001,500000000);
thread th6(sum, 500000001,600000000);
thread th7(sum, 600000001,700000000);
thread th8(sum, 700000001,800000000);
thread th9(sum, 800000001,900000000);
thread th10(sum, 900000001,1000000000);
// Wait for the threads to finish
th1.join();
th2.join();
th3.join();
th4.join();
th5.join();
th6.join();
th7.join();
th8.join();
th9.join();
th10.join();
cout<< total <<endl;
cout << "main thread ends" << endl;
auto end = chrono::high_resolution_clock::now();
// Calculating total time taken by the program.
double time_taken =
chrono::duration_cast<chrono::nanoseconds>(end - start).count();
time_taken *= 1e-9;
cout << "Time taken by program is : " << fixed
<< time_taken << setprecision(9);
cout << " sec" << endl;
return 0;
}
<file_sep>#include <iostream>
#include <thread>
#include <atomic>
#include <bits/stdc++.h>
#include <chrono>
using namespace std;
// sum function
void sum(long start, long end)
{
unsigned long long cnt = 0;
for (int i = start; i < end; i++) {
cnt+=i;
}
cout<<cnt<<endl;
cout << "sum thread ends" << endl;
}
int main()
{
auto start = chrono::high_resolution_clock::now();
// unsync the I/O of C and C++.
ios_base::sync_with_stdio(false);
cout << "main thread starts" << endl;
thread th1(sum, 1,1000000000);
// Wait for thread t1 to finish
th1.join();
cout << "main thread ends" << endl;
auto end = chrono::high_resolution_clock::now();
// Calculating total time taken by the program.
double time_taken =
chrono::duration_cast<chrono::nanoseconds>(end - start).count();
time_taken *= 1e-9;
cout << "Time taken by program is : " << fixed
<< time_taken << setprecision(9);
cout << " sec" << endl;
return 0;
}
| a43c6843996aee6247a28dbfb7d6589b58f4c9f4 | [
"C++"
]
| 2 | C++ | loadbyte/multithreading-in-cpp-analysis | 6724f2e18e0bce155bdc42e22c417e137e3a2fdd | 8dfe43a2a650f5e6c31f856f5f5f09fd31335f9e |
refs/heads/master | <repo_name>joshjiejie/Collaborative-filtering<file_sep>/train.h
#include <omp.h>
#include "mpi.h"
#define TRAIN_FILE_NAME "train.txt"
#define TEST_FILE_NAME "test.txt"
#define U 116020
#define V 136737
#define Train_data_num 44302276
#define Test_data_num 1160200
#define H 32
#define alpha 0.0001
#define beta 0.02
#define thread_num 8
typedef struct{
unsigned int uid;
unsigned int vid;
unsigned short rate;
} data;
double cpu1, cpu2;
void train_scatter(data *Train_data, float * user_FV, float * item_FV, float * user_Update, float * item_Update, int sid){
float prediction;
float error;
int i,j, uid, vid;
if(sid==0){
#pragma omp parallel for default(shared) private(i, j, vid, uid, prediction, error) schedule(static)
for(i=0; i<Train_data_num/2; i++){
prediction = 0;
uid = Train_data[i].uid;
vid = Train_data[i].vid;
for(j=0; j<H; j++){
prediction+= user_FV[uid*H+j]*item_FV[vid*H+j];
}
error = Train_data[i].rate-prediction;
for(j=0; j<H; j++){
user_Update[uid*H+j] = 2*alpha*error*item_FV[vid*H+j]-beta*user_FV[uid*H+j];
item_Update[vid*H+j] = 2*alpha*error*user_FV[uid*H+j]-beta*item_FV[vid*H+j];
}
}
}
else {
#pragma omp parallel for default(shared) private(i, j, vid, uid, prediction, error) schedule(static)
for(i=Train_data_num/2; i<Train_data_num; i++){
prediction = 0;
uid = Train_data[i].uid;
vid = Train_data[i].vid;
for(j=0; j<H; j++){
prediction+= user_FV[uid*H+j]*item_FV[vid*H+j];
}
error = Train_data[i].rate-prediction;
for(j=0; j<H; j++){
user_Update[uid*H+j] = 2*alpha*error*item_FV[vid*H+j]-beta*user_FV[uid*H+j];
item_Update[vid*H+j] = 2*alpha*error*user_FV[uid*H+j]-beta*item_FV[vid*H+j];
}
}
}
//MPI_Barrier(MPI_COMM_WORLD);
}
void train_gather(float * user_FV, float * item_FV, float * user_Update, float * item_Update, int sid){
int i,j;
#pragma omp parallel for default(shared) private(i, j) schedule(static)
for(i=U/2*sid; i<U/2*(sid+1); i++){
for(j=0; j<H; j++){
user_FV[i*H+j] = user_FV[i*H+j] + user_Update[i*H+j];
user_Update[i*H+j] = 0;
}
}
#pragma omp parallel for default(shared) private(i, j) schedule(static)
for(i=0; i<V; i++){
for(j=0; j<H; j++){
item_FV[i*H+j] = item_FV[i*H+j] + item_Update[i*H+j];
item_Update[i*H+j] = 0;
}
}
}
float validate(data * Test_data, float * user_FV, float * item_FV, int sid){
float Overall_squar_error = 0;
float prediction;
int i,j;
if(sid==0){
#pragma omp parallel for default(shared) private(i, prediction) schedule(static) reduction(+:Overall_squar_error)
for(i=0; i<580100; i++){
prediction = 0;
for(j=0; j<H; j++){
prediction+= user_FV[Test_data[i].uid*H+j]*item_FV[Test_data[i].vid*H+j];
}
Overall_squar_error += (Test_data[i].rate-prediction)*(Test_data[i].rate-prediction);
}
}
if(sid==1){
#pragma omp parallel for default(shared) private(i, prediction) schedule(static) reduction(+:Overall_squar_error)
for(i=580101; i<Test_data_num; i++){
prediction = 0;
for(j=0; j<H; j++){
prediction+= user_FV[Test_data[i].uid*H+j]*item_FV[Test_data[i].vid*H+j];
}
Overall_squar_error += (Test_data[i].rate-prediction)*(Test_data[i].rate-prediction);
}
}
MPI_Allreduce(&Overall_squar_error, &Overall_squar_error, 1, MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
return Overall_squar_error/Test_data_num;
} <file_sep>/train.c
#include <assert.h>
#include <getopt.h>
#include <limits.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "train.h"
int main(int argc, char **argv) {
FILE *fp;
int i, j, k, n;
unsigned int u, v, r;
unsigned int u_max = 0;
unsigned int v_max = 0;
int iteration;
struct timespec start, stop;
double exe_time;
float MSE;
int sid;
MPI_Init(&argc,&argv); /* Initialize the MPI environment */
MPI_Status status;
MPI_Comm_rank(MPI_COMM_WORLD, &sid); /* My processor ID */
printf("My rank is %d\n", sid);
data *Train_data = (data*)malloc(sizeof(data)*Train_data_num);
data *Test_data = (data*)malloc(sizeof(data)*Test_data_num);
fp=fopen(TRAIN_FILE_NAME,"r");
for(i=0;i<Train_data_num;i++){
if(fscanf(fp,"%d %d %d\n",&u,&v,&r)!=EOF){
Train_data[i].uid=u;
Train_data[i].vid=v;
Train_data[i].rate=r;
if(u>u_max) u_max = u;
if(v>v_max) v_max = v;
}
}
fclose(fp);
fp=fopen(TEST_FILE_NAME,"r");
for(i=0;i<Test_data_num;i++){
if(fscanf(fp,"%d %d %d\n",&u,&v,&r)!=EOF){
Test_data[i].uid=u;
Test_data[i].vid=v;
Test_data[i].rate=r;
if(u>u_max) u_max = u;
if(v>v_max) v_max = v;
}
}
fclose(fp);
printf("u_max = %d, v_max =%d\n", u_max, v_max);
float *user_FV = (float *)malloc(sizeof(float)*U*H);
float *item_FV = (float *)malloc(sizeof(float)*V*H);
float *user_Update = (float *)malloc(sizeof(float)*U*H);
float *item_Update = (float *)malloc(sizeof(float)*V*H);
float *item_Update_recvbuf = (float *)malloc(sizeof(float)*V*H);
srand((unsigned int)time(NULL));
for(i=0; i<U*H; i++) user_FV[i] = (float) rand() / (RAND_MAX);
for(i=0; i<U*H; i++) user_Update[i] = 0;
for(i=0; i<V*H; i++) item_FV[i] = (float) rand() / (RAND_MAX);
for(i=0; i<V*H; i++) item_Update[i] = 0;
for(i=0; i<V*H; i++) item_Update_recvbuf[i] = 0;
omp_set_num_threads(thread_num);
MPI_Barrier(MPI_COMM_WORLD);
cpu1 = MPI_Wtime();
for(iteration =0; iteration<10; iteration++){
if(clock_gettime(CLOCK_REALTIME, &start) == -1) { perror("clock gettime");}
train_scatter(Train_data, user_FV, item_FV, user_Update, item_Update, sid);
//MPI_Allreduce((float*)item_Update, (float*)item_Update_recvbuf, H*V, MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD);
//train_gather(user_FV, item_FV, user_Update, item_Update_recvbuf, sid);
//MSE = validate(Test_data, user_FV, item_FV, sid);
if(clock_gettime(CLOCK_REALTIME, &stop) == -1) { perror("clock gettime");}
exe_time = (stop.tv_sec - start.tv_sec)+ (double)(stop.tv_nsec - start.tv_nsec)/1e9;
//if (sid == 0) printf("sid %d: Iter %d -> MSE = %.3f, exe time = %f\n", sid, iteration, MSE, exe_time);
if (sid == 0) printf("%.3f\n", MSE);
}
cpu2 = MPI_Wtime();
if (sid == 0) printf("Total time= %le\n",cpu2-cpu1);
//if(clock_gettime(CLOCK_REALTIME, &stop) == -1) { perror("clock gettime");}
//exe_time = (stop.tv_sec - start.tv_sec)+ (double)(stop.tv_nsec - start.tv_nsec)/1e9;
//printf("Execution time is %f sec per iteration, n=%d\n", exe_time/iteration, iteration);
////////free space////////
free(user_FV);
free(item_FV);
free(user_Update);
free(item_Update);
free(Train_data);
free(Test_data);
MPI_Finalize(); /* Clean up the MPI environment */
return 0;
}
| 15fe37780c1b9149c2272fbab844d113c8c442b2 | [
"C"
]
| 2 | C | joshjiejie/Collaborative-filtering | ef7d18f8a80d94247bc2da25e24fe3c6463d823b | 7ab964ef4cfe1f2dcf30d639d94fff9d54d87178 |
refs/heads/master | <file_sep>Vagrant::Config.run do |config|
config.vm.box = "precise32"
config.vm.box_url = "http://files.vagrantup.com/precise32.box"
config.vm.share_folder "source", "/macaroni", "../../../"
end
| 1213b685d1711c2bc59aee93b115a084767b7ebb | [
"Ruby"
]
| 1 | Ruby | bowlofstew/Macaroni | 0fb39c18f40ec514f69c6a33578ed87e2e6d8f73 | 75882c68c43fcd2680153f46c7825fbe858b81b1 |
refs/heads/master | <file_sep>//counter code
var button= document.getElementById("counter");
button.onclick= function(){
//make a request to the counter endpoint
//Capture the response and store
counter= counter+1;
var span = document.getElementById("count");
span.innerHTML=counter.toString();
};
| 78356b3226aca8d5441c066b94047c6e3552f8ea | [
"JavaScript"
]
| 1 | JavaScript | Kartm12/imad-app-v2 | c247351ed6900cd5e4af1846df26b4f8666741d2 | f9720f08d2008366cf16338efa7f7cc7f0a748b3 |
refs/heads/master | <file_sep>from math import inf, sqrt
from heapq import heappop, heappush
from turtledemo.chaos import line
from _ast import Str
import collections
def find_path(source_point,destination_point,mesh): #source_point is (x,y) pair, destination(x,y) pair , a data structure (fancy graph)
path = []
visited_nodes = []
#print (mesh)
for box in mesh['boxes']:
b = find_box(source_point, mesh)
if b != None :
visited_nodes.append(b)
b = find_box(destination_point, mesh)
if b != None:
visited_nodes.append(b)
path, visited_nodes = dijkstras_shortest_path(source_point, destination_point, mesh, navigation_edges, visited_nodes)
#print ("path: " + str(path))
#print(visited_nodes)
return (path , visited_nodes) # path is a list of points like ((x1,y1),(x2,y2)).
# visited nodes = a list of boxes explored by your algorithm identified by their bounds (x1,x2,y1,y2)
def find_box(point, mesh):
for box in mesh['boxes']:
if point[0] >= box[0] and point[0] <= box[1] \
and point[1] >= box[2] and point[1] <= box[3]:
return box
return None
def dijkstras_shortest_path(initial_position, destination, graph, adj, visited_nodes):
""" Searches for a minimal cost path through a graph using Dijkstra's algorithm.
Args:
initial_position: The initial cell from which the path extends.
destination: The end location for the path.
graph: A loaded level, containing walls, spaces, and waypoints.
adj: An adjacency function returning cells adjacent to a given cell as well as their respective edge costs.
Returns:
If a path exits, return a list containing all cells from initial_position to destination.
Otherwise, return None.
"""
initial_box = find_box(initial_position, graph)
destination_box = find_box(destination, graph)
distances = {initial_box: 0} # Table of distances to cells
previous_cell = {initial_box: None} # Back links from cells to predecessors
queue = [(0, initial_box)] # The heap/priority queue used
# Initial distance for starting position
distances[initial_position] = 0
while queue:
# Continue with next min unvisited node
current_distance, current_box = heappop(queue)
print (current_distance == distances[current_box])
#print ("cur_node: " +str(current_box))
# Early termination check: if the destination is found, return the path
if current_box == destination_box:
node = destination_box
path = []
prev_point = initial_position
while node is not None:
line_end = (0,0)
line_start = (0,0)
#print (str(initial_box) + " " + str(destination_box) + " " + str(previous_cell[node]))
if destination_box == initial_box:
#print("single box")
line_start = initial_position
line_end = destination
elif previous_cell[node] != None or previous_cell[node] == initial_box:
if node == destination_box:
#print("destination box")
line_start = destination
line_end = next_point(destination, node, previous_cell[node])
else:
#print("the rest")
line_start = prev_point
line_end = next_point(prev_point, node, previous_cell[node])
else:
#print("initial box")
line_start = prev_point
line_end = initial_position
visited_nodes.append(node)
path.append((line_start,line_end))
prev_point = line_end
node = previous_cell[node]
#print ("djtra: " + str(path))
#print("path: " + str(path))
return (path[::-1], visited_nodes)
# Calculate tentative distances to adjacent cells
for adjacent_node, edge_cost in adj(graph, current_box):
new_distance = current_distance + heuristic(destination_box, adjacent_node)
if adjacent_node not in distances or new_distance < distances[adjacent_node]:
# Assign new distance and update link to previous cell
distances[adjacent_node] = new_distance
previous_cell[adjacent_node] = current_box
heappush(queue, (new_distance, adjacent_node))
# Failed to find a path
print("Failed to find a path from", initial_position, "to", destination)
return None
def next_point(prev_point, current_box, destination_box):
#print("prev: " +str(prev_point))
#print("current_box: " + str(current_box))
#print("destination_box: " + str(destination_box))
border_p1 =(max(current_box[0], destination_box[0]), max(current_box[2],destination_box[2]))
border_p2 =(min(current_box[1], destination_box[1]), min(current_box[3], destination_box[3]))
point = (0,0)
#Vertical
if (border_p1[0] == border_p2[0]):
#py >= max(by1, by2)
if (prev_point[1] >= max(border_p1[1],border_p2[1])):
#p = bx1, max(by1,by2)
point = (border_p1[0], max(border_p1[1],border_p2[1]))
#py <= min(by1, by2)
elif (prev_point[1] <= min(border_p1[1],border_p2[1])):
#p = bx1, min(by1,by2)
point = (border_p1[0], min(border_p1[1],border_p2[1]))
else:
point = (border_p1[0], prev_point[1])
#Horizontal
else:
#px >= max(bx1, bx2)
if (prev_point[0] >= max(border_p1[0],border_p2[0])):
#p = max(bx1,bx2),
point = (max(border_p1[0],border_p2[0]), border_p1[1])
elif (prev_point[0] <= min(border_p1[0],border_p2[0])):
point = (min(border_p1[0],border_p2[0]), border_p1[1])
else:
point = (prev_point[0], border_p1[1])
#mid_point = ((border_p2[0] + border_p1[0])/2, (border_p2[1] + border_p1[1])/2)
#print ("midpoint: " + str(mid_point))
return point
def heuristic(goal_box, cur_box):
mid_point_goal = ((goal_box[0] + goal_box[1])/2, (goal_box[2] + goal_box[3])/2)
mid_point_cur = ((cur_box[0] + cur_box[1])/2, (cur_box[2] + cur_box[3])/2)
return sqrt(pow(mid_point_goal[0] - mid_point_cur[0], 2) + pow(mid_point_goal[1] - mid_point_cur[1],2))
#return abs(mid_point_goal[0]-mid_point_cur[0]) + abs(mid_point_goal[1]-mid_point_cur[1])
def navigation_edges(mesh, cell):
""" Provides a list of adjacent cells and their respective costs from the given cell.
Args:
level: A loaded level, containing walls, spaces, and waypoints.
cell: A target location.
Returns:
A list of tuples containing an adjacent cell's coordinates and the cost of the edge joining it and the
originating cell.
E.g. from (0,0):
[((0,1), 1),
((1,0), 1),
((1,1), 1.4142135623730951),
... ]
"""
#print ("n_e: " + str(level["adj"][cell]))
cells_and_costs = []
for box in mesh['adj'][cell]:
area = 1/(box[1] - box[0]) * (box[3] - box[2])
cells_and_costs.append((box, area))
return cells_and_costs
'''
boxes = level['boxes']
adj = level['adj']
adjacent_nodes = {}
for neighbors in adj[cell]:
next_cell = (x + delta_x, y + delta_y)
if next_cell != cell and next_cell in spaces:
distance = sqrt(delta_x ** 2 + delta_y ** 2)
adjacent_nodes[next_cell] = distance * (spaces[cell] + spaces[next_cell])/2
adjacent_nodes.it
return adjacent_nodes.items()'''
| c0ba5adcd7b1153711f8fcf928c64f62a5f18b2f | [
"Python"
]
| 1 | Python | joethered/cmps146p3 | 2f1de4312b0a5f930ffcee7de774eb1531a320b0 | 162d96e62e60e55ba10b49eaa48dc7514bcf9a64 |
refs/heads/main | <file_sep>#include<stdio.h>
void main();
{
printf("Hello World...!!!);
printf("\n this is the basic of c++ programm");
}
| 129952f4668e0299e23ec73f675ea2c26f36141b | [
"C"
]
| 1 | C | HyperAT/HELLO-WORLD | 32af0d4ac2ea1aa55bd281d219452d79496518af | 66f55c2b6304a1ba78660d591a43ead248ea6531 |
refs/heads/master | <repo_name>fangbo-yuan/pynesweeper<file_sep>/README.md
# pynesweeper
Slightly simplified version of minesweeper written in Python, where only one tile is shown at a time, and you enter the coordinates of tiles via your keyboard.
Setup:
After you clone this repo, run the following line in your terminal:
chmod +x pynesweeper.py
Then you can run the game by typing
./pynesweeper.py
<file_sep>/pynesweeper.py
#!/usr/bin/env python3
from random import randint, randrange
from copy import deepcopy
def make_board(width, height, num_mines):
""" Makes the board and the board the user sees. """
board = []
proxy_board = []
row = []
proxy_row = []
for i in range(height):
for j in range(width):
proxy_row.append('_')
proxy_board.append(proxy_row)
proxy_row = []
for i in range(height):
for j in range(width):
row.append('_')
board.append(row)
row = []
# popoulate the board with mines
for i in range(num_mines):
print('adsfa')
rand_1st = randrange(0, height)
rand_2nd = randrange(0, width)
# keep picking spaces to be mines if you repeated an index
while board[rand_1st][rand_2nd] != '_':
rand_1st = randrange(0, height)
rand_2nd = randrange(0, width)
board[rand_1st][rand_2nd] = '*'
""" Check the mines touching each of the 4 corner tiles. """
# upper left corner
if board[0][0] != '*':
mines = 0
if board[1][0] == '*':
mines += 1
if board[0][1] == '*':
mines += 1
if board[1][1] == '*':
mines += 1
board[0][0] = str(mines)
# lower left corner
if board[height-1][0] != '*':
mines = 0
if board[height-1][1] == '*':
mines += 1
if board[height-2][0] == '*':
mines += 1
if board[height-2][1] == '*':
mines += 1
board[height-1][0] = str(mines)
# upper right corner
if board[0][width-1] != '*':
mines = 0
if board[0][width-2] == '*':
mines += 1
if board[1][width-1] == '*':
mines += 1
if board[1][width-2] == '*':
mines += 1
board[0][width-1] = str(mines)
# lower right corner
if board[height-1][width-1] != '*':
mines = 0
if board[height-2][width-1] == '*':
mines += 1
if board[height-1][width-2] == '*':
mines += 1
if board[height-2][width-2] == '*':
mines += 1
board[height-1][width-1] = str(mines)
""" Check the number of mines touching the edges. """
# left edge
for i in range(1, height-1):
if board[i][0] != '*':
mines = 0
if board[i+1][0] == '*':
mines += 1
if board[i-1][0] == '*':
mines += 1
if board[i][1] == '*':
mines += 1
if board[i-1][1] == '*':
mines += 1
if board[i+1][1] == '*':
mines += 1
board[i][0] = str(mines)
# top edge
for j in range (1, width-1):
if board[0][j] != '*':
mines = 0
if board[0][j+1] == '*':
mines += 1
if board[0][j-1] == '*':
mines += 1
if board[1][j] == '*':
mines += 1
if board[1][j-1] == '*':
mines += 1
if board[1][j+1] == '*':
mines += 1
board[0][j] = str(mines)
# right edge
j = width - 1
for i in range(1, height-1):
if board[i][j] != '*':
mines = 0
if board[i][j-1] == '*':
mines += 1
if board[i-1][j] == '*':
mines += 1
if board[i+1][j] == '*':
mines += 1
if board[i-1][j-1] == '*':
mines += 1
if board[i+1][j-1] == '*':
mines += 1
board[i][j] = str(mines)
# bottom edge
i = height - 1
for j in range(1, width-1):
if board[i][j] != '*':
mines = 0
if board[i][j-1] == '*':
mines += 1
if board[i][j+1] == '*':
mines += 1
if board[i-1][j-1] == '*':
mines += 1
if board[i-1][j+1] == '*':
mines += 1
if board[i-1][j] == '*':
mines += 1
board[i][j] = str(mines)
""" Check the number of mines touching the middle tiles. """
for i in range (1, height-1):
for j in range(1, width-1):
if board[i][j] != '*':
mines = 0
if board[i-1][j] == '*':
mines += 1
if board[i][j-1] == '*':
mines += 1
if board[i][j+1] == '*':
mines += 1
if board[i+1][j] == '*':
mines += 1
if board[i-1][j-1] == '*':
mines += 1
if board[i-1][j+1] == '*':
mines += 1
if board[i+1][j-1] == '*':
mines += 1
if board[i+1][j+1] == '*':
mines += 1
board[i][j] = str(mines)
return board, proxy_board
def display_board(board):
counter = 0
for item in board:
for tile in item:
print(tile + '|', end = '')
counter += 1
print('')
print('Expand the screen if the tiles look weird.')
def show_rules():
print('You will be asked to choose the coordinate of the '
'tile you wish to uncover. First, choose how far '
'down, starting from 0 as the uppermost row. Then, '
'choose how far to the right, starting from 0 as the '
'leftmost column.')
def play_game(board, proxy_board, num_mines):
display_board(proxy_board)
tiles_swept = 0
answer = input('Would you like to read the rules? Enter y for yes. ')
if answer == 'y' or answer == 'Y':
show_rules()
while tiles_swept != len(board)*len(board[0]):
down = ''
right = ''
while not down.isdigit():
down = input('Choose the row of your tile: ')
while not right.isdigit():
right = input('Choose the column of your tile: ')
down = int(down)
right = int(right)
while down >= len(board[0]) or right >= len(board):
down = int(input('Out of bounds. Choose the row again: '))
right = int(input('Now choose the column again: '))
if board[down][right] == '*':
print('YOU LOSE!')
display_board(board)
return False
else:
proxy_board[down][right] = board[down][right]
display_board(proxy_board)
print('Congratulations! You found all the mines.')
return True
def main():
# Get the dimensions of the board
print('You can play on a board with the following dimensions.')
print('1: 10x10')
print('2: 25x25')
print('3: 50x50')
print('4: 100x100')
choice = input('Choose 1, ' + '2, ' + '3, ' + 'or 4: ')
while choice != '1' and choice != '2' and choice != '3' and choice != '4':
choice = input('Choose 1, ' + '2, ' + '3, ' + 'or 4: ')
if choice == '1':
height = 10
width = 10
elif choice == '2':
height = 25
width = 25
elif choice == '3':
height = 50
width = 50
elif choice == '4':
height = 100
width = 100
num_mines = ''
while not num_mines.isdigit() or int(num_mines) >= width * height:
num_mines = \
input('Choose the number of mines. It must be less than the number of tiles: ')
num_mines = int(num_mines)
if num_mines == 0:
print('You think I would let you play a game with zero mines?!! HAHAHA game over')
return
print('Generating game with', num_mines, 'mines.')
board, proxy_board = make_board(width, height, num_mines)
if not play_game(board, proxy_board, num_mines):
return
if __name__ == '__main__':
main()
| 11f8db45712e4e0b244e5e40adba1930c9455656 | [
"Markdown",
"Python"
]
| 2 | Markdown | fangbo-yuan/pynesweeper | afc92df8a8cb7009a490fa914cd5c3e57d43230b | 13acf799494b41d6e62a7786a0c4ae25cdb528d3 |
refs/heads/master | <file_sep>/*
********************************************************************************
** Intel Architecture Group
** Copyright (C) 2018-2019 Intel Corporation
********************************************************************************
**
** INTEL CONFIDENTIAL
** This file, software, or program is supplied under the terms of a
** license agreement and/or nondisclosure agreement with Intel Corporation
** and may not be copied or disclosed except in accordance with the
** terms of that agreement. This file, software, or program contains
** copyrighted material and/or trade secret information of Intel
** Corporation, and must be treated as such. Intel reserves all rights
** in this material, except as the license agreement or nondisclosure
** agreement specifically indicate.
**
** All rights reserved. No part of this program or publication
** may be reproduced, transmitted, transcribed, stored in a
** retrieval system, or translated into any language or computer
** language, in any form or by any means, electronic, mechanical,
** magnetic, optical, chemical, manual, or otherwise, without
** the prior written permission of Intel Corporation.
**
** Intel makes no warranty of any kind regarding this code. This code
** is provided on an "As Is" basis and Intel will not provide any support,
** assistance, installation, training or other services. Intel does not
** provide any updates, enhancements or extensions. Intel specifically
** disclaims any warranty of merchantability, noninfringement, fitness
** for any particular purpose, or any other warranty.
**
** Intel disclaims all liability, including liability for infringement
** of any proprietary rights, relating to use of the code. No license,
** express or implied, by estoppel or otherwise, to any intellectual
** property rights is granted herein.
**/
/********************************************************************************
**
** @file tdt_agent.h
**
** @brief Defines the C entry point for ThreatDetection Technology Library.
**
**
********************************************************************************
*/
#include <stddef.h>
#ifndef TDT_AGENT_H
#define TDT_AGENT_H
#if defined(_WIN32)
#ifdef DLL_EXPORTS
#define TDT_API_EXPORT __declspec( dllexport )
#else
#define TDT_API_EXPORT __declspec( dllimport )
#endif
#else
#define TDT_API_EXPORT
#endif
#define VALID_HANDLE(h) ((h) != ((void*)0))
#define INVALID_HANDLE(h) ((h) == ((void*)0))
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @brief Return codes from agent APIs.
*
*/
typedef enum tdt_return_code_
{
TDT_ERROR_SUCCESS,
TDT_ERROR_NULL_PARAM,
TDT_ERROR_INVALID_PARAM,
TDT_ERROR_OUT_OF_MEMORY,
TDT_ERROR_INTERNAL,
TDT_ERROR_INSUFFICIENT_BUFFER_SIZE,
TDT_ERROR_NOT_IMPLEMENTED,
TDT_ERROR_STARTUP_FAILURE,
TDT_ERROR_INVALID_CMD_LINE,
TDT_ERROR_INVALID_PLUGIN,
TDT_ERROR_INVALID_CONFIG,
TDT_ERROR_NO_EXECUTION,
TDT_ERROR_PIPELINE_ABORTED,
TDT_ERROR_SIGNVERIFY_FAILED
}tdt_return_code;
/**
* @brief Communication protocol formats supported by the library.
*
*/
typedef enum tdt_protocol_format_
{
TDT_PROTO_FORMAT_JSON,
TDT_PROTO_FORMAT_XML
}tdt_protocol_format;
/**
* @brief The tdt agent opaque class.
*
*/
typedef struct agentc *agent_handle;
/**
* @brief Constructor
*
* @param[in] proto_fmt Protocol format the user wishes to use.
*
* @return valid handle on success or NULL on failure.
*/
TDT_API_EXPORT const agent_handle construct_agent(const tdt_protocol_format proto_fmt);
typedef const agent_handle(*construct_agent_t)(const tdt_protocol_format proto_fmt);
/**
* @brief Destructor
*
* @param[in] hagent the agent handle returned by construct_agent.
*/
TDT_API_EXPORT const tdt_return_code destruct_agent(agent_handle hagent);
typedef const tdt_return_code(*destruct_agent_t)(agent_handle hagent);
/**
* @brief The notification callback signature.
*
* @param[in] context the context that was passed to set_notification_callback.
* @param[in] msg the notification message.
* @param[in] msg_len the length of msg in bytes.
*/
typedef void(*notification_t)(const long long context, const char* msg, const size_t msg_len);
/**
* @brief discover version, build and supported profiles.
*
* @param[in] hagent the agent handle returned by construct_agent.
* @param[out] capabilities on return from this API it will contain a null terminated JSON object
* containing version, build info, available profiles with properties.
* @code{.json} output: {"version": "1.2.1", "build":{"date":"Feb 18 2019", time: "23:59:01"},"profiles":
* [{"rfc_ml_sc":{"description":"side channel","state":"active"}},
* {"rfc_ml_cj":{"description":"crypto mining","state":"inactive"}}]}
* @endcode
* @param[in] caps_buffer_len size of the capabilities buffer in bytes including null terminator.
* @param[out] caps_len length in bytes of the capabilities including null terminator populated in the buffer
* if capabilities is NULL then caps_len if not NULL will contain the
* size of the buffer required to populate the capabilities including the null terminator.
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
TDT_API_EXPORT const tdt_return_code discover(agent_handle hagent, char* capabilities, const size_t caps_buffer_len, size_t* caps_len);
typedef const tdt_return_code(*discover_t)(agent_handle hagent, char* capabilities, size_t caps_buffer_len, size_t* caps_len);
/**
* @brief get current supported configurations for all profiles or a specific profile.
*
* @param[in] hagent the agent handle returned by construct_agent.
* @param[in] opt_profile_name optional name of the profile for which to get the configuration. can be NULL.
* @param[in] opt_profile_name_len length of opt_profile_name. ignored if opt_profile_name is NULL.
* @param[out] config on return will contain a JSON object describing current configurations for profile(s).
* @param[in] config_buffer_len the size of the config buffer in bytes.
* @param[out] config_len the length in bytes of configurations populated in config.
* @code{.json} input: opt_profile: "rfc_ml_cj"
* @endcode
* @code{.json} output: gconfig: {"rfc_ml_cj":{ "normalizer": {"model": {"t0_features_per_tid": true}}}}
* @endcode
* @code{.json} input: opt_profile: ""
* @endcode
* @code{.json} output: gconfig: {"profiles": ["rfc_ml_cj"], "configurations" : {"rfc_ml_cj":{ "normalizer": {"model": {"t0_features_per_tid": false}}}}}
* @endcode
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
TDT_API_EXPORT const tdt_return_code get_configuration(agent_handle hagent, const char* opt_profile_name, const size_t opt_profile_name_len, char* config, const size_t config_buffer_len, size_t* config_len);
typedef const tdt_return_code(*get_configuration_t)(agent_handle hagent, const char* opt_profile_name, const size_t opt_profile_name_len, char* config, const size_t config_buffer_len, size_t* config_len);
/**
* @brief set configurations for profiles or a specific profile that need to be started when start is called.
*
* @param[in] hagent the agent handle returned by construct_agent.
* @param[in] opt_profile_name optional name of the profile for which to set the configuration. can be NULL.
* @param[in] opt_profile_name_len length of opt_profile_name if opt_profile_name is not NULL.
* @param[in] opt_config a JSON object to modify current configuration for the profile.
* if NULL then opt_profile can't be NULL and current configuration will be applied for profile specified in opt_profile.
* @param[in] opt_config_buffer_len the size of the config buffer in bytes if opt_config is not NULL.
* @code{.json} input: opt_profile: ""
* @endcode
* @code{.json} input: sconfig: {"rfc_ml_cj":{ "normalizer": {"model": {"t0_features_per_tid": true}}}}
* @endcode
* @code{.json} input: opt_profile: "rfc_ml_cj"
* @endcode
* @code{.json} input: sconfig: {"profiles": ["rfc_ml_cj"], "configurations" : {"rfc_ml_cj":{ "normalizer": {"model": {"t0_features_per_tid": false}}}}}
* @endcode
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
TDT_API_EXPORT const tdt_return_code set_configuration(agent_handle hagent, const char* opt_profile_name, const size_t opt_profile_name_len, const char* opt_config, const size_t opt_config_buffer_len);
typedef const tdt_return_code(*set_configuration_t)(agent_handle hagent, const char* opt_profile_name, const size_t opt_profile_name_len, const char* opt_config, const size_t opt_config_buffer_len);
/**
* @brief Applies profiles set by set_configuration and starts detection process.
*
* @param[in] hagent the agent handle returned by construct_agent.
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
TDT_API_EXPORT const tdt_return_code start(agent_handle hagent);
typedef const tdt_return_code(*start_t)(agent_handle hagent);
/**
* @brief Stops current detection process for specified profile or all profiles.
*
* @param[in] hagent the agent handle returned by construct_agent.
* @param[in] opt_profile_name optional name of the profile to stop detection. can be NULL.
* @param[in] opt_profile_name_len length of opt_profile_name. ignored if opt_profile_name is NULL.
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
TDT_API_EXPORT const tdt_return_code stop(agent_handle hagent, const char *opt_profile_name, const size_t opt_profile_name_len);
typedef const tdt_return_code(*stop_t)(agent_handle hagent, const char *opt_profile_name, const size_t opt_profile_name_len);
/**
* @brief set callback for notifications.
*
* @param[in] hagent the agent handle returned by construct_agent.
* @param[in] callback to send notifications.
* @param[in] context to send with notifications.
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
TDT_API_EXPORT const tdt_return_code set_notification_callback(agent_handle hagent, const notification_t callback, const long long context);
typedef const tdt_return_code(*set_notification_callback_t)(agent_handle hagent, const notification_t callback, const long long context);
/**
* @brief get string describing an error code.
*
* @param[in] code error code returned by the APIs.
* @code{.c} output: "out of memory"
* @endcode
*
* @return a pointer to a null terminated string describing the error code.
* returns NULL for invalid error codes.
*/
TDT_API_EXPORT const char* get_error_string(const tdt_return_code code);
typedef const char* (*get_error_string_t)(const tdt_return_code code);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* TDT_AGENT_H */<file_sep>/*
********************************************************************************
** Intel Architecture Group
** Copyright (C) 2019 Intel Corporation
********************************************************************************
**
** INTEL CONFIDENTIAL
** This file, software, or program is supplied under the terms of a
** license agreement and/or nondisclosure agreement with Intel Corporation
** and may not be copied or disclosed except in accordance with the
** terms of that agreement. This file, software, or program contains
** copyrighted material and/or trade secret information of Intel
** Corporation, and must be treated as such. Intel reserves all rights
** in this material, except as the license agreement or nondisclosure
** agreement specifically indicate.
**
** All rights reserved. No part of this program or publication
** may be reproduced, transmitted, transcribed, stored in a
** retrieval system, or translated into any language or computer
** language, in any form or by any means, electronic, mechanical,
** magnetic, optical, chemical, manual, or otherwise, without
** the prior written permission of Intel Corporation.
**
** Intel makes no warranty of any kind regarding this code. This code
** is provided on an "As Is" basis and Intel will not provide any support,
** assistance, installation, training or other services. Intel does not
** provide any updates, enhancements or extensions. Intel specifically
** disclaims any warranty of merchantability, noninfringement, fitness
** for any particular purpose, or any other warranty.
**
** Intel disclaims all liability, including liability for infringement
** of any proprietary rights, relating to use of the code. No license,
** express or implied, by estoppel or otherwise, to any intellectual
** property rights is granted herein.
**/
/********************************************************************************
**
** @file tdt_json.go
**
** @brief JSON interface to read/write configuration, detection and errors.
**
**
********************************************************************************
*/
// Package tdt_lib provides Go interface to the native C++ Threat Detection
// Technology Library.
package tdt_lib
<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
* +build !tdt
*/
package main
import (
"encoding/json"
"intel/isecl/tdagent/constants"
"intel/isecl/tdservice/types"
"net/rpc"
"os"
"time"
)
func main() {
c, err := rpc.Dial("unix", constants.MockSockFile)
if err != nil {
panic(err)
}
var payload types.Report
payload.Detection.ProfileDescription = "simulated threat"
payload.Detection.PID = os.Getpid()
payload.Detection.TID = 0
payload.Detection.Timestamp = time.Now().Unix()
payloadStr, _ := json.Marshal(&payload)
var reply int
err = c.Call("Mock.MockNotify", string(payloadStr), &reply)
if err != nil {
panic(err)
}
}
<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package constants
const (
HomeDir = "/opt/tdagent/"
ConfigDir = "/etc/tdagent/"
DataDir = "/var/lib/tdagent/"
LogDir = "/var/log/tdagent/"
LogFile = "tdagent.log"
ConfigFile = "config.yml"
ServiceTLSCertFile = "tds.pem"
TLSCertFile = "cert.pem"
TLSKeyFile = "key.pem"
PIDFile = "tdagent.pid"
LibTDTFile = "/usr/lib64/libtdt.so"
LibTBBFile = "/usr/lib64/libtbb.so.2"
HostIDFile = "hostid"
DefaultTDTProfile = "telemetry_collect_tdtlib"
ServiceRemoveCmd = "systemctl disable tdagent"
)
// State represents whether or not a daemon is running or not
type State bool
const (
// Stopped is the default nil value, indicating not running
Stopped State = false
// Running means the daemon is active
Running State = true
)
<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package tasks
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"errors"
"flag"
"intel/isecl/lib/common/setup"
"io/ioutil"
"os"
)
type SigningKey struct {
Flags []string
SigningKeyFile string
}
func (sks SigningKey) Run(c setup.Context) error {
fs := flag.NewFlagSet("singing-key", flag.ContinueOnError)
force := fs.Bool("force", false, "force recreation")
err := fs.Parse(sks.Flags)
if err != nil {
return err
}
if *force || sks.Validate(c) != nil {
reader := rand.Reader
key, err := rsa.GenerateKey(reader, 4096)
if err != nil {
return err
}
// marshal to disk
encoded := x509.MarshalPKCS1PrivateKey(key)
err = ioutil.WriteFile(sks.SigningKeyFile, encoded, 0600)
if err != nil {
return err
}
}
return nil
}
func (sks SigningKey) Validate(c setup.Context) error {
_, err := os.Stat(sks.SigningKeyFile)
if os.IsNotExist(err) {
return errors.New("SigningKeyFile is not configured")
}
return nil
}
<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package config
import (
"errors"
"intel/isecl/tdagent/constants"
"os"
"path"
"sync"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)
// Configuration is the global configuration struct that is marshalled/unmarshaled to a persisted yaml file
type Configuration struct {
configFile string
TDTProfile string
Port int
TDS struct {
BaseURL string
Username string
Token string
}
Admin struct {
Username string
Password string
}
HostID string
LogLevel log.Level
InsecureSkipVerify bool
}
var mu sync.Mutex
var Global *Configuration
var ErrNoConfigFile = errors.New("no config file")
func (c *Configuration) Save() error {
if c.configFile == "" {
return ErrNoConfigFile
}
file, err := os.OpenFile(c.configFile, os.O_RDWR, 0)
if err != nil {
// we have an error
if os.IsNotExist(err) {
// error is that the config doesnt yet exist, create it
file, err = os.Create(c.configFile)
if err != nil {
return err
}
os.Chmod(c.configFile, 0664)
} else {
// someother I/O related error
return err
}
}
defer file.Close()
return yaml.NewEncoder(file).Encode(c)
}
func Load(path string) (*Configuration, error) {
var c Configuration
file, err := os.Open(path)
if err == nil {
defer file.Close()
yaml.NewDecoder(file).Decode(&c)
} else {
c.LogLevel = log.ErrorLevel
}
c.configFile = path
return &c, nil
}
func init() {
// load from config
g, err := Load(path.Join(constants.ConfigDir, constants.ConfigFile))
if err == nil {
Global = g
}
}
<file_sep>#!/bin/bash
# READ .env file
echo PWD IS $(pwd)
if [ -f ~/tdagent.env ]; then
echo Reading Installation options from `realpath ~/tdagent.env`
source ~/tdagent.env
elif [ -f ../tdagent.env ]; then
echo Reading Installation options from `realpath ../tdagent.env`
source ../tdagent.env
else
echo No .env file found
export TDA_NOSETUP
fi
# Export all known variables
export TDA_ADMIN_PASSWORD
export TDA_ADMIN_USERNAME
export TDA_PORT
export TDA_TLS_HOSTS
export TDS_SERVICE_BASEURL
export TDS_SERVICE_USERNAME
export TDS_SERVICE_PASSWORD
export TDT_PROFILE
if [[ $EUID -ne 0 ]]; then
echo "This installer must be run as root"
exit 1
fi
echo Setting up Threat Detection Agent Linux User...
id -u tda 2> /dev/null || useradd tda
echo Installing Threat Detection Agent...
COMPONENT_NAME=tdagent
PRODUCT_HOME=/opt/$COMPONENT_NAME
BIN_PATH=$PRODUCT_HOME/bin
LOG_PATH=/var/log/$COMPONENT_NAME
CONFIG_PATH=/etc/$COMPONENT_NAME
mkdir -p $BIN_PATH && chown tda:tda $BIN_PATH/
cp $COMPONENT_NAME $BIN_PATH && chown tda:tda $BIN_PATH/*
chmod 750 $BIN_PATH
ln -sfT $BIN_PATH/tdagent /usr/bin/$COMPONENT_NAME
# Create configuration directory in /etc
mkdir -p $CONFIG_PATH && chown tda:tda $CONFIG_PATH
chmod 700 $CONFIG_PATH
chmod g+s $CONFIG_PATH
# Create logging dir in /var/log
mkdir -p $LOG_PATH && chown tda:tda $LOG_PATH
chmod 661 $LOG_PATH
chmod g+s $LOG_PATH
# Install libs
mkdir -p /var/lib/tdagent
cp -f lib/* /var/lib/tdagent
chmod 755 /var/lib/tdagent/*
# symlink runtime libs
ln -sf /var/lib/tdagent/libtdt.so /usr/lib64/libtdt.so
ln -sf /var/lib/tdagent/libtbb.so.2 /usr/lib64/libtbb.so.2
# Install profiles
cp -f profiles/* /var/lib/tdagent
# Install systemd script
cp tdagent.service $PRODUCT_HOME && chown tda:tda $PRODUCT_HOME/tdagent.service && chown tda:tda $PRODUCT_HOME
# Enable systemd service
systemctl disable tdagent.service > /dev/null 2>&1
systemctl enable $PRODUCT_HOME/tdagent.service
systemctl daemon-reload
# check if TDA_NOSETUP is defined
if [[ -z $TDA_NOSETUP ]]; then
tdagent setup all
SETUPRESULT=$?
if [ ${SETUPRESULT} == 0 ]; then
echo Installation completed successfully!
systemctl start tdagent
else
echo Installation completed with errors
fi
else
echo flag TDA_NOSETUP is defined, skipping setup
echo Installation completed successfully!
fi
<file_sep>GITTAG := $(shell git describe --tags --abbrev=0 2> /dev/null)
GITCOMMIT := $(shell git describe --always)
GITCOMMITDATE := $(shell git log -1 --date=short --pretty=format:%cd)
VERSION := $(or ${GITTAG}, v0.0.0)
.PHONY: tdagent tdagent-sim installer installer-sim docker all test clean
tdagent:
env GOOS=linux LD_LIBRARY_PATH=lib go build -buildmode=pie -tags tdt -ldflags "-X intel/isecl/tdagent/version.Version=$(VERSION) -X intel/isecl/tdagent/version.GitHash=$(GITCOMMIT)" -o out/tdagent
test:
go test ./... -coverprofile cover.out
go tool cover -func cover.out
go tool cover -html=cover.out -o cover.html
installer: tdagent
mkdir -p out/installer
cp dist/linux/install.sh out/installer/install.sh && chmod +x out/installer/install.sh
cp dist/linux/tdagent.service out/installer/tdagent.service
cp out/tdagent out/installer/tdagent
mkdir -p ./out/installer/lib
cp ./lib/* ./out/installer/lib/
mkdir -p ./out/installer/profiles
cp ./profiles/* ./out/installer/profiles/
makeself --notemp out/installer out/tdagent-$(VERSION).bin "Threat Detection Agent $(VERSION)" ./install.sh
tdagent-sim:
env GOOS=linux go build -ldflags "-X intel/isecl/tdagent/version.Version=$(VERSION) -X intel/isecl/tdagent/version.GitHash=$(GITCOMMIT)" -o out/tdagent-sim
env GOOS=linux go build -o out/threat-sim cmd/sim/main.go
installer-sim: tdagent-sim
mkdir -p out/installer-sim
mkdir -p out/installer-sim/lib
mkdir -p out/installer-sim/profiles
cp dist/linux/install.sh out/installer-sim/install.sh && chmod +x out/installer-sim/install.sh
cp dist/linux/tdagent.service out/installer-sim/tdagent.service
echo "cp threat-sim /usr/bin/threat-sim" >> out/installer-sim/install.sh
cp out/tdagent-sim out/installer-sim/tdagent
cp out/threat-sim out/installer-sim/threat-sim
makeself out/installer-sim out/tdagent-sim-$(VERSION).bin "Threat Detection Agent Simulator $(VERSION)" ./install.sh
all: test installer installer-sim
clean:
rm -f cover.*
rm -f tdagent
rm -rf out/<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package main
import (
"fmt"
"intel/isecl/tdagent/constants"
"os"
"path"
)
func openLogFiles() *os.File {
logFilePath := path.Join(constants.LogDir, constants.LogFile)
logFile, _ := os.OpenFile(logFilePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0)
os.Chmod(logFilePath, 0664)
return logFile
}
func main() {
l := openLogFiles()
defer l.Close()
app := &App{LogWriter: l}
err := app.Run(os.Args)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package main
import (
"bytes"
"io/ioutil"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func createApp() *App {
configDir, _ := ioutil.TempDir("", "config")
return &App{
ConfigDir: configDir,
Interactive: false,
}
}
func teardownApp(a *App) {
os.Remove(a.ConfigDir)
}
func TestHelp(t *testing.T) {
app := createApp()
defer teardownApp(app)
var b bytes.Buffer
app.ConsoleWriter = &b
app.Run([]string{"tdagent", "help"})
}
func TestDaemon(t *testing.T) {
assert := assert.New(t)
app := createApp()
var b bytes.Buffer
app.ConsoleWriter = &b
defer teardownApp(app)
err := app.Run([]string{"tdagent", "setup", "tls"})
assert.Equal(nil, err)
go app.Run([]string{"tdagent", "run"})
time.Sleep(5 * time.Second)
assert.Contains(b.String(), "TDT Started")
}
<file_sep>/*
********************************************************************************
** Intel Architecture Group
** Copyright (C) 2018-2019 Intel Corporation
********************************************************************************
**
** INTEL CONFIDENTIAL
** This file, software, or program is supplied under the terms of a
** license agreement and/or nondisclosure agreement with Intel Corporation
** and may not be copied or disclosed except in accordance with the
** terms of that agreement. This file, software, or program contains
** copyrighted material and/or trade secret information of Intel
** Corporation, and must be treated as such. Intel reserves all rights
** in this material, except as the license agreement or nondisclosure
** agreement specifically indicate.
**
** All rights reserved. No part of this program or publication
** may be reproduced, transmitted, transcribed, stored in a
** retrieval system, or translated into any language or computer
** language, in any form or by any means, electronic, mechanical,
** magnetic, optical, chemical, manual, or otherwise, without
** the prior written permission of Intel Corporation.
**
** Intel makes no warranty of any kind regarding this code. This code
** is provided on an "As Is" basis and Intel will not provide any support,
** assistance, installation, training or other services. Intel does not
** provide any updates, enhancements or extensions. Intel specifically
** disclaims any warranty of merchantability, noninfringement, fitness
** for any particular purpose, or any other warranty.
**
** Intel disclaims all liability, including liability for infringement
** of any proprietary rights, relating to use of the code. No license,
** express or implied, by estoppel or otherwise, to any intellectual
** property rights is granted herein.
**/
/********************************************************************************
**
** @file tdt_agent.hpp
**
** @brief Defines the C++ entry point for ThreatDetection Technology Library.
**
**
********************************************************************************
*/
#ifndef TDT_AGENT_HPP
#define TDT_AGENT_HPP
#include <string>
#include <memory>
#include <functional>
#if defined(_WIN32)
#pragma warning(disable : 4251) // class needs to have a dll interface
#ifdef DLL_EXPORTS
#define TDT_API_EXPORT __declspec( dllexport )
#else
#define TDT_API_EXPORT __declspec( dllimport )
#endif
#else
#define TDT_API_EXPORT
#endif
namespace tdt_library
{
/**
* @brief The notification callback signature.
*
* @param[in] context the context that was passed to set_notification_callback.
* @param[in] msg the notification message.
*/
using notification_t = std::function<void(const long long context, const std::string& msg)>;
/**
* @brief Return codes from agent APIs.
*
*/
enum tdt_return_code : uint32_t
{
TDT_ERROR_SUCCESS,
TDT_ERROR_NULL_PARAM,
TDT_ERROR_INVALID_PARAM,
TDT_ERROR_OUT_OF_MEMORY,
TDT_ERROR_INTERNAL,
TDT_ERROR_INSUFFICIENT_BUFFER_SIZE,
TDT_ERROR_NOT_IMPLEMENTED,
TDT_ERROR_STARTUP_FAILURE,
TDT_ERROR_INVALID_CMD_LINE,
TDT_ERROR_INVALID_PLUGIN,
TDT_ERROR_INVALID_CONFIG,
TDT_ERROR_NO_EXECUTION,
TDT_ERROR_PIPELINE_RUNNING,
TDT_ERROR_PIPELINE_NOT_RUNNING,
TDT_ERROR_PIPELINE_ABORTED,
TDT_ERROR_SIGNVERIFY_FAILED,
TDT_ERROR_MAX
};
/**
* @brief Communication protocol formats supported by the library.
*
*/
enum tdt_protocol_format : uint32_t
{
TDT_PROTO_FORMAT_JSON,
TDT_PROTO_FORMAT_XML
};
//forward declaration
class tdt_agent_impl;
/**
* @brief The tdt agent class.
*
* The interface to configure various threat profiles and detect different threats.
*/
class TDT_API_EXPORT agent
{
public:
/**
* @brief Constructor.
*
*/
agent();
/**
* @brief Constructor.
*
* @param[in] proto_fmt Protocol format the user wishes to use. JSON is default if proto_fmt is not specified.
*/
agent(tdt_protocol_format proto_fmt);
/**
* @brief Destructor.
*/
~agent();
// No Copy constructor or copy assignment
agent(const agent& orig) = delete;
agent & operator=(agent&) = delete;
/**
* @brief discover version, build and supported profiles.
*
* @param[out] capabilities on return from this API it will contain a JSON object
* containing version, build, available profiles with properties.
* @code{.json} output: {"version": "1.2.1", "build":{"date":"Feb 18 2019", time: "23:59:01"},"profiles":
* [{"rfc_ml_sc":{"description":"side channel","state":"active"}},
* {"rfc_ml_cj":{"description":"crypto mining","state":"inactive"}}]}
* @endcode
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
const tdt_return_code discover(std::string& capabilities);
/**
* @brief get current supported configurations for all profiles or a specific profile.
*
* @param[in] opt_profile optional name of profile for which to get the configuration. this can be empty.
* @param[out] gconfig on return will contain a JSON object describing current configurations for profile(s).
* @code{.json} input: opt_profile: "rfc_ml_cj"
* @endcode
* @code{.json} output: gconfig: {"rfc_ml_cj":{ "normalizer": {"model": {"t0_features_per_tid": true}}}}
* @endcode
* @code{.json} input: opt_profile: ""
* @endcode
* @code{.json} output: gconfig: {"profiles": ["rfc_ml_cj"], "configurations" : {"rfc_ml_cj":{ "normalizer": {"model": {"t0_features_per_tid": false}}}}}
* @endcode
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
const tdt_return_code get_configuration(const std::string& opt_profile, std::string& gconfig);
/**
* @brief set configurations for profiles or a specific profile that need to be started when start is called.
*
* @param[in] opt_profile optional name of a specific profile for which to set the configuration.
* @param[in] sconfig a JSON object to modify current configuration for the profile.
* if empty then opt_profile can't be empty and current configuration will be applied for profile specified in opt_profile.
* @code{.json} input: opt_profile: ""
* @endcode
* @code{.json} input: sconfig: {"rfc_ml_cj":{ "normalizer": {"model": {"t0_features_per_tid": true}}}}
* @endcode
* @code{.json} input: opt_profile: "rfc_ml_cj"
* @endcode
* @code{.json} input: sconfig: {"profiles": ["rfc_ml_cj"], "configurations" : {"rfc_ml_cj":{ "normalizer": {"model": {"t0_features_per_tid": false}}}}}
* @endcode
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
const tdt_return_code set_configuration(const std::string& opt_profile, const std::string& sconfig);
/**
* @brief Applies profiles set by set_configuration and starts detection process.
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
const tdt_return_code start();
/**
* @brief Stops current detection process for specified profile or all profiles.
* @param[in] opt_profile optional name of profile for which to stop detections.
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
const tdt_return_code stop(const std::string& opt_profile);
/**
* @brief set callback for notifications.
*
* @param[in] callback to send notifications.
* @param[in] context to send with notifications.
*
* @return TDT_ERROR_SUCCESS on success or an error code.
*/
const tdt_return_code set_notification_callback(notification_t callback, const long long context);
/**
* @brief get string describing an error code.
*
* @param[in] code an error code.
* @code{.c} output: "out of memory"
* @endcode
*
* @return null terminated string describing the error code for valid error codes.
* returns nullptr for invalid error codes.
*
*/
static const char* get_error_string(const tdt_return_code code);
private:
std::unique_ptr<tdt_agent_impl> m_private;
};
}
#endif /* TDT_AGENT_HPP */<file_sep># Threat Detection Agent Low Level Documentation
## Acronyms
| | Description |
|-----|-----------------------------|
| TDT | Threat Detection Technology |
| TDA | Threat Detection Agent |
| TDS | Threat Detection Service |
| TDL | Threat Detection Library |
| TDD | Threat Detection Driver |
# Overview
The Threat Detection Agent is a daemon that will encapsulate the `Threat Detection Technology Library`, a C++ library, in a higher level microservice that will be written in go.
The `Threat Detection Agent` has three core functionalities:
1. Manage and collect reports from the underlying Threat Detection Technology stack (`Threat Detection Library`, `Threat Detection Driver`) in real time
2. Push Threat Detection Notification Reports to an external `Threat Detection Service`
3. Provide an API to let external services push Threat Detection Heuristics into the `TDL` for updated scanning definitions
# Threat Detection Library Interface
The Threat Detection Library interface is written in C++ (C version pending) , and is provided and maintained by PSD. It uses C++11 features, so a C++11 enabled compiler must be used.
```cpp
#ifndef TDT_AGENT_H
#define TDT_AGENT_H
#include <string>
#include <memory>
#include <functional>
#if defined(_WIN32)
#pragma warning(disable : 4251) // class needs to have a dll
interface
#ifdef DLL_EXPORTS
#else
#else #endif
#define TDT_API_EXPORT
#define TDT_API_EXPORT
__declspec( dllexport )
__declspec( dllimport )
#define TDT_API_EXPORT
#endif // WIN32
using notification_t = std::function<void(long long context, const std::
string& msg)>;
namespace tdt_library
{
enum tdt_return_code : uint32_t
{
TDT_ERROR_SUCCESS,
TDT_ERROR_INTERNAL,
TDT_ERROR_NOT_IMPLEMENTED,
TDT_ERROR_STARTUP_FAILURE,
TDT_ERROR_INVALID_CMD_LINE,
TDT_ERROR_INVALID_PLUGIN,
TDT_ERROR_INVALID_CONFIG,
TDT_ERROR_NO_EXECUTION,
TDT_ERROR_PIPELINE_ABORTED,
TDT_ERROR_SIGNVERIFY_FAILED
};
enum tdt_protocol_format : uint32_t
{
TDT_PROTO_FORMAT_JSON, // default
TDT_PROTO_FORMAT_XML
};
// Forward Declaration
class tdt_agent_impl;
class TDT_API_EXPORT agent
{
public:
agent();
agent(tdt_protocol_format proto_fmt);
~agent();
// No Copy constructor or copy assignment operator
agent(const agent& orig) = delete;
agent& operator=(agent&) = delete;
tdt_return_code discover(std::string& capabilities);
tdt_return_code get_configuration(const std::string& opt_profile,
std::string& gconfig);
tdt_return_code set_configuration(const std::string& opt_profile,
const std::string& sconfig);
tdt_return_code start();
tdt_return_code stop();
tdt_return_code set_notification_callback(notification_t
callback, long long context);
std::string get_error_string(tdt_return_code code);
private:
std::unique_ptr<tdt_agent_impl> m_pimpl;
};
}
#endif /* TDT_AGENT_H */
```
## Calling Threat Detection Library function from Go
C++ interoperability to other languages is generally not directly supported. For example, Java Native interface supports calling into C code, and Cgo as well only supports calling into C code. Thus, somewhere inbetween the Threat Detection Agent (written in Go) and the Threat Detection Library, must lie some C/C++ code that acts as a bridge between the two. The bridging code is compiled using a C++ compiler, but exports interface API's that are purely `C` using `extern "C" {}` blocks.
This bridging code could be written manually as such:
```cpp
typedef const char* malloc_string;
// Opaque type
typedef struct c_agent;
c_agent* c_agent_new() {
return reinterpret_cast<c_agent*>(new agent());
}
void c_agent_delete(c_agent* c) {
delete reinterpret_cast<agent*>(c);
}
tdt_return_code c_agent_discover(c_agent* c, malloc_string* out_cap) {
std::string cap;
auto a = reinterpret_cast<agent*>(c;
auto rc = a->discover(cap);
*out_cap = malloc(cap.size());
std::copy(cap.begin(), cap.end(), out_cap);
return rc;
}
...
```
Alternatively, bridging code can be auto generated by using [SWIG](http://www.swig.org).
# Threat Detection Agent Installation
The Threat Detection Agent has two modes of installation:
1. Bare Metal
2. Container
### Bare Metal Installation
The daemon will create and use the following files on the OS:
1. /var/run/tdagent/tdagent.run (PID file to track daemon)
2. /var/run/tdagent/tdagent.sock (RPC socket)
3. /etc/tdagent/tdagent.yaml (Configuration)
4. /etc/tdagent/tls-key.pem (TLS key)
5. /etc/tdagent/tls-cert.pem (TLS cert)
6. /etc/tdagent/signing-key.pem (Signing Key)
7. /etc/tdagent/signing-cert.pem (Signing Key Cert)
8. /usr/*/bin/tdagent (executable binary)
### Container Installation
It is possible to install the Threat Detection Agent and Threat Detection Libraries under a containerized environmennt assuming the following hold:
1. Container is ran in privileged mode
2. Host has TDT Kernel Drivers installed
## API Endpoints
API could be enabled via REST endpoints or GRPC.
Assuming REST:
### GET `/tda/discover`
Returns information about the availability and capability of Threat Detection Technology. This API is exposed so the `Threat Detection Service` can pull status information about the agent.
Example:
```json
{
"version": "1.2.1",
"build": "201910012012",
"os": "linux",
}
```
## Real Time Detection
Threat Detection Library posts threat notifications via callback, so Threat Detection Agent will only need to sit idly and wait for these callbacks to occur.
### Starting Real Time Detection
When Threat Detection Agent starts, the following library code will be called
C++:
```cpp
agent a();
std::string cap;
auto rc = a.discover(cap);
ASSERT_RC_OK(rc);
ASSERT_CAP_OK(cap);
rc = a.set_profile(DEFAULT_PROFILE); // profiles will not be configurable in phase 1.
ASSERT_RC_OK(rc);
auto handler = [/*captures*/](long long context, const std::string& msg) {
// ...
}
rc = a.set_notification_callback(handler, 0);
rc = a.start();
ASSERT_RC_OK(rc);
```
Using the C++ to Go bridge:
```go
agent := new(Agent)
capa, err := agent.Discover()
if err != nil {
panic()
}
ctx := interface{}
err = agent.SetProfile(DefaultProfile)
err = agent.SetNotificationCallback(func(ctx interface{}, msg string) {
/* handle */
}, ctx)
err = agent.Start()
```
### Stopping Real Time Detection
C++:
```cpp
a.stop()
```
Go:
```go
agent.Stop()
```
## Handling and Publishing Threat Notifications
Threat notifications happen in real time, and thus notifications should be pushed from the `Threat Detection Agent` directly to the `Threat Detection Service`
C++:
```cpp
auto handler = [/*captures*/](long long context, const std::string& msg) {
// pseudocode
auto signedmsg = prepareSignMessage(msg)
auto req = NewHTTPRequest(POST, "https://apigateway.service/tds/report", signedmsg);
req.SetAuthorization("username", "<PASSWORD>")
req.Do();
}
rc = a.set_notification_callback(handler, 0);
```
**TODO: Handle duplicates, time series analysis: TDA or TDS?**
Go:
```go
err = agent.SetNotificationCallback(
func(ctx interface{}, msg string) {
signed := prepareSignMessage(msg)
req := http.NewRequest(http.Post, "https://apigateway.service/tds/report", signed)
req.SetBasicAuth("username", "<PASSWORD>")
client := &http.Client{}
client.Do(req)
}, ctx)
```
Edge cases to consider:
If TDS is down, need to defer posting of the report at a later time when TDS comes back up. This could be an arbitrary unit of time later, and should be persisted even on TDA shutdown.
## Deferred Report Posting
In the event where a report fails to post to TDS, it can be deferred for a later point in time by storing the report payload into `/var/lib/tdagent/pending/<timestamp>.json`
Periodically, `TDA` will continuously attempt to submit all pending reports in this directory in a goroutine, deleting them as they are successfully submitted.
# Connection to Threat Detection Service
The following Configuration Variables must be set in order to connect to the Threat Detection Service
1. BaseURL
2. Username
3. Password
4. TLS Configuration
## Registering with a Threat Detection Service
Before the Threat Detection Agent can push reports to the Threat Detection Service, it must first register itself with the TDS. During setup of the TDA, a post request to the TDS will be executed as such:
`POST https://api.gateway/tds/hosts Content-Type: application/json {}`
In Phase 1, authentication will be done with HTTP Basic (Username + Password), and the contents of the request body will be the JSON output of the `discover` function.
```json
{
"version": "1.2.1",
"build": "201910012012",
"profiles": [
{
"rfc_ml_sc": "side channel"
},
{
"rfc_ml_cj": "crypto mining"
}
]
}
```
## TLS Configuration
By default, `TDA` will use the system's cert pool for trusting the `TDS` TLS certificate. If a certificate is to be manually added to the trust pool, place the respective certificate file in `/etc/tdagent/certs/<hostname.pem>
For example, if the `TDS` server is at https://tds.internal.intel.com, place its pem cert in /etc/tdagent/certs/tds.internal.intel.com.pem
`TDA` will then use both the systems cert pool as well as any certificates found in this directory for TLS validation. Ensure any missing intermediates are concatenated with the supplied .pem.
# Command Line Operations
## Setup
```console
> tdagent setup
Available setup tasks:
- server
- tls
- signingkey
- register
```
### Setup - HTTP Server
```console
> tdagent setup server --port=8443]]
```
### Setup - TLS
```consolefd
> tdagent setup tls [--force] [--hosts=intel.com,10.1.168.2]
```
Creates a Self Signed TLS Keypair in /etc/tdagent/ for quality of life. It is expected that consumers of this product will provide their own key and certificate in /etc/threat-detection before or after running setup, to make `TDA` use those instead.
`--force` overwrites any existing files, and will always generate a self signed pair.
Environment variables `TDA_TLS_HOSTS` can be used instead of command line flags
### Setup - Signing Key
```console
> tdagent setup signingkey [--force]
```
Creates a Self Signed Signing Key in /etc/tdagent/ for quality of life. This key is used for signing threat reports. It is expected that consumers of this product will provide their own key and certificate in /etc/threat-detection before or after running setup, to make `TDA` use those instead.
### Setup - Register
```console
> tdagent setup register --tds-url=https://api.gateway/tds/ --tds-user=admin --tds-pass=<PASSWORD>
```
Sets up the connection to the `TDS`, as well as registers this `TDA` with the `TDS` by making a `POST` request to `/tds/hosts`, sending it's host information as well as `TDT capabilities` from `agent::discover()`
The setup task can alternatively read variables from the environment, such as:
```console
export TDS_SERVICE_BASEURL=https://api.gateway/tds/
export TDS_SERVICE_USERNAME=admin
export TDS_SERVICE_PASSWORD=<PASSWORD>
```
Running `tdagent setup all` will run all setup tasks in order, picking arguments from environment variables, then command line.
## Start/Stop
```console
> tdagent start
Threat Detection Agent started
> tdagent stop
Threat Detection Agent stopped
```
## Uninstall
```console
> tdagent uninstall
Threat Detection Agent uninstalled
```
# Container Operations
Stubbed out until phase 2
<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package tasks
import (
"crypto/tls"
"crypto/x509"
"errors"
"flag"
"fmt"
"intel/isecl/lib/common/setup"
"intel/isecl/tdagent/config"
"intel/isecl/tdagent/version"
"intel/isecl/tdservice/client"
"intel/isecl/tdservice/types"
"io"
"net/http"
"net/url"
"strings"
)
type Register struct {
Flags []string
Config *config.Configuration
RootCAs *x509.CertPool
ConsoleWriter io.Writer
}
var ErrInvalidBaseURL = errors.New("Invalid base url")
var ErrInvalidWebProtocol = errors.New("Unsupported protocol")
var ErrInvalidPath = errors.New("Invalid path")
var ErrQueryAttached = errors.New("No query please")
func (r Register) Run(c setup.Context) (err error) {
if r.Validate(c) != nil {
// register to TDS
defaultBaseURL, _ := c.GetenvString("TDS_SERVICE_BASEURL", "Threat Detection Service base URL")
defaultUser, _ := c.GetenvString("TDS_SERVICE_USERNAME", "Threat Detection Service username")
defaultPass, _ := c.GetenvSecret("TDS_SERVICE_PASSWORD", "<PASSWORD>")
fs := flag.NewFlagSet("register", flag.ContinueOnError)
fs.StringVar(&r.Config.TDS.BaseURL, "tds-url", defaultBaseURL, "Threat Detection Service base URL")
Username := fs.String("tds-user", defaultUser, "Threat Detection Service username")
Password := fs.String("tds-pass", <PASSWORD>, "<PASSWORD>")
fs.Parse(r.Flags)
// validate tds base URL
if err = validateURL(r.Config.TDS.BaseURL); err != nil {
return err
}
tds := client.Client{BaseURL: r.Config.TDS.BaseURL, Username: *Username, Password: *<PASSWORD>}
tds.HTTPClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true, // Disable this next build
RootCAs: r.RootCAs,
},
},
}
hostname, err := outboundHost()
if err != nil {
return err
}
info := types.HostInfo{
Hostname: hostname,
OS: "linux",
Version: version.Version,
Build: version.GitHash,
}
host, err := tds.AddHost(info)
if err != nil {
return err
}
// created host, store the id
r.Config.HostID = host.Host.ID
r.Config.TDS.Username = host.User
r.Config.TDS.Token = host.Token
return r.Config.Save()
} else {
fmt.Fprintln(r.ConsoleWriter, "Threat Detection Agent is already registered")
}
return
}
func (r Register) Validate(c setup.Context) (err error) {
// check if hostid is already set
if r.Config.HostID == "" {
return errors.New("agent not registered")
}
// hostid is set, check if it exists against the service
tds := client.Client{BaseURL: r.Config.TDS.BaseURL, Username: r.Config.TDS.Username, Password: r.Config.TDS.Token,}
tds.HTTPClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true, // Disable this next build
RootCAs: r.RootCAs,
},
},
}
_, err = tds.GetHost(r.Config.HostID)
if err != nil && strings.Contains(err.Error(), "HTTP Code: 404") {
// host does not exist, we have been unregistered
return errors.New("agent's registration status is stale")
}
// TDS didn't give a 404, so we can't make any reasonable assumption about the registration status
return
}
func validateURL(test_url string) error {
url_obj, err := url.Parse(test_url)
if err == nil {
if url_obj.Scheme != "http" && url_obj.Scheme != "https" {
return ErrInvalidWebProtocol
}
if url_obj.Path != "/tds/" {
return ErrInvalidPath
}
if url_obj.RawQuery != "" || url_obj.Fragment != "" {
return ErrQueryAttached
}
} else {
return ErrInvalidBaseURL
}
return nil
}
<file_sep>module intel/isecl/tdagent
require (
github.com/gorilla/handlers v1.4.0
github.com/gorilla/mux v1.7.0
github.com/sirupsen/logrus v1.3.0
github.com/stretchr/testify v1.3.0
gopkg.in/yaml.v2 v2.2.2
intel/isecl/lib/common v1.0.0-Beta
intel/isecl/tdservice v1.0.0-Beta
)
replace intel/isecl/tdservice => github.com/intel-secl/tdservice v1.0.0-Beta
//replace intel/isecl/tdservice => ../tdservice
replace intel/isecl/lib/common => github.com/intel-secl/common v1.0.0-Beta
<file_sep># Threat Detection Agent
`Threat Detection Agent` is a daemon that encapsulates the `Threat Detection Technology Library`, a C++ library that utilizes pre-trained heuristic models to detect potential side channel attacks.
## Key features
- Incorporates `Threat Detection Technology Library`
- Configures the library
- Detects potential side channel attacks with pre-trained heuristic models
- Generates threat reports that will be posted to `Threat Detection Service`
*Note: The heuristic models for detecting side channel attacks need to be obtained seperately. Please review the product guide for instructions on how to obtain these.*
## System Requirements
- RHEL 7.5/7.6
- Epel 7 Repo
- Proxy settings if applicable
## Software requirements
- git
- makeself
- GCC 7.x or newer
- On RHEL distributions, you will need devtoolset-7 that requires subscription manager
- Go 11.4 or newer
- Intel Threat Detection library
- CMake 3.11.2 or newer
- boost Library 1.68 or newer (https://www.boost.org/)
- Intel Thread Building Blocks (TBB: https://software.intel.com/en-us/intel-tbb)
# Step By Step Build Instructions
## Install required shell commands
### Http proxy and Tools
Please make sure that you have the right `http proxy` settings if you are behind a proxy
```shell
export HTTP_PROXY=http://<proxy>:<port>
export HTTPS_PROXY=https://<proxy>:<port>
```
Install required tools
```shell
sudo yum install -y git wget makeself
```
### Install `GCC 7.x` or newer
The current repos including repos with a subscription manager does not have rpm packages to install the required version of `GCC`. We shall rely on `devtoolset-7` to install the required version of `GCC`.
*Note : installing `devtoolset-7` requires access to the subscription manager. Please contact your system administrator to configure your build server with access to the subscription manager*
1. On RHEL, enable RHSCL repository for system
```shell
sudo yum-config-manager --enable rhel-server-rhscl-7-rpms
```
2. Install the devtoolset-7
```shell
sudo yum install devtoolset-7
```
*Note: Install ‘yum install -y yum-utils’ if yum-config-manager command is not available*
### Install `cmake 3.11.2` or newer
`cmake` versions available in `RHEL` repos is not compatible with building the `Threat Detection Libraries`. You will therefore need to install a version of `cmake` that is available directly at https://cmake.org. Future version of RHEL or updated repositories may contain `cmake` version that are compatible. But currently, the following is what has been verified to work.
```shell
sudo yum remove cmake
wget https://github.com/Kitware/CMake/releases/download/v3.14.0/cmake-3.14.0-Linux-x86_64.sh
chmod +x cmake-3.14.0-Linux-x86_64.sh
sudo ./cmake-3.14.0-Linux-x86_64.sh --skip-license --include-subdir --prefix=/usr/local
export PATH=$PATH:/usr/local/cmake-3.14.0-Linux-x86_64/bin
```
### Install `go 1.11.4` or newer
The `Threat Detection Agent` requires Go version 11.4 that has support for `go modules`. The build was validated with version 11.4 version of `go`. It is recommended that you use a newer version of `go` - but please keep in mind that the product has been validated with 1.11.4 and newer versions of `go` may introduce compatibility issues. You can use the following to install `go`.
```shell
wget https://dl.google.com/go/go1.11.4.linux-amd64.tar.gz
tar -xzf go1.11.4.linux-amd64.tar.gz
sudo mv go /usr/local
export GOROOT=/usr/local/go
export PATH=$GOPATH/bin:$GOROOT/bin:$PATH
```
## Build `Threat Detection Library`
Threat detection library info can be found here: [lib-tdt README](https://github.com/intel-secl/lib-tdt/blob/master/README.MD)
The threat detection library depends on following. All the depencies are automatically downloaded and built as part of the Threat detection library build.
- Boost 1.68 or up (https://www.boost.org/)
- Intel Thread Building Blocks (TBB: https://software.intel.com/en-us/intel-tbb)
The following are the steps to download and build the threat detection library.
- Git clone the threat detection library
- Run scripts to build the threat detection library
- Copy needed library binaries and profiles into source folder for TD Agent
```shell
git clone https://github.com/intel-secl/lib-tdt.git
cd lib-tdt
./compile.sh
cd ..
```
## Build `Threat Detection Agent`
- Git clone the threat detection agent
- Copy the necessary library files from the threat detection library repository to TD Agent repository lib and profiles folder
- Copy any additional acquired or developed heuristic library files to TD Agent repository lib and profiles folder
- Run scripts to build the threat detection agent
```shell
git clone https://github.com/intel-secl/tdagent.git
mkdir tdagent/lib tdagent/profiles
cp lib-tdt/release_package/*.so* tdagent/lib/
cp lib-tdt/release_package/*.profile tdagent/profiles/
# copy additional heuristics at this time
cd tdagent
make installer
```
# Third Party Dependencies
## Threat Detection Agent
| Name | Repo URL | Minimum Version Required |
| ------- | --------------------------- | :----------------------: |
| logrus | github.com/sirupsen/logrus | v1.3.0 |
| testify | github.com/stretchr/testify | v1.3.0 |
| yaml.v2 | gopkg.in/yaml.v2 | v2.2.2 |
*Note: All dependencies are listed in go.mod*
# Links
- https://01.org/intel-secl/tdt
- boost Library: https://www.boost.org/
- Intel Thread Building Blocks: https://software.intel.com/en-us/intel-tbb
<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
* +build !tdt
*/
package constants
const MockSockFile = "/tmp/mock.sock"
<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package tasks
import (
"errors"
"flag"
"fmt"
"intel/isecl/lib/common/setup"
"intel/isecl/tdagent/config"
"intel/isecl/tdagent/constants"
"io"
)
type TdtProfile struct {
Flags []string
Config *config.Configuration
ConsoleWriter io.Writer
}
var ErrEmptyTDTProfile = errors.New("TDT Profile cannot be empty")
func (r TdtProfile) Run(c setup.Context) (err error) {
EnvTDTProfile, _ := c.GetenvString("TDT_PROFILE", "Threat Detection Technology Profile")
if EnvTDTProfile == "" {
EnvTDTProfile = constants.DefaultTDTProfile
}
fs := flag.NewFlagSet("tdtprofile", flag.ContinueOnError)
TDTProfile := fs.String("profile", EnvTDTProfile, "Threat Detection Technology Profile")
fs.Parse(r.Flags)
r.Config.TDTProfile = *TDTProfile
fmt.Fprintln(r.ConsoleWriter, r.Config.TDTProfile+" will be used as TDT profile")
return r.Config.Save()
}
func (r TdtProfile) Validate(c setup.Context) error {
return nil
}
<file_sep>// +build tdt
/*
********************************************************************************
** Intel Architecture Group
** Copyright (C) 2018-2019 Intel Corporation
********************************************************************************
**
** INTEL CONFIDENTIAL
** This file, software, or program is supplied under the terms of a
** license agreement and/or nondisclosure agreement with Intel Corporation
** and may not be copied or disclosed except in accordance with the
** terms of that agreement. This file, software, or program contains
** copyrighted material and/or trade secret information of Intel
** Corporation, and must be treated as such. Intel reserves all rights
** in this material, except as the license agreement or nondisclosure
** agreement specifically indicate.
**
** All rights reserved. No part of this program or publication
** may be reproduced, transmitted, transcribed, stored in a
** retrieval system, or translated into any language or computer
** language, in any form or by any means, electronic, mechanical,
** magnetic, optical, chemical, manual, or otherwise, without
** the prior written permission of Intel Corporation.
**
** Intel makes no warranty of any kind regarding this code. This code
** is provided on an "As Is" basis and Intel will not provide any support,
** assistance, installation, training or other services. Intel does not
** provide any updates, enhancements or extensions. Intel specifically
** disclaims any warranty of merchantability, noninfringement, fitness
** for any particular purpose, or any other warranty.
**
** Intel disclaims all liability, including liability for infringement
** of any proprietary rights, relating to use of the code. No license,
** express or implied, by estoppel or otherwise, to any intellectual
** property rights is granted herein.
**/
/********************************************************************************
**
** @file tdt_agent.go
**
** @brief GO interface for Threat Detection Technology Library.
**
**
********************************************************************************
*/
// Package tdt_lib provides Go interface to the native C++ Threat Detection
// Technology Library.
package tdt_lib
/*
// // preanble for cgo. see https://golang.org/cmd/cgo/
#cgo CFLAGS: -std=c99 -I../include -I./
#cgo LDFLAGS: -L../lib -Wl,-rpath-link,$ORIGIN -ltdt
#include <stdlib.h>
#include "tdt_agent.h"
tdt_return_code SetNotificationCallback(agent_handle hagent, const long long context);
*/
import "C"
import "unsafe"
import "fmt"
import "sync"
// The return codes from the TDT Library APIs.
type tdt_return_code int
const (
TDT_ERROR_SUCCESS tdt_return_code = iota
TDT_ERROR_NULL_PARAM
TDT_ERROR_INVALID_PARAM
TDT_ERROR_OUT_OF_MEMORY
TDT_ERROR_INTERNAL
TDT_ERROR_INSUFFICIENT_BUFFER_SIZE
TDT_ERROR_NOT_IMPLEMENTED
TDT_ERROR_STARTUP_FAILURE
TDT_ERROR_INVALID_CMD_LINE
TDT_ERROR_INVALID_PLUGIN
TDT_ERROR_INVALID_CONFIG
TDT_ERROR_NO_EXECUTION
TDT_ERROR_PIPELINE_ABORTED
TDT_ERROR_SIGNVERIFY_FAILED
)
// The protocol format to use when using the TDT Library APIs.
type tdt_protocol_format int
const (
TDT_PROTO_FORMAT_JSON tdt_protocol_format = iota
TDT_PROTO_FORMAT_XML
)
// An internal structure to store a TDT agent instance.
type tdt_agent struct {
h C.agent_handle
f func(uint64, string)
c uint64
}
// To make concurrency safe
var callbackMutex sync.Mutex
// Map to associate agent instance with context
var callbackFuncs = make(map[uint64]*tdt_agent)
// Factory method to get an instance of TDT agent.
func GetTDTAgentInstance() *tdt_agent {
agent := &tdt_agent{h: nil}
return agent
}
// Constructs and initializes an instance of TDT agent to use the
// specified protocol format (e.g. JSON) for communication.
// Returns nil on success or any encountered error.
func (agent *tdt_agent) Construct(proto_fmt tdt_protocol_format) error {
if agent.h == nil {
agent_h := C.construct_agent(C.tdt_protocol_format(proto_fmt))
if agent_h != nil {
agent.h = agent_h
return nil
}
return fmt.Errorf("out of memory")
}
return fmt.Errorf("invalid handle")
}
// Destructs an instance of TDT agent.
// Returns nil on success or any encountered error.
func (agent *tdt_agent) Destruct() error {
if agent.h != nil {
C.destruct_agent(agent.h)
agent.h = nil
return nil
}
return fmt.Errorf("invalid handle")
}
// Starts the threat detection for all currently configured threat profiles.
// Returns TDT_ERROR_SUCCESS or an error code.
func (agent *tdt_agent) Start() tdt_return_code {
if agent.h != nil {
return tdt_return_code(C.start(agent.h))
}
return TDT_ERROR_NULL_PARAM
}
// Stops threat detection for all currently configured profiles or a specified profile.
// If opt_profile is empty then stops detection for all profiles.
// Returns TDT_ERROR_SUCCESS or an error code.
func (agent *tdt_agent) Stop(opt_profile string) tdt_return_code {
if agent.h != nil {
var opt_ps *C.char
var opt_ps_len C.size_t
if opt_profile != "" {
opt_ps = C.CString(opt_profile)
opt_ps_len = (C.size_t)(len(opt_profile))
}
return tdt_return_code(C.stop(agent.h, opt_ps, opt_ps_len))
}
return TDT_ERROR_NULL_PARAM
}
// Discovers capabilities and threat profiles currently supported.
// On success it returns the capabilities and profiles in the protocol format
// specified during construction of the TDT agent instance and
// TDT_ERROR_SUCCESS. On failure it returns an empty string with an error code.
func (agent *tdt_agent) Discover() (string, tdt_return_code) {
ret_code := TDT_ERROR_NULL_PARAM
if agent.h != nil {
var caps_len C.size_t
ret_code = tdt_return_code(C.discover(agent.h, nil, 0, &caps_len))
if ret_code == TDT_ERROR_INSUFFICIENT_BUFFER_SIZE {
buffer := C.malloc(C.size_t(caps_len)) // guarantees never to return nil
ret_code = tdt_return_code(C.discover(agent.h, (*C.char)(buffer), caps_len, nil))
gs := C.GoString((*C.char)(buffer))
C.free(unsafe.Pointer(buffer))
return gs, ret_code
}
}
return "", ret_code
}
// Gets configuration for optional threat profile or for all currently supported threat profiles.
// On success it returns the configuration(s) in the protocol format
// specified during construction of the TDT agent instance and
// TDT_ERROR_SUCCESS. On failure it returns an empty string with an error code.
func (agent *tdt_agent) GetConfiguration(opt_profile string) (string, tdt_return_code) {
gs := ""
ret_code := TDT_ERROR_NULL_PARAM
if agent.h != nil {
var caps_len C.size_t
var opt_ps *C.char
var opt_ps_len C.size_t
if opt_profile != "" {
opt_ps = C.CString(opt_profile)
opt_ps_len = (C.size_t)(len(opt_profile))
}
ret_code = tdt_return_code(C.get_configuration(agent.h, opt_ps, opt_ps_len, nil, 0, &caps_len))
if ret_code == TDT_ERROR_INSUFFICIENT_BUFFER_SIZE {
buffer := C.malloc(C.size_t(caps_len)) // guarantees never to return nil
ret_code = tdt_return_code(C.get_configuration(agent.h, opt_ps, opt_ps_len, (*C.char)(buffer), caps_len, nil))
gs = C.GoString((*C.char)(buffer))
C.free(unsafe.Pointer(buffer))
}
if opt_ps != nil {
C.free(unsafe.Pointer(opt_ps))
}
}
return gs, ret_code
}
// Sets configuration for optional threat profile or for all currently supported threat profiles.
// The config string should be in the protocol format specified at construction of the TDT agent instance.
// Returns TDT_ERROR_SUCCESS or an error code.
func (agent *tdt_agent) SetConfiguration(opt_profile string, config string) tdt_return_code {
ret_code := TDT_ERROR_NULL_PARAM
if agent.h != nil {
if config != "" {
var opt_ps *C.char
var opt_ps_len C.size_t
if opt_profile != "" {
opt_ps = C.CString(opt_profile)
opt_ps_len = (C.size_t)(len(opt_profile))
}
cs := C.CString(config)
cs_len := (C.size_t)(len(config))
ret_code = tdt_return_code(C.set_configuration(agent.h, opt_ps, opt_ps_len, cs, cs_len))
C.free(unsafe.Pointer(cs))
if opt_ps != nil {
C.free(unsafe.Pointer(opt_ps))
}
} else {
ret_code = TDT_ERROR_INVALID_PARAM
}
}
return ret_code
}
// The Go notification callback exported to be invoked from C
// It uses the unique context to acquire correct agent from a map
// and invokes the notification function for that agent.
// see https://golang.org/cmd/cgo/ for more details about export.
//export GoNotifier
func GoNotifier(context uint64, msg string) {
callbackMutex.Lock()
agent := callbackFuncs[context]
callbackMutex.Unlock()
if agent == nil {
panic("missing callback context")
}
if agent.c != context {
panic("callback context mismatch")
}
if agent.f == nil {
panic("missing callback function in context")
}
agent.f(context, msg)
}
// Sets the callback for notification of detected threats or runtime errors.
// context will be passed to the callback whenever it is invoked.
// Returns TDT_ERROR_SUCCESS or an error code. TDT_ERROR_INVALID_PARAM will be returned
// if context is already used by another agent. callback will be overwritten for already existing context.
func (agent *tdt_agent) SetNotifier(callback func(uint64, string), context uint64) tdt_return_code {
ret_code := TDT_ERROR_NULL_PARAM
if agent.h != nil && context != 0 && callback != nil {
agent.f = callback
agent.c = context
// Read passing pointers section in below article.
// https://golang.org/cmd/cgo/#hdr-Using_cgo_with_the_go_command
/* https://github.com/golang/go/issues/12416
Go code that wants to preserve funcs/pointers stores them into a map indexed by an int.
Go code calls the C code, passing the int,which the C code may store freely.
When the C code wants to call into Go, it passes the int to a Go function that looks
in the map and makes the call. An explicit call is required to release the value from the
map if it is no longer needed.
*/
callbackMutex.Lock()
any_existing_agent := callbackFuncs[context]
if any_existing_agent == nil || any_existing_agent == agent {
callbackFuncs[context] = agent // overwrite existing
callbackMutex.Unlock()
ret_code = tdt_return_code(C.SetNotificationCallback(agent.h, C.longlong(context)))
} else {
callbackMutex.Unlock()
ret_code = TDT_ERROR_INVALID_PARAM
}
}
return ret_code
}
// Returns the string description of error code.
func GetErrorString(err_code tdt_return_code) string {
cs := C.GoString(C.get_error_string(C.tdt_return_code(err_code)))
return cs
}
<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package main
import (
"errors"
"flag"
"fmt"
e "intel/isecl/lib/common/exec"
"intel/isecl/lib/common/setup"
"intel/isecl/tdagent/config"
"intel/isecl/tdagent/constants"
"intel/isecl/tdagent/tasks"
"intel/isecl/tdagent/version"
"io"
"os"
"os/exec"
"path"
"strings"
"syscall"
stdlog "log"
log "github.com/sirupsen/logrus"
)
type App struct {
HomeDir string
ConfigDir string
DataDir string
LogDir string
ExecutablePath string
Interactive bool
ConsoleWriter io.Writer
LogWriter io.Writer
HTTPLogWriter io.Writer
Config *config.Configuration
}
func (a *App) homeDir() string {
if a.HomeDir != "" {
return a.HomeDir
}
return constants.HomeDir
}
func (a *App) configDir() string {
if a.ConfigDir != "" {
return a.ConfigDir
}
return constants.ConfigDir
}
func (a *App) dataDir() string {
if a.DataDir != "" {
return a.DataDir
}
return constants.DataDir
}
func (a *App) executablePath() string {
if a.ExecutablePath != "" {
return a.ExecutablePath
}
exec, err := os.Executable()
if err != nil {
// if we can't find self-executable path, we're probably in a state that is panic() worthy
panic(err)
}
return exec
}
func (a *App) logDir() string {
if a.LogDir != "" {
return a.LogDir
}
return constants.LogDir
}
func (a *App) configuration() *config.Configuration {
if a.Config == nil {
return config.Global
}
return a.Config
}
func (a *App) consoleWriter() io.Writer {
if a.ConsoleWriter == nil {
return os.Stdout
}
return a.ConsoleWriter
}
func (a *App) logWriter() io.Writer {
if a.LogWriter == nil {
return os.Stderr
}
return a.LogWriter
}
func (a *App) httpLogWriter() io.Writer {
if a.HTTPLogWriter == nil {
return os.Stderr
}
return a.HTTPLogWriter
}
func (a *App) printUsage() {
fmt.Fprintln(a.consoleWriter(), "Usage:")
fmt.Fprintln(a.consoleWriter(), "")
fmt.Fprintln(a.consoleWriter(), " tdagent <command> [arguments]")
fmt.Fprintln(a.consoleWriter(), "")
fmt.Fprintln(a.consoleWriter(), "Avaliable Commands:")
fmt.Fprintln(a.consoleWriter(), " help|-h|-help Show this help message")
fmt.Fprintln(a.consoleWriter(), " setup [task] Run setup task")
fmt.Fprintln(a.consoleWriter(), " start Start tdagent")
fmt.Fprintln(a.consoleWriter(), " stop Stop tdagent")
fmt.Fprintln(a.consoleWriter(), " uninstall Uninstall tdagent")
fmt.Fprintln(a.consoleWriter(), "")
fmt.Fprintln(a.consoleWriter(), "Avaliable Tasks for setup:")
fmt.Fprintln(a.consoleWriter(), " tdagent setup tls [--force] [--hosts=<host_names>]")
fmt.Fprintln(a.consoleWriter(), " - Use the key and certificate provided in /etc/threat-detection if files exist")
fmt.Fprintln(a.consoleWriter(), " - Otherwise create its own self-signed TLS keypair in /etc/tdagent for quality of life")
fmt.Fprintln(a.consoleWriter(), " - Option [--force] overwrites any existing files, and always generate self-signed keypair")
fmt.Fprintln(a.consoleWriter(), " - Argument <host_names> is a list of host names used by this device, seperated by comma")
fmt.Fprintln(a.consoleWriter(), " - Environment variable TDA_TLS_HOSTS=<host_names> can be set alternatively")
fmt.Fprintln(a.consoleWriter(), " tdagent setup signingkey [--force]")
fmt.Fprintln(a.consoleWriter(), " - Creates a Self Signed Signing Key in /etc/tdagent for quality of life")
fmt.Fprintln(a.consoleWriter(), " - Option [--force] overwrites any existing files, and always generate self-signed keypair")
fmt.Fprintln(a.consoleWriter(), " - The signing key is expected to be provided in /etc/threat-detection by the user")
fmt.Fprintln(a.consoleWriter(), " tdagent setup register --tds-url=<api_gateway> --tds-user=<username> --tds-pass=<<PASSWORD>>")
fmt.Fprintln(a.consoleWriter(), " - Setup the connection to the TDS as well as registers this TDA with the TDS")
fmt.Fprintln(a.consoleWriter(), " - <api_gateway> should be in format: https://<hostname>/tds/")
fmt.Fprintln(a.consoleWriter(), " - Environment variable TDS_SERVICE_BASEURL=<api_gateway> can be set alternatively")
fmt.Fprintln(a.consoleWriter(), " - Environment variable TDS_SERVICE_USERNAME=<username> can be set alternatively")
fmt.Fprintln(a.consoleWriter(), " - Environment variable TDS_SERVICE_PASSWORD=<password> can be set alternatively")
fmt.Fprintln(a.consoleWriter(), " tdagent setup tdtprofile --profile=<tdt_profile_name>")
fmt.Fprintln(a.consoleWriter(), " - Set up the profile to be used eg: telemetry")
fmt.Fprintln(a.consoleWriter(), " - <tdt_profile_name> should be the name of the file without .profile extenstion")
fmt.Fprintln(a.consoleWriter(), " - Environment variable TDT_PROFILE=<tdt_profile_name> can be set alternatively")
fmt.Fprintln(a.consoleWriter(), " tdagent setup all")
fmt.Fprintln(a.consoleWriter(), " - Setup all previous options in listed order")
fmt.Fprintln(a.consoleWriter(), "")
}
func (a *App) configureLogs() {
log.SetOutput(io.MultiWriter(os.Stderr, a.logWriter()))
log.SetLevel(a.configuration().LogLevel)
// override golang logger
w := log.StandardLogger().WriterLevel(a.configuration().LogLevel)
stdlog.SetOutput(w)
}
func (a *App) Run(args []string) error {
a.configureLogs()
if len(args) < 2 {
a.printUsage()
os.Exit(1)
}
switch command := args[1]; command {
default:
fmt.Println("Error: Unrecognized command: ", args[1])
a.printUsage()
case "help":
a.printUsage()
case "run":
a.startDaemon()
case "setup":
if len(args) <= 2 {
fmt.Fprintln(a.consoleWriter(),
`Available setup tasks:
- tls
- register
- tdtprofile
--------------
- [all]
`)
return errors.New("no setup task specified")
}
task := strings.ToLower(args[2])
flags := args[3:]
rootCAs := a.loadCAs()
setupRunner := &setup.Runner{
Tasks: []setup.Task{
tasks.TLS{
Flags: flags,
TLSCertFile: path.Join(a.configDir(), constants.TLSCertFile),
TLSKeyFile: path.Join(a.configDir(), constants.TLSKeyFile),
},
tasks.Register{
Flags: flags,
Config: a.configuration(),
RootCAs: rootCAs,
ConsoleWriter: a.consoleWriter(),
},
tasks.TdtProfile{
Flags: flags,
Config: a.configuration(),
ConsoleWriter: a.consoleWriter(),
},
},
AskInput: false,
}
var err error
if task == "all" {
err = setupRunner.RunTasks()
} else {
// run a singular task
err = setupRunner.RunTasks(task)
}
if err != nil {
fmt.Fprintln(a.consoleWriter(), "Error running setup:", err)
return err
}
case "start":
return a.start()
case "stop":
return a.stop()
case "status":
return a.status()
case "uninstall":
var keepConfig bool
flag.CommandLine.BoolVar(&keepConfig, "keep-config", false, "keep config when uninstalling")
flag.CommandLine.Parse(args[2:])
a.uninstall(keepConfig)
os.Exit(0)
case "version":
fmt.Fprintf(a.consoleWriter(), "Threat Detection Agent Version %s-%s\n", version.Version, version.GitHash)
}
return nil
}
func (a *App) start() error {
fmt.Fprintln(a.consoleWriter(), `Forwarding to "systemctl start tdagent"`)
systemctl, err := exec.LookPath("systemctl")
if err != nil {
return err
}
return syscall.Exec(systemctl, []string{"systemctl", "start", "tdagent"}, os.Environ())
}
func (a *App) stop() error {
fmt.Fprintln(a.consoleWriter(), `Forwarding to "systemctl stop tdagent"`)
systemctl, err := exec.LookPath("systemctl")
if err != nil {
return err
}
return syscall.Exec(systemctl, []string{"systemctl", "stop", "tdagent"}, os.Environ())
}
func (a *App) status() error {
fmt.Fprintln(a.consoleWriter(), `Forwarding to "systemctl status tdagent"`)
systemctl, err := exec.LookPath("systemctl")
if err != nil {
return err
}
return syscall.Exec(systemctl, []string{"systemctl", "status", "tdagent"}, os.Environ())
}
func (a *App) uninstall(keepConfig bool) {
fmt.Println("Uninstalling Threat Detection Agent")
removeService()
fmt.Println("removing : ", a.executablePath())
err := os.Remove(a.executablePath())
if err != nil {
log.WithError(err).Error("error removing executable")
}
if !keepConfig {
fmt.Println("removing : ", a.configDir())
err = os.RemoveAll(a.configDir())
if err != nil {
log.WithError(err).Error("error removing config dir")
}
}
fmt.Println("removing : ", a.logDir())
err = os.RemoveAll(a.logDir())
if err != nil {
log.WithError(err).Error("error removing log dir")
}
fmt.Println("removing : TDT and TBB libraries")
err = os.RemoveAll(constants.LibTDTFile)
if err != nil {
log.WithError(err).Error("error removing TDT symlink")
}
err = os.RemoveAll(constants.LibTBBFile)
if err != nil {
log.WithError(err).Error("error removing TBB symlink")
}
fmt.Println("removing : ", a.dataDir())
err = os.RemoveAll(a.dataDir())
if err != nil {
log.WithError(err).Error("error removing data dir")
}
fmt.Println("removing : ", a.homeDir())
err = os.RemoveAll(a.homeDir())
if err != nil {
log.WithError(err).Error("error removing home dir")
}
fmt.Fprintln(a.consoleWriter(), "Threat Detection Agent uninstalled")
}
func removeService() {
_, _, err := e.RunCommandWithTimeout(constants.ServiceRemoveCmd, 5)
if err != nil {
fmt.Println("Could not remove Threat Detection Agent Service")
fmt.Println("Error : ", err)
}
}
<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"intel/isecl/tdagent/constants"
"intel/isecl/tdagent/tdt_lib"
"intel/isecl/tdservice/client"
"intel/isecl/tdservice/types"
"io/ioutil"
"net/http"
"os"
"os/signal"
"path"
"syscall"
log "github.com/sirupsen/logrus"
)
func (a *App) loadCAs() *x509.CertPool {
rootCAs, err := x509.SystemCertPool()
if err != nil {
rootCAs = x509.NewCertPool()
}
tdsCert := path.Join(a.configDir(), constants.ServiceTLSCertFile)
if _, err := os.Stat(tdsCert); os.IsExist(err) {
certs, err := ioutil.ReadFile(tdsCert)
if err != nil {
log.WithError(err).Error("Failed to read certs file")
return rootCAs
}
// Append our cert to the system pool
if ok := rootCAs.AppendCertsFromPEM(certs); !ok {
log.Info("No certs appended, using system certs only")
}
}
return rootCAs
}
func (a *App) startDaemon() error {
log.Info("Starting Daemon")
stop := make(chan os.Signal)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
// Start TDT
log.Trace("Constructing TDT...")
tdt := tdt_lib.GetTDTAgentInstance() // New
err := tdt.Construct(tdt_lib.TDT_PROTO_FORMAT_JSON) // Merged with New()
defer tdt.Destruct() // Close()
if err != nil {
log.WithError(err).Fatal("failed to construct TDT instance")
}
log.Trace("Constructed TDT successfully")
log.Trace("Configuring TDT...")
// I dont know if TDT lets you point to a path, but I'm going to assume it doesn't right now
os.Chdir(a.dataDir())
log.Info(a.configuration().TDTProfile)
es, rc := tdt.GetConfiguration(a.configuration().TDTProfile)
if es == "" {
es = tdt_lib.GetErrorString(rc)
log.WithField("errorString", es).Error("failure getting configuration")
} else {
log.WithField("configuration", es).Info("Got configuration")
}
rc = tdt.SetConfiguration(a.configuration().TDTProfile, "{}")
if rc != tdt_lib.TDT_ERROR_SUCCESS {
return errors.New(tdt_lib.GetErrorString(rc))
}
log.Trace("Configured TDT successfully")
tds := client.Client{
BaseURL: a.configuration().TDS.BaseURL,
Username: a.configuration().TDS.Username,
Password: a.configuration().TDS.Token,
}
rootCAs := a.loadCAs()
tds.HTTPClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true, // disable this in next release
RootCAs: rootCAs,
},
},
}
log.Trace("Configuring TDT notification...")
tdt.SetNotifier(func(context uint64, message string) {
// we must be registered with the service to post reports
log.WithField("message", message).Trace("Notifier called")
hostID := a.configuration().HostID
if hostID == "" {
return
}
var report types.Report
report.HostID = hostID
err = json.Unmarshal([]byte(message), &report)
log.WithField("report", report).Debug("Got report from TDT")
if err != nil {
log.WithError(err).Error("failed to unmarshal threat notification")
return
}
_, err = tds.AddReport(report)
if err != nil {
log.WithError(err).Error("failed to post report to Threat Detection Service")
}
}, 0x1234567890)
log.Trace("Configured TDT notification successfully")
log.Trace("Starting TDT...")
rc = tdt.Start()
if rc != tdt_lib.TDT_ERROR_SUCCESS {
err := errors.New(tdt_lib.GetErrorString(rc))
log.WithError(err).WithField("rc", rc).Error("Failed to start TDT")
return err
}
fmt.Fprintln(a.consoleWriter(), "TDT Started")
log.Trace("TDT Started")
// block until stop signal is raised
<-stop
log.Info("Threat Detection Agent stopping")
tdt.Stop("")
log.Trace("TDT Stopped")
return nil
}
<file_sep>// +build !tdt
package tdt_lib
import (
"intel/isecl/tdagent/constants"
"net"
"net/rpc"
"os"
)
// The return codes from the TDT Library APIs.
type tdt_return_code int
const (
TDT_ERROR_SUCCESS tdt_return_code = iota
TDT_ERROR_NULL_PARAM
TDT_ERROR_INVALID_PARAM
TDT_ERROR_OUT_OF_MEMORY
TDT_ERROR_INTERNAL
TDT_ERROR_INSUFFICIENT_BUFFER_SIZE
TDT_ERROR_NOT_IMPLEMENTED
TDT_ERROR_STARTUP_FAILURE
TDT_ERROR_INVALID_CMD_LINE
TDT_ERROR_INVALID_PLUGIN
TDT_ERROR_INVALID_CONFIG
TDT_ERROR_NO_EXECUTION
TDT_ERROR_PIPELINE_ABORTED
TDT_ERROR_SIGNVERIFY_FAILED
)
// The protocol format to use when using the TDT Library APIs.
type tdt_protocol_format int
const (
TDT_PROTO_FORMAT_JSON tdt_protocol_format = iota
TDT_PROTO_FORMAT_XML
)
type tdt_agent struct {
listener net.Listener
cb func(uint64, string)
c uint64
}
type Mock struct {
agent *tdt_agent
}
func GetTDTAgentInstance() *tdt_agent {
return &tdt_agent{}
}
func (agent *tdt_agent) Construct(fmt tdt_protocol_format) (err error) {
return
}
// Destructs an instance of TDT agent.
// Returns nil on success or any encountered error.
func (agent *tdt_agent) Destruct() (err error) {
return
}
func (m *Mock) MockNotify(notification string, reply *int) error {
m.agent.cb(m.agent.c, notification)
return nil
}
// Starts the threat detection for all currently configured threat profiles.
// Returns TDT_ERROR_SUCCESS or an error code.
func (agent *tdt_agent) Start() (rc tdt_return_code) {
r := rpc.NewServer()
var err error
os.Remove(constants.MockSockFile)
agent.listener, err = net.Listen("unix", constants.MockSockFile)
if err != nil {
return TDT_ERROR_STARTUP_FAILURE
}
r.Register(&Mock{agent: agent})
go r.Accept(agent.listener)
return
}
// Stops threat detection for all currently configured profiles or a specified profile.
// If opt_profile is empty then stops detection for all profiles.
// Returns TDT_ERROR_SUCCESS or an error code.
func (agent *tdt_agent) Stop(opt_profile string) (rc tdt_return_code) {
if agent.listener != nil {
agent.listener.Close()
}
return
}
// Discovers capabilities and threat profiles currently supported.
// On success it returns the capabilities and profiles in the protocol format
// specified during construction of the TDT agent instance and
// TDT_ERROR_SUCCESS. On failure it returns an empty string with an error code.
func (agent *tdt_agent) Discover() (cap string, rc tdt_return_code) {
return
}
// Gets configuration for optional threat profile or for all currently supported threat profiles.
// On success it returns the configuration(s) in the protocol format
// specified during construction of the TDT agent instance and
// TDT_ERROR_SUCCESS. On failure it returns an empty string with an error code.
func (agent *tdt_agent) GetConfiguration(opt_profile string) (conf string, rc tdt_return_code) {
return "{}", 0
}
// Sets configuration for optional threat profile or for all currently supported threat profiles.
// The config string should be in the protocol format specified at construction of the TDT agent instance.
// Returns TDT_ERROR_SUCCESS or an error code.
func (agent *tdt_agent) SetConfiguration(opt_profile string, config string) (rc tdt_return_code) {
return
}
// The Go notification callback exported to be invoked from C
// It uses the unique context to acquire correct agent from a map
// and invokes the notification function for that agent.
// see https://golang.org/cmd/cgo/ for more details about export.
//export GoNotifier
func GoNotifier(context uint64, msg string) {
}
// Sets the callback for notification of detected threats or runtime errors.
// context will be passed to the callback whenever it is invoked.
// Returns TDT_ERROR_SUCCESS or an error code. TDT_ERROR_INVALID_PARAM will be returned
// if context is already used by another agent. callback will be overwritten for already existing context.
func (agent *tdt_agent) SetNotifier(callback func(uint64, string), context uint64) (rc tdt_return_code) {
agent.cb = callback
agent.c = context
return
}
// Returns the string description of error code.
func GetErrorString(err_code tdt_return_code) (errStr string) {
return
}
<file_sep>/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package tasks
import (
"bytes"
"intel/isecl/lib/common/setup"
"intel/isecl/tdagent/config"
"net/http"
"net/http/httptest"
"testing"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
)
func mockTDS() *httptest.Server {
r := mux.NewRouter()
r.Handle("/tds/hosts", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(201)
w.Write([]byte(`{"id": "eb6af396-361b-4d22-b27b-56bc8290d334"}`))
})).Methods("POST")
r.Handle("/tds/hosts/{id}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
if id == "eb6af396-361b-4d22-b27b-56bc8290d334" {
w.Write([]byte(`{"id": "eb6af396-361b-4d22-b27b-56bc8290d334"}`))
return
}
w.WriteHeader(404)
})).Methods("GET")
server := httptest.NewServer(r)
return server
}
func TestRegister(t *testing.T) {
assert := assert.New(t)
s := mockTDS()
defer s.Close()
c := &config.Configuration{}
var cw bytes.Buffer
task := Register{
Config: c,
ConsoleWriter: &cw,
Flags: []string{"-tds-url", s.URL + "/tds/", "-tds-user", "admin", "-tds-pass", "<PASSWORD>"},
}
context := setup.Context{}
err := task.Run(context)
assert.Equal(config.ErrNoConfigFile, err)
}
func TestAlreadyRegistered(t *testing.T) {
assert := assert.New(t)
s := mockTDS()
defer s.Close()
c := &config.Configuration{}
c.TDS.BaseURL = s.URL + "/tds/"
c.TDS.Username = "admin"
c.TDS.Token = "<PASSWORD>"
c.HostID = "eb6af396-361b-4d22-b27b-56bc8290d334"
var cw bytes.Buffer
task := Register{
Config: c,
ConsoleWriter: &cw,
Flags: nil,
}
context := setup.Context{}
err := task.Validate(context)
assert.NoError(err)
}
func TestReregister(t *testing.T) {
assert := assert.New(t)
s := mockTDS()
defer s.Close()
c := &config.Configuration{}
c.HostID = "aaaaf396-361b-4d22-b27b-56bc8290d334"
var cw bytes.Buffer
task := Register{
Config: c,
ConsoleWriter: &cw,
Flags: []string{"-tds-url", s.URL + "/tds/", "-tds-user", "admin", "-tds-pass", "<PASSWORD>"},
}
context := setup.Context{}
err := task.Run(context)
assert.Equal(config.ErrNoConfigFile, err)
}
func TestInvalidURL(t *testing.T) {
assert := assert.New(t)
good_url_1 := "https://google.com"
good_url_2 := "http://good.url.with.port:5566"
good_url_3 := "https://good.url.https.with.port:5566"
good_tests := [3]string{good_url_1, good_url_2, good_url_3}
for _, good_str := range good_tests {
var cw bytes.Buffer
task := Register{
Config: &config.Configuration{},
ConsoleWriter: &cw,
Flags: []string{"-tds-url", good_str + "/tds/", "-tds-user", "admin", "-tds-pass", "<PASSWORD>"},
}
context := setup.Context{}
err := task.Run(context)
assert.NotEqual(err, ErrInvalidBaseURL)
assert.NotEqual(err, ErrInvalidWebProtocol)
assert.NotEqual(err, ErrInvalidPath)
assert.NotEqual(err, ErrQueryAttached)
}
bad_url_1 := "bad.url.without.protocol/tds/"
bad_url_2 := "scheme://bad.url.with.wrong.protocol/tds/"
bad_url_3 := "https://bad.url.with.path/tds/path/path/"
bad_url_4 := "https://bad.url.with.query/tds/?query=haha"
bad_tests := [4]string{bad_url_1, bad_url_2, bad_url_3, bad_url_4}
bad_results := [4]error{ErrInvalidWebProtocol, ErrInvalidWebProtocol, ErrInvalidPath, ErrQueryAttached}
for i, bad_str := range bad_tests {
var cw bytes.Buffer
task := Register{
Config: &config.Configuration{},
ConsoleWriter: &cw,
Flags: []string{"-tds-url", bad_str, "-tds-user", "admin", "-tds-pass", "<PASSWORD>"},
}
context := setup.Context{}
err := task.Run(context)
assert.Equal(bad_results[i], err)
}
}
<file_sep>// +build tdt
/*
********************************************************************************
** Intel Architecture Group
** Copyright (C) 2018-2019 Intel Corporation
********************************************************************************
**
** INTEL CONFIDENTIAL
** This file, software, or program is supplied under the terms of a
** license agreement and/or nondisclosure agreement with Intel Corporation
** and may not be copied or disclosed except in accordance with the
** terms of that agreement. This file, software, or program contains
** copyrighted material and/or trade secret information of Intel
** Corporation, and must be treated as such. Intel reserves all rights
** in this material, except as the license agreement or nondisclosure
** agreement specifically indicate.
**
** All rights reserved. No part of this program or publication
** may be reproduced, transmitted, transcribed, stored in a
** retrieval system, or translated into any language or computer
** language, in any form or by any means, electronic, mechanical,
** magnetic, optical, chemical, manual, or otherwise, without
** the prior written permission of Intel Corporation.
**
** Intel makes no warranty of any kind regarding this code. This code
** is provided on an "As Is" basis and Intel will not provide any support,
** assistance, installation, training or other services. Intel does not
** provide any updates, enhancements or extensions. Intel specifically
** disclaims any warranty of merchantability, noninfringement, fitness
** for any particular purpose, or any other warranty.
**
** Intel disclaims all liability, including liability for infringement
** of any proprietary rights, relating to use of the code. No license,
** express or implied, by estoppel or otherwise, to any intellectual
** property rights is granted herein.
**/
/********************************************************************************
**
** @file tdt_agent.c
**
** @brief CGO notification interface for Threat Detection Technology Library.
**
**
********************************************************************************
*/
#include "tdt_agent.h"
/** @brief Generated at run time by the cgo module.
* Exports the GoNotifier from Go to be accessed from C
*/
#include "_cgo_export.h"
/**
* @brief The notification bridge function between Go and C languages.
*
* @param[in] context the context that was passed to SetNotificationCallback
* @param[in] msg the notification message
* @param[in] msg_len the length of msg in bytes
*/
void NotifierBridgeCallback(const long long context, const char *msg, const size_t msg_len)
{
GoNotifier(context, (GoString) { msg, msg_len });
}
/**
* @brief sets the intermediate bridge callback for notifications
*
* @param[in] hagent the agent handle returned by construct_agent
* @param[in] context to send with notifications
*
* @return TDT_ERROR_SUCCESS on success or an error code
*/
tdt_return_code SetNotificationCallback(agent_handle hagent, const long long context)
{
return set_notification_callback(hagent, NotifierBridgeCallback, context);
} | 565cdc790035a94d89eeb42afff48ccf1bff05d6 | [
"Markdown",
"Makefile",
"Go Module",
"C",
"Go",
"C++",
"Shell"
]
| 23 | C | intel-secl/tdagent | 5354c23ac217c2d792aba15b5c3906a00cd3ff80 | 77dc43235bb80e81de879553f94e9668b73d12b8 |
refs/heads/master | <file_sep>function calculate() {
// get input from user
// var $list_price; // Declare variable
var listPrice =
document.getElementById('list_price').valueAsNumber;
var customerType =
document.getElementById('type').value;
// Assign value to get reference to user input using document object method
$list_price = document.getElementById('list_price');
$list_price = $list_price.valueAsNumber; // new to html 5 - Get number value inputted using number object method
// Calculate discount amount and discount price
// var $discount_percent = document.getElementById('discount_percent').valueAsNumber;
// Calculate discount percent
if (customerType == "R") {
if (listPrice < 100)
discountPercent = 0;
else if (listPrice >= 100 && listPrice < 250)
discountPercent = 10;
else if (listPrice >= 250)
discountPercent = 25;
} else if (customerType == "C") {
if (listPrice < 250)
discountPercent = 20;
else
discountPercent = 30;
}
discountPercent = parseFloat(discountPercent);
// calculate discount amount and discount price
var $discount = $list_price * $discount_percent * .01;
var $discount_price = $list_price - $discount;
//set output
document.getElementById('discount_percent').valueAsNumber = discountPercent;
$discount = $discount.toFixed(2); // Convert number value to string value keeping 2 decimal places
$discount = '$' +$discount; // Concatenate $ to string variable
var tempVar; // Declare variable
tempVar = document.getElementById('discount'); // Set reference to output using document object method
tempVar.value = $discount; // Set string value output using string object methods
$discount_price = '$'+$discount_price.toFixed(2);
document.getElementById('discount_price').value = $discount_price;
} // end calculate
| 956803a317d1660d8d04af7c60844ac942d0c6b8 | [
"JavaScript"
]
| 1 | JavaScript | ickenj/baw-week-10 | 79b62d526e4917b2a098ba964572db0fddc75e95 | 8c8534e7795ca0a6c69e98f4cee3f5a160408608 |
refs/heads/master | <file_sep>const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());
const compiled_contract = require('../compile');
const bytecode = compiled_contract.evm.bytecode.object;
const abi = compiled_contract.abi;
let accounts;
let lottery;
let manager;
beforeEach(async () => {
accounts = await web3.eth.getAccounts();
lottery = await new web3.eth.Contract(abi)
.deploy({ data: bytecode })
.send({ from: accounts[0], gas:'1000000' });
manager = accounts[0];
})
describe('Lottery Contract', () => {
it('deploys a contract', () => {
assert.ok(lottery.options.address)
});
it('join one player to the lottery when minimum money is paid', async () => {
const player = accounts[0];
await lottery.methods.join().send({
from: player,
value: web3.utils.toWei('0.02', 'ether') });
const playersList = await lottery.methods.getPlayers().call({
from: manager
});
assert.strictEqual(1, playersList.length);
assert.strictEqual(player, playersList[0]);
})
it('join multiple players to the lottery when minimum money is paid', async () => {
const player1 = accounts[1];
const player2 = accounts[2];
await lottery.methods.join().send({
from: player1,
value: web3.utils.toWei('0.02', 'ether') });
await lottery.methods.join().send({
from: player2,
value: web3.utils.toWei('0.02', 'ether') });
const playersList = await lottery.methods.getPlayers().call({
from: manager
});
assert.strictEqual(2, playersList.length);
assert.strictEqual(player1, playersList[0]);
assert.strictEqual(player2, playersList[1]);
})
it('refuse joining player to the lottery when minimum amount is not paid', async () => {
const player = accounts[0];
let error;
try {
await lottery.methods.join().send({
from: player,
value: '10' });
} catch (err) {
error = err;
}
const playersList = await lottery.methods.getPlayers().call({
from: manager
});
assert(error);
assert.strictEqual(0, playersList.length);
})
it('only manager should be allowed to pick winner', async () => {
let error;
try {
await lottery.methods.pickWinner().call({
from: accounts[1]
});
} catch (err) {
error = err
}
assert(error);
})
it('manager picks a winner, winner receives money and playesrs list get reset', async () => {
const player1 = accounts[1];
const player2 = accounts[2];
await lottery.methods.join().send({
from: player1,
value: web3.utils.toWei('0.02', 'ether') });
const player1InitialBalance = await web3.eth.getBalance(player1);
await lottery.methods.join().send({
from: player2,
value: web3.utils.toWei('0.02', 'ether') });
const player2InitialBalance = await web3.eth.getBalance(player2);
lotteryBalance = await web3.eth.getBalance(lottery.options.address);
// console.log(player1InitialBalance, player2InitialBalance, lotteryBalance);
// ensure players are added to the lottery
const playersListBeforePickingWinner = await lottery.methods.getPlayers().call({
from: manager
});
assert.strictEqual(2, playersListBeforePickingWinner.length);
assert.strictEqual(player1, playersListBeforePickingWinner[0]);
assert.strictEqual(player2, playersListBeforePickingWinner[1]);
// no winner untill picked
let winner = await lottery.methods.getWinner().call();
assert.strictEqual(winner, '0x0000000000000000000000000000000000000000');
// pick a winner
await lottery.methods.pickWinner().send({
from: manager
});
winner = await lottery.methods.getWinner().call();
assert(winner);
let winningPlayer;
let winningPlayerFinalBalance;
let difference;
if (winner == player1) {
console.log('Player1 wins');
winningPlayer = player1;
winningPlayerFinalBalance = await web3.eth.getBalance(winningPlayer);
difference = winningPlayerFinalBalance - player1InitialBalance;
} else {
console.log('Player2 wins');
winningPlayer = player2;
winningPlayerFinalBalance = await web3.eth.getBalance(winningPlayer);
difference = winningPlayerFinalBalance - player2InitialBalance;
}
// console.log(difference);
// winning price should be equal to lottery balance
assert.strictEqual(difference.toString(), lotteryBalance);
// contract balance should become zero after picking winner
lotteryBalanceAfterPickingWinner = await web3.eth.getBalance(lottery.options.address);
assert.strictEqual('0', lotteryBalanceAfterPickingWinner);
// list of players should reset after picking a winner
const playersListAfterPickingWinner = await lottery.methods.getPlayers().call({
from: manager
});
assert.strictEqual(0, playersListAfterPickingWinner.length);
})
});<file_sep># ethereum_lottery
A ethereum based lottery smart contract which allows to add players and pick one as winner.
| b80a661095bad2849c08b6b8a5c4907ca32f71b1 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | kshewani/ethereum_lottery | bcdab26aa8cb3735773da1c4ffff86709ea60549 | c0f611844e89215407ee50e976293b51bb28fbe3 |
refs/heads/master | <repo_name>kiaia/Library<file_sep>/Librarytest/src/Librarytest.java
/**
* Copyright KaiKiaia.
* All right reserved.
*/
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.regex.*;
import java.math.BigDecimal;
import java.lang.String;
import java.util.Collection;
import java.util.*;
import java.util.Iterator;
import static java.lang.Integer.min;
public class Librarytest {
public static void main(String[] args) {
Console test1 = new Console();
boolean runningstate=test1.run();
while(runningstate){runningstate=test1.run();}
//santi.print();
/* 推荐测试命令
超级用户账号:super1 密码:<PASSWORD>
超级用户账号:super2 密码:<PASSWORD>
超级用户账号:super3 密码:<PASSWORD>
注册普通用户 输入账号密码后 按y确认
注册管理员 登录超级用户账号后 使用addorgan命令 输入账号密码后 按y确认
使用help命令查看帮助
添加的书籍数据 9787309132519, fuzizaixiang,wo,12.7,30,20
修改的书籍数据 9787121316388,9787111301974,two body,liucixi,12.7,30,20
search words -d al
search words -w al
search words -d
search isbn 9787121316388
search isbn 23
exit
help
ctrl+z
采用shell式命令输入,目前-d/-w还不能省略
*/
/*
8981
123
exit
super1
123456
searchuser
*/
}
}
class Console {
Library buaa = new Library();
Userdatebase testUser= new Userdatebase();
String input = "";
String cons="";
String modification = "";
String modification2 = "";
String code = "";
int page=1;
Scanner scan = new Scanner(System.in);
Calendar now= Calendar.getInstance();
Console() {
File file = new File("src/inputbook.txt");
char[] data = new char[8192];
try (Reader reader = new FileReader(file)) {
reader.read(data);
} catch (Exception e) {
e.printStackTrace();
}
String res=String.valueOf(data);
String[] record = res.split("\n");
for(int i=0;i<record.length;i++){
String[] member=record[i].split(",");
buaa.addBook(new Book(member[1],member[0],member[2],member[3],
Integer.parseInt(member[4]),
Integer.parseInt(member[5].toString().trim())));
}
/*Book sant1 = new Book("9787121316388", "three body", "liucixi", "12.7", 30, 20);
Book sant2 = new Book("9787040406641", "aldatabase", "liucixi", "12.7", 30, 20);
Book sant3 = new Book("9787302424505", "algorithm", "wo", "12.7", 30, 20);
Book sant4 = new Book("9787507603507", "alaa", "wo", "12.7", 30, 20);
Book sant5 = new Book("9787539654706", "testbook", "wo", "12.7", 30, 20);
Book sant6 = new Book("9787530218723", "yuannv", "wo", "12.7", 30, 20);
Book sant7 = new Book("9787530218648", "banshengyuan", "wo", "12.7", 30, 20);
Book sant8 = new Book("9787531741220", "chunmingwaishi", "zhanghenshui", "12.7", 30, 20);
Book sant9 = new Book("9787559625243", "xiaofengsanwen", "wo", "12.7", 30, 20);
Book sant10 = new Book("9787559420589", "jvzheng", "wo", "12.7", 30, 20);
Book sant11= new Book("9787020145881", "huangsha", "wo", "12.7", 30, 20);
Book sant12 = new Book("9787500320616", "kanbudong", "wo", "12.7", 30, 20);
//Book sant14= new Book("9787309132519", "fuzizaixiang", "wo", "12.7", 30, 20);
//9787309132519, fuzizaixiang,wo,12.7,30,20
//9787121316388,9787111301974,,three body,liucixi,12.7,30,20
buaa.addBook(sant1);
buaa.addBook(sant3);
buaa.addBook(sant2);
buaa.addBook(sant4);
buaa.addBook(sant5);
buaa.addBook(sant6);
buaa.addBook(sant7);
buaa.addBook(sant8);
buaa.addBook(sant9);
buaa.addBook(sant10);
buaa.addBook(sant11);
buaa.addBook(sant12);
//buaa.addBook(sant14);*/
}
boolean run() {
//Library testLib = new Library();
String logininres=login();
while((logininres.equals("quit"))||(logininres.equals("useridwrong"))||(logininres.equals("passwordswrong")))
{
if(logininres.equals("quit")){savebook();saveuser();saveborrow();return false;}
logininres=login();
}
String loginlevel=testUser.userTreeMap.get(logininres).level.toString();
System.out.println("setup in "+loginlevel+"mode");
if(loginlevel.equals("user"))
{mainMenu(); return userprogram(logininres);}
if(loginlevel.equals("organizer"))
{organMenu();return organprogram(logininres);}
if(loginlevel.equals("superuser"))
{ superMenu(); return superprogram(logininres);}
return false;
}
boolean userprogram(String username){
input = "";
cons="";
modification = "";
modification2 = "";
code = "";
while (!input.equals("exit")) {
input = inputF();
if (input.equals("error")) {
System.out.println("wrong isbn");
continue;
}
if (input.equals("exit")) {
return true;
}
if (input.equals("quit")) {
savebook();
saveuser();
saveborrow();
return false;
}
switch (cons) {
case "search":
this.search();
break;
case "help":
this.mainMenu();
break;
case "exit":
break;
case "borrow":
this.borrowbook(username);
break;
case "renew":
this.renewbook(username);
break;
case "returnbook":
this.returnBook(username);
break;
case "showmybook":
this.showmybook(username,buaa);
break;
case "addtime":
addtime();
break;
case "showtime":
showtime(now);
break;
default:
System.out.println("input error ,input help to get help");
}
}
return true;
}
boolean showtime(Calendar now){
Date tasktime=now.getTime();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(tasktime));
return true;
}
boolean organprogram(String username){
input = "";
cons="";
modification = "";
modification2 = "";
code = "";
while (!input.equals("exit")) {
input = inputF();
if (input.equals("error")) {
System.out.println("wrong isbn");
continue;
}
if (input.equals("exit")) {
return true;
}
if (input.equals("quit")) {
savebook();
saveuser();
saveborrow();
return false;
}
switch (cons) {
case "search":
this.search();
break;
case "help":
this.mainMenu();
this.organMenu();
break;
case "exit":
break;
case "searchuser":
searchuser();
break;
case "addbook":
addBook();
break;
case "alterbook":
alterbook();
break;
case "deletebook":
deletbook();
break;
case"borrowlist":
borrowlist();
break;
case "reducenoborrow":
reducenoborrow();
break;
default:
System.out.println("input error ,input help to get help");
}
input = "";
cons="";
modification = "";
modification2 = "";
code = "";
}
return true;
}
boolean superprogram(String username){
input = "";
cons="";
modification = "";
modification2 = "";
code = "";
while (!input.equals("exit")) {
input = inputF();
if (input.equals("error")) {
System.out.println("wrong isbn");
continue;
}
if (input.equals("exit")) {
return true;
}
if (input.equals("quit")) {
savebook();
saveuser();
saveborrow();
return false;
}
switch (cons) {
case "search":
this.search();
break;
case "help":
this.mainMenu();
this.organMenu();
this.superMenu();
break;
case "exit":
break;
case "addbook":
addBook();
break;
case "alterbook":
alterbook();
break;
case "deletebook":
deletbook();
break;
case "searchuser":
searchuser();
break;
case "searchorgan":
searchorgan();
break;
case "addorgan":
addorgan();
break;
case "addtime":
addtime();
break;
default:
System.out.println("input error ,input help to get help");
}
input = "";
cons="";
modification = "";
modification2 = "";
code = "";
}
return true;
}
private String login(){
String userid;
String password;
System.out.println("please input your userid and password,if you want to register a new count");
System.out.println("input the userid and password and comfirm to make a new count");
System.out.println("Please set a password with a length greater than 5 and less than 30.");
System.out.println("userid:");
userid=inputP();if(userid.equals("quit"))return "quit";
System.out.println("password:");
password=inputP();if(password.equals("quit"))return "quit";
if(testUser.checkcount(userid,password).equals("useridwrong")){
System.out.println(" the userid you input didn'exit, input \'y\' to make a new count");
String inputs=scan.nextLine();
if(inputs.equals("y"))
{
int res=testUser.addUser(userid,password);
if(res==1){
System.out.println("addusersucc");
return testUser.userTreeMap.get(userid).getName();}
else if(res==2){
System.out.println("\n" +
"Please set a password with a length greater than 5 and less than 30.");
return "useridwrong";}
} else return "useridwrong";}
if(testUser.checkcount(userid,password).equals("<PASSWORD>")){
System.out.println(" the password is wrong,please try again");
return "<PASSWORD>";
}
return testUser.userTreeMap.get(userid).getName().toString();
}
String inputP(){
String res="";
//String password="";
try{res = scan.nextLine();}catch(NoSuchElementException e){ savebook();saveuser();saveborrow();System.out.println("强制退出");return "exit";}
return res;
}
String inputF() {
String inputstr = " ";
String[] temp = new String[4];
input="";
cons = "";
modification = "";
modification2 = "";
code = "";
// while(scan.hasNextLine()){
try{inputstr = scan.nextLine();}catch(NoSuchElementException e){ savebook();saveuser();saveborrow();System.out.println("强制退出");return "exit";} //输入ctrl+z抛出异常
//catch(EOFException b){ System.out.println("强制退出");}
// }
{int i = 0;
for (String retval : inputstr.split(" +", 4)) {
//System.out.println(retval);
temp[i] = retval;
i++;
}
if(temp[0]!=null)cons = temp[0];
if(temp[1]!=null)modification = temp[1];
if(temp[2]!=null)modification2 = temp[2];
if(temp[3]!=null)code = temp[3];}
if(modification.equals("isbn")&&(!ISBN.pubcheckisbn(modification2)))return "error";
//scan.close();
return inputstr;
}
void search() {
if (modification.equals("isbn"))
System.out.println(buaa.getBookByIsbn(this.modification2).getTitle());
if (modification.equals("words")) {
page = 1;
if (modification2.equals( "-d")) {
List<Book> matchbook = buaa.getBooksByKeyword(code);
searchhelp(matchbook);
}
if (modification2 .equals( "-w")||(modification2.equals("")&&code.equals(""))) {
List<Book> matchbook = buaa.getBooksByKeyword(code);
Collections.sort(matchbook, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o1.getTitle().compareTo(o2.getTitle()); //升序排列
}
});
searchhelp(matchbook);
}
}
}
void searchhelp(List<Book> matchbook){
System.out.format("%-15s %-15s %-15s %-15s %-7s %7s\n",new String("title"),new String("isbn"),new String("author"),new String("price"),new String("rest"),new String("total"));
if (matchbook.size() < 10)
for (int i = 0; i < matchbook.size(); i++) {
System.out.format("%-15s %-15s %-15s %-15s %-7d %7d\n",matchbook.get(i).getTitle(),matchbook.get(i).code.isbn,matchbook.get(i).getAuthor(),matchbook.get(i).getPrice(),matchbook.get(i).getRest(),matchbook.get(i).getTotal());
}
if (matchbook.size() >= 10) {
for (int i = 0; i < 10; i++) {
System.out.format("%-15s %-15s %-15s %-15s %-7d %7d\n",matchbook.get(i).getTitle(),matchbook.get(i).code.isbn,matchbook.get(i).getAuthor(),matchbook.get(i).getPrice(),matchbook.get(i).getRest(),matchbook.get(i).getTotal());
}
System.out.println("now you are in page"+page);
Pagehelp();
while (showoptions( matchbook.size(), matchbook)) {
}
}
}
void showlist( List<Book> matchbook,int matchlist) {
System.out.format("%-15s %-15s %-15s %-15s %-7s %7s\n",new String("title"),new String("isbn"),new String("author"),new String("price"),new String("rest"),new String("total"));
for (int i = 0; i < (min(10,matchlist-(page - 1) * 10)); i++) {
System.out.format("%-15s %-15s %-15s %-15s %-7d %7d\n",matchbook.get(i).getTitle(),matchbook.get(i).code.isbn,matchbook.get(i).getAuthor(),matchbook.get(i).getPrice(),matchbook.get(i).getRest(),matchbook.get(i).getTotal());
}
System.out.println("now you are in page"+page);
}
void showuserlist( List<User> matchbook,int matchlist) {
for (int i = 0; i < (min(10,matchlist-(page - 1) * 10)); i++) {
System.out.print(matchbook.get(i + (page - 1) * 10).getName()+" ");
System.out.println(matchbook.get(i + (page - 1) * 10).getPassword());
}
System.out.println("now you are in page"+page);
}
boolean showoptions(int matchlist, List<Book> matchbook) {
Scanner scan = new Scanner(System.in);
int ins = scan.nextInt();
if (ins == 0 && checkRange(page, matchlist, ins)) {page++;showlist( matchbook,matchlist);}
else if (ins == -1 && checkRange(page, matchlist, ins)) {page--;showlist( matchbook,matchlist);}
else if ((ins<-2||ins>0) &&checkRange(page, matchlist, ins)) {page=ins;showlist( matchbook,matchlist);}
else if (ins == -2) return false;
Pagehelp();
return true;
}
void Pagehelp(){
System.out.println("input \"0\" to see the next page");
System.out.println("input \"-1\" to see the last page");
System.out.println("input \"[number]\" to see the designated page");
System.out.println("if you want to borrow a book ,use borrow (isbn)");
System.out.println("input \"-2\" to exit");
}
boolean showuseroptions(int matchlist, List<User> matchbook) {
Scanner scan = new Scanner(System.in);
int ins = scan.nextInt();
if (ins == 0 && checkRange(page, matchlist, ins)) {page++;showuserlist( matchbook,matchlist);}
else if (ins == -1 && checkRange(page, matchlist, ins)) {page--;showuserlist( matchbook,matchlist);}
else if ((ins<-2||ins>0) &&checkRange(page, matchlist, ins)) {page=ins;showuserlist( matchbook,matchlist);}
else if (ins == -2) return false;
Pagehelp();
return true;
}
boolean checkRange(int page, int matchlist, int ins) {
if (page == 1 && ins == -1) {
System.out.println("This is the first page!");
return false;
}
if (page == (matchlist /10+1) && ins == 0) {
System.out.println("This is the last page!");
return false;
}
if (ins < -2|| ins > (matchlist / 10 + 1)) {
System.out.println("The designated page is out of range");
return false;
}
return true;
}
String addorgan(){
String organid="";
String password="";
System.out.println("please input organid and password you want to register ");
System.out.println("input the userid and password and comfirm to make a new count");
//
System.out.println("userid:");
organid=inputP();if(organid.equals("exit"))return "exit";
System.out.println("password:");
password=inputP();if(password.equals("exit"))return "exit";
if(testUser.checkcount(organid,password).equals("useridwrong")){
System.out.println(" the userid you input didn'exit, input \'y\' to make a new count");
String inputs=scan.nextLine();
if(inputs.equals("y")){testUser.addorgan(organid,password);return "success";}}
if(testUser.checkcount(organid,password).equals("passwordwrong"))
{System.out.println(" the id you input has existed,please change a new id");}
return "failed";
}
boolean searchorgan(){
List<User> matchbook = testUser.searchorgan(modification);
Collections.sort(matchbook, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return o1.getName().compareTo(o2.getName()); //升序排列
}
});
searchuserhelp(matchbook);
return true;
}
boolean searchuser(){
List<User> matchbook = testUser.searchuser(modification);
Collections.sort(matchbook, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return o1.getName().compareTo(o2.getName()); //升序排列
}
});
searchuserhelp(matchbook);
return true;
}
void searchuserhelp(List<User> matchbook){
if (matchbook.size() < 10)
for (int i = 0; i < matchbook.size(); i++) {
System.out.print(matchbook.get(i).getName()+" ");
System.out.println(matchbook.get(i).getPassword());
}
if (matchbook.size() >= 10) {
for (int i = 0; i < 10; i++) {
System.out.print(matchbook.get(i).getName()+" ");
System.out.println(matchbook.get(i).getPassword());
}
System.out.println("now you are in page"+page);
Pagehelp();
while (showuseroptions( matchbook.size(), matchbook)) {
}
}
}
void mainMenu() {
System.out.println("input following code to get information");
System.out.println("\"search isbn (isbncode)\" to get the book ");
System.out.println("\"search words -d/-w (keywords) \" to get the book ,\"-d\"means sort by ISBN ascending order,\"-w\"means sort by heading dictionary order ");
System.out.println("search words -d/-w without keywords will show all the book in the lib");
System.out.println("\"help\" to get help ");
System.out.println("\"exit\" to exit this count ");
System.out.println("\"quit\" to quit this program ");
System.out.println("\"borrow (isbn) (-t)\" to borrow a book ");
System.out.println("\"renew (isbn) (-t)\" to renew a book ");
System.out.println("\"returnbook (isbn) (-t)\" to return a book ");
System.out.println("The above three commands can only use the time modified by addtime when - t is used, otherwise the current system time will be used automatically.");
System.out.println("\"showmybook\" to show your related books ");
System.out.println("\"showtime\" to get current time ");
System.out.println("\"addtime\" to Delay the current time by ten days ");
}
String addBook(){
System.out.println("\"input code title author price,totalnumber,restnumber\" ");
System.out.println("example:\"addbook,9787121316388,three body,liucixi,12.7,30,20");
String inputstr = " ";
String[] temp = new String[9];
String code="";
String title = "";
String author = "";
String price = "";
int totalnumber=0;
int resnumber=0;
// while(scan.hasNextLine()){
try{inputstr = scan.nextLine();}catch(NoSuchElementException e){ savebook();saveuser();saveborrow(); System.out.println("强制退出");return "exit";} //输入ctrl+z抛出异常
//catch(EOFException b){ System.out.println("强制退出");}
// }
{int j = 0;
for (String retval : inputstr.split(",", 20)) {
//System.out.println(retval);
temp[j] = retval;
j++;
}}
if(temp[0]!=null)code=temp[0];
if(temp[1]!=null)title = temp[1];
if(temp[2]!=null) author = temp[2];
if(temp[3]!=null) price = temp[3];
if(temp[4]!=null)totalnumber=Integer.parseInt(temp[4]);
if(temp[5]!=null)resnumber=Integer.parseInt(temp[5]);
Book newbook=new Book(code,title,author,price,totalnumber,resnumber);
if(!buaa.addBook(newbook))return "addfalse";
//scan.close();
System.out.println("successfully addbook");
return "addtrue";
}
String alterbook(){
System.out.println("\"input old code new code title author price,totalnumber,restnumber\" ");
System.out.println("example:\"9787121316388,9787111301974,,three body,liucixi,12.7,30,20");
String inputstr = " ";
String[] temp = new String[9];
String code="";
String code1="";
String title = "";
String author = "";
String price = "";
int totalnumber=0;
int resnumber=0;
// while(scan.hasNextLine()){
try{inputstr = scan.nextLine();}catch(NoSuchElementException e){ savebook();saveuser();saveborrow();System.out.println("强制退出");return "exit";} //输入ctrl+z抛出异常
//catch(EOFException b){ System.out.println("强制退出");}
// }
{int j = 0;
for (String retval : inputstr.split(",", 20)) {
//System.out.println(retval);
temp[j] = retval;
j++;
}}
if(temp[0]!=null)code=temp[0];
if(temp[1]!=null)code1=temp[1];
if(temp[2]!=null)title = temp[2];
if(temp[3]!=null)author = temp[3];
if(temp[4]!=null)price = temp[4];
if(temp[5]!=null)totalnumber=Integer.parseInt(temp[5]);
if(temp[6]!=null)resnumber=Integer.parseInt(temp[6]);
//Book newbook=new Book(code,title,author,price,totalnumber,resnumber);
if(!buaa.changeBook(code,code1,title,author,price,totalnumber,resnumber))return "addfalse";
//scan.close();
System.out.println("successfully alterbook");
return "altertrue";
}
boolean deletbook(){
if(!buaa.deleteBook(modification))return false;
System.out.println("successfully deletebook");
return true;
}
void organMenu(){
System.out.println("input following code to get information");
System.out.println("\"search isbn (isbncode)\" to get the book ");
System.out.println("\"search words -d/-w (keywords) \" to get the book ,\"-d\"means sort by ISBN ascending order,\"-w\"means sort by heading dictionary order ");
System.out.println("search words -d/-w without keywords will show all the book in the lib");
System.out.println("\"help\" to get help ");
System.out.println("\"exit\" to exit this count ");
System.out.println("\"quit\" to quit this program ");
System.out.println("\"addbook\" ");
System.out.println("\"deletbook isbn\"");
System.out.println("\"searchuser userid\"");
System.out.println("\"reducenoborrow (userid)\"to reduce the noborrow-time for a user");
System.out.println("\"borrowlist (userid)\"to get a user's related books");
}
void superMenu(){
System.out.println("input following code to get information");
System.out.println("\"search isbn (isbncode)\" to get the book ");
System.out.println("\"search words -d/-w (keywords) \" to get the book ,\"-d\"means sort by ISBN ascending order,\"-w\"means sort by heading dictionary order ");
System.out.println("search words -d/-w without keywords will show all the book in the lib");
System.out.println("\"help\" to get help ");
System.out.println("\"exit\" to exit this count ");
System.out.println("\"quit\" to quit this program ");
System.out.println("\"addbook\" ");
System.out.println("\"deletbook isbn\"");
System.out.println("\"searchuser userid\"");
System.out.println("\"searchorgan organid\" ");
System.out.println("\"addorgan\"");
}
boolean addtime(){
now.add(Calendar.DATE, 10);
showtime(now);
return true;
}
boolean borrowbook(String username){
int res;
if((modification.equals(null)||!ISBN.pubcheckisbn(modification))){
System.out.println("ISBN WRONG"); return false;}
if(modification2.equals("-t"))res=testUser.userTreeMap.get(username).borrowBook(modification,buaa,now);
else res=testUser.userTreeMap.get(username).borrowBook(modification,buaa,now=Calendar.getInstance());
Date tasktime=testUser.userTreeMap.get(username).noBorrow.getTime();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(res==1){System.out.println("borrow book successfully!");return true;}
else if(res==0)System.out.println("If any books are not returned, please return them and borrow them again.");
else if(res==2)System.out.println("You are forbidden to borrow books until "+df.format(tasktime));
else if(res==3)System.out.println("You have borrowed four books, which is the maximum number.");
else if(res==4)System.out.println("All the books have been lent out.");
return false;
}
boolean renewbook(String username){
User user1=testUser.userTreeMap.get(username);
int res;
if((modification.equals(null)||!ISBN.pubcheckisbn(modification))){
System.out.println("ISBN WRONG"); return false;}
if(modification2.equals("-t"))res=testUser.userTreeMap.get(username).renew(modification,now);
else res=testUser.userTreeMap.get(username).renew(modification,now=Calendar.getInstance());
if(res==1){System.out.println("Successful renewal of books");return true;}
else if(res==0)System.out.println("If any books are not returned, please return them and borrow them again.");
else if(res==2)System.out.println("You are forbidden to borrow books until"+testUser.userTreeMap.get(username).noBorrow.toString());
else if(res==3)System.out.println("It can only be renewed once.");
else if(res==4)System.out.println("It can be renewed only three days before it expires.");
return false;
}
boolean showmybook(String username, Library lib){
User user1=testUser.userTreeMap.get(username);
user1.checkRent(now);
System.out.println("The books you borrowed:"+user1.normalRent.size());
showmyrentbook(username,user1.normalRent,lib);
System.out.println("Books you have returned:"+user1.returnRent.size());
showmyrentbook(username,user1.returnRent,lib);
System.out.println("Books you've overdue:"+user1.unreturnedRent.size());
showmyrentbook(username,user1.unreturnedRent,lib);
return true;
}
boolean showmyrentbook(String username,Map<String,borrowList> Rent, Library lib){
User user1=testUser.userTreeMap.get(username);
int size=Rent.size();
for(String key : Rent.keySet())
{System.out.print(key+ " "+lib.getBookByIsbn(key).getTitle()+" "+showtime(Rent.get(key).returntime));
System.out.print(" returntime:");showtime(Rent.get(key).returntime);}
return true;
}
boolean returnBook(String username){
User user1=testUser.userTreeMap.get(username);
if((modification.equals(null)||!ISBN.pubcheckisbn(modification))){
System.out.println("ISBN WRONG"); return false;}
int res;
if(modification2.equals("-t"))res=testUser.userTreeMap.get(username).returnbook(modification,buaa,now);
else res=testUser.userTreeMap.get(username).returnbook(modification,buaa,now=Calendar.getInstance());
if(res==1){System.out.println("Successful returned a book");return true;}
else if(res==0)System.out.println("If any books are not returned, please return them and borrow them again.");// TODO: 2019/5/11 outofisbn
return false;
}
void savebook(){
StringBuilder book=new StringBuilder();
for(String key: buaa.libraryMap.keySet()){
Book temp=buaa.libraryMap.get(key);
book.append(temp.getTitle());
book.append(",");
book.append(temp.code.isbn);
book.append(",");
book.append(temp.getAuthor());
book.append(",");
book.append(temp.getPrice());
book.append(",");
book.append(temp.getRest());
book.append(",");
book.append(temp.getTotal());
book.append("\n");
}
book.setLength(book.length() - 1);
File file = new File("src/inputbook.txt");
try (OutputStream os = new FileOutputStream(file)) {
String book2=book.toString();
byte[] data = book2.getBytes();
os.write(data);
System.out.println("bookmessage successfully saved");
} catch (Exception e) {
e.printStackTrace();
}
}
void saveuser(){
StringBuilder us=new StringBuilder();
for(String key: testUser.userTreeMap.keySet()){
User temp=testUser.userTreeMap.get(key);
us.append(temp.getName());
us.append(",");
us.append(temp.getPassword());
us.append(",");
us.append(temp.level.toString());
us.append(",");
us.append(temp.noBorrow.get(Calendar.YEAR));
us.append(",");
us.append(temp.noBorrow.get(Calendar.MONTH));
us.append(",");
us.append(temp.noBorrow.get(Calendar.DATE));
us.append(",");
us.append(temp.noBorrow.get(Calendar.HOUR));
us.append(",");
us.append(temp.noBorrow.get(Calendar.MINUTE));
us.append(",");
us.append(temp.noBorrow.get(Calendar.SECOND));
us.append("\r\n");
}
us.setLength(us.length() - 1);
File file = new File("src/inputuser.txt");
try (OutputStream os = new FileOutputStream(file)) {
String us2=us.toString();
byte[] data = us2.getBytes();
os.write(data);
System.out.println("usermessage successfully saved");
} catch (Exception e) {
e.printStackTrace();
}
}
void saveborrow(){
StringBuilder us=new StringBuilder();
for(String key: testUser.userTreeMap.keySet()){
for(String key2:testUser.userTreeMap.get(key).normalRent.keySet())
{borrowList temp=testUser.userTreeMap.get(key).normalRent.get(key2);
us.append(temp.isbn);
us.append(",");
us.append(temp.name);
us.append(",");
us.append(key);
us.append(",");
us.append("normal");
us.append(",");
us.append(temp.borrowtime.get(Calendar.YEAR));
us.append(",");
us.append(temp.borrowtime.get(Calendar.MONTH));
us.append(",");
us.append(temp.borrowtime.get(Calendar.DATE));
us.append(",");
us.append(temp.borrowtime.get(Calendar.HOUR));
us.append(",");
us.append(temp.borrowtime.get(Calendar.MINUTE));
us.append(",");
us.append(temp.borrowtime.get(Calendar.SECOND));
us.append(",");
us.append(temp.returntime.get(Calendar.YEAR));
us.append(",");
us.append(temp.returntime.get(Calendar.MONTH));
us.append(",");
us.append(temp.returntime.get(Calendar.DATE));
us.append(",");
us.append(temp.returntime.get(Calendar.HOUR));
us.append(",");
us.append(temp.returntime.get(Calendar.MINUTE));
us.append(",");
us.append(temp.returntime.get(Calendar.SECOND));
us.append("\r\n");}
}
for(String key: testUser.userTreeMap.keySet()){
for(String key2:testUser.userTreeMap.get(key).returnRent.keySet())
{borrowList temp=testUser.userTreeMap.get(key).returnRent.get(key2);
us.append(temp.isbn);
us.append(",");
us.append(temp.name);
us.append(",");
us.append(testUser.userTreeMap.get(key).getName());
us.append(",");
us.append("returned");
us.append(",");
us.append(temp.borrowtime.get(Calendar.YEAR));
us.append(",");
us.append(temp.borrowtime.get(Calendar.MONTH));
us.append(",");
us.append(temp.borrowtime.get(Calendar.DATE));
us.append(",");
us.append(temp.borrowtime.get(Calendar.HOUR));
us.append(",");
us.append(temp.borrowtime.get(Calendar.MINUTE));
us.append(",");
us.append(temp.borrowtime.get(Calendar.SECOND));
us.append(",");
us.append(temp.returntime.get(Calendar.YEAR));
us.append(",");
us.append(temp.returntime.get(Calendar.MONTH));
us.append(",");
us.append(temp.returntime.get(Calendar.DATE));
us.append(",");
us.append(temp.returntime.get(Calendar.HOUR));
us.append(",");
us.append(temp.returntime.get(Calendar.MINUTE));
us.append(",");
us.append(temp.returntime.get(Calendar.SECOND));
us.append("\r\n");}
}
for(String key: testUser.userTreeMap.keySet()){
for(String key2:testUser.userTreeMap.get(key).unreturnedRent.keySet())
{borrowList temp=testUser.userTreeMap.get(key).unreturnedRent.get(key2);
us.append(temp.isbn);
us.append(",");
us.append(temp.name);
us.append(",");
us.append(testUser.userTreeMap.get(key).getName());
us.append(",");
us.append("unreturned");
us.append(",");
us.append(temp.borrowtime.get(Calendar.YEAR));
us.append(",");
us.append(temp.borrowtime.get(Calendar.MONTH));
us.append(",");
us.append(temp.borrowtime.get(Calendar.DATE));
us.append(",");
us.append(temp.borrowtime.get(Calendar.HOUR));
us.append(",");
us.append(temp.borrowtime.get(Calendar.MINUTE));
us.append(",");
us.append(temp.borrowtime.get(Calendar.SECOND));
us.append(",");
us.append(temp.returntime.get(Calendar.YEAR));
us.append(",");
us.append(temp.returntime.get(Calendar.MONTH));
us.append(",");
us.append(temp.returntime.get(Calendar.DATE));
us.append(",");
us.append(temp.returntime.get(Calendar.HOUR));
us.append(",");
us.append(temp.returntime.get(Calendar.MINUTE));
us.append(",");
us.append(temp.returntime.get(Calendar.SECOND));
us.append("\r\n");}
}
us.setLength(us.length() - 1);
File file = new File("src/borrow.txt");
try (OutputStream os = new FileOutputStream(file)) {
String us2=us.toString();
byte[] data = us2.getBytes();
os.write(data);
System.out.println("borrowmessage successfully saved");
} catch (Exception e) {
e.printStackTrace();
}
}
boolean borrowlist(){
if((modification.equals(null)||testUser.userTreeMap.get(modification)==null)){
System.out.println("the userid wrong"); return false;}
else showmybook(modification,buaa);
return true;
}
boolean reducenoborrow(){
if((modification.equals(null)||testUser.userTreeMap.get(modification)==null)){
System.out.println("the userid wrong"); return false;}
else
{testUser.userTreeMap.get(modification).noBorrow.add(Calendar.MONTH,-1);
System.out.println("Prohibition of borrowing time has been reduced by one month"); return false;}
}
}
class Library {
TreeMap<String, Book> libraryMap;
public Library() {
libraryMap = new TreeMap<String, Book>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2); //升序排列
}
});
}
public boolean addBook(Book addbook) {
if (libraryMap.containsKey(addbook.code.isbn))
{System.out.println("图书已经包含,将更新其信息");return false;}
if (!addbook.code.checkisbn()) {
System.out.println("isbn信息错误,请更正");
return false;
}
if (addbook.getPrice() < 0 || addbook.getRest() < 0) {
System.out.println("价格或数量信息错误,请更正");
return false;
}
libraryMap.put(addbook.code.isbn, addbook);
return true;
}
public Book getBookByIsbn(String isbn) {
final Book book = libraryMap.get(isbn);
return book;
}
public boolean changeBook(String isbn, String isbn2, String title, String author, String price, int total,
int rest) {
BigDecimal newprice = new BigDecimal(price);
if (libraryMap.containsKey(isbn))
System.out.println("图书已经包含,将更新其信息");
else {
System.out.println("图书信息未包含,请确认isbn代码");
//return false;
}
if (!ISBN.pubcheckisbn(isbn2)) {
System.out.println("isbn错误");
return false;
}
if(libraryMap.containsKey(isbn2)) {
System.out.println("更正的isbn信息已存在,无法操作,若错在isbn错填,请删除错填isbn的书目项重新录入");
return false;}
if (newprice.doubleValue() < 0 || rest < 0) {
System.out.println("价格或数量信息错误,请更正");
return false;
}
this.deleteBook(isbn);
Book temp = new Book(isbn2, title, author, price, total, rest);
libraryMap.put(temp.code.isbn, temp);
System.out.println("successfully alter");
return true;
}
public boolean deleteBook(String isbn) {
libraryMap.remove(isbn);
return true;
}
public List<Book> getBooksByKeyword(String keyword) {
List<Book> matchbook = new ArrayList<>();
for (Map.Entry<String, Book> entry : libraryMap.entrySet()) {
if (entry.getValue().getTitle().indexOf(keyword) > -1) matchbook.add(entry.getValue());
}
return matchbook;
}
}
class ISBN {
/**
*
*/
private static final int _12 = 12;
String isbn;
ISBN(String isbn) {
this.isbn = isbn;
}
void setISBN(String isbn) {
this.isbn = isbn;
}
ISBN() {
}
boolean checkisbn() {
String isbn2 = isbn;
if (isbn2.length() != 13 && isbn2.length() != 10)
return false;
if (isbn2.length() == 10) {
return checkisbn10(isbn2);
}
if (isbn2.length() == 13) {
return checkisbn13(isbn2);
}
return false;
}
public static boolean pubcheckisbn(String isbn2) {
if (isbn2.length() != 13 && isbn2.length() != 10)
return false;
if (isbn2.length() == 10) {
return checkisbn10(isbn2);
}
if (isbn2.length() == 13) {
return checkisbn13(isbn2);
}
return false;
}
static boolean checkisbn10(String isbn) {
String isbn2 = isbn;
int sum = 0;
for (var i = 0; i < 9; i++) {
sum += (int) (isbn2.charAt(i) - '0') * (11 - i);
}
if (isbn2.charAt(9) == 'X')
sum += 10;
else
sum += isbn2.charAt(9) - '0';
if (sum % 11 != 0)
return false;
return true;
}
static boolean checkisbn13(String isbn) {
String isbn2 = isbn;
if (isbn2.substring(0, 3).equals("978") && isbn2.substring(0, 3).equals("979"))
return false;
else if (isbn2.charAt(12) == 'X')
return false;
int sum = 0;
for (var i = 0; i < 13; i++) {
if (i % 2 == 0)
sum += (int) (isbn2.charAt(i) - '0') * 1;
else
sum += (int) (isbn2.charAt(i) - '0') * 3;
}
if (sum % 10 != 0)
return false;
return true;
}
String toString(String code) {
String output = code;
if (code.length() == 10)
output = String.format("%s-%s", code.substring(0, 9), code.substring(9));
if (code.length() == 13)
output = String.format("%s-%s-%s", code.substring(0, 3), code.substring(2, 12), code.substring(12));
return output;
}
}
class Book {
ISBN code;
private String title;
private String author;
private BigDecimal price;//= new BigDecimal("2.111");
private int total;
private int rest;
Book(String code, String title, String author, String price, int rest, int total) {
this.code = new ISBN(code);
this.title = title;
this.author = author;
this.price = new BigDecimal(price);
this.total = total;
this.rest = rest;
}
ISBN getCode() {
return code;
}
void setCode(String code) {
this.code.isbn = code;
}
String getTitle() {
return title;
}
void setTitle(String title) {
this.title = title;
}
String getAuthor() {
return author;
}
void setAuthor(String author) {
this.author = author;
}
double getPrice() {
return price.doubleValue();
}
void setPrice(String price) {
BigDecimal newprice = new BigDecimal(price);
this.price = newprice;
}
int getTotal() {
return total;
}
void setTotal(int total) {
this.total = total;
}
int getRest() {
return rest;
}
void setRest(int rest) {
this.rest = rest;
}
void print() {
System.out.println("ISBN:" + this.code.isbn);
System.out.println("author:" + author);
System.out.println("title:" + title);
System.out.println("price:" + (double) price.doubleValue());
System.out.println("total:" + total);
System.out.println("rest:" + rest);
}
}<file_sep>/README.md
# Library
This project is an object-oriented programming job. This is console java application, run librarytest.java in terminal,if you need any help
,input 'help' to get more information.
<file_sep>/Librarytest/src/borrowList.java
import java.util.Calendar;
public class borrowList {
String isbn;
String name;
Calendar borrowtime;
Calendar returntime;
int renewtimes=0;
borrowList(String isbn,String name){
borrowtime=Calendar.getInstance();
this.name=name;
returntime=Calendar.getInstance();
returntime.add(Calendar.DATE,30);
this.isbn=isbn;
}
borrowList(String isbn,String name,String year,String mouth,String day,String hour,String min,String sec,String year1,String mouth1,String day1,String hour1,String min1,String sec1){
borrowtime=Calendar.getInstance();
this.name=name;
returntime=Calendar.getInstance();
returntime.add(Calendar.DATE,30);
this.isbn=isbn;
borrowtime.set(Calendar.YEAR,Integer.parseInt(year.trim()));
borrowtime.set(Calendar.MONTH,Integer.parseInt(mouth.trim()));
borrowtime.set(Calendar.DATE,Integer.parseInt(day.trim()));
borrowtime.set(Calendar.HOUR,Integer.parseInt(hour.trim()));
borrowtime.set(Calendar.MINUTE,Integer.parseInt(min.trim()));
borrowtime.set(Calendar.SECOND,Integer.parseInt(sec.trim()));
returntime.set(Calendar.YEAR,Integer.parseInt(year1.trim()));
returntime.set(Calendar.MONTH,Integer.parseInt(mouth1.trim()));
returntime.set(Calendar.DATE,Integer.parseInt(day1.trim()));
returntime.set(Calendar.HOUR,Integer.parseInt(hour1.trim()));
returntime.set(Calendar.MINUTE,Integer.parseInt(min1.trim()));
returntime.set(Calendar.SECOND,Integer.parseInt(sec1.trim()));
}
int renew(Calendar now){
long t1 = returntime.getTimeInMillis();
long t2 = now.getTimeInMillis();
long days = (t2 - t1)/(24 * 60 * 60 * 1000);
if (renewtimes!=0) return 3;
if(days>=3||days<0)return 4;
else {returntime.add(Calendar.DATE,14);renewtimes++; return 1;}
}
}
| 420f64d1c5da3aba8bf7e7dd006928f267d21547 | [
"Markdown",
"Java"
]
| 3 | Java | kiaia/Library | 6683587916734e3593e9cf49b78b9e71e837d041 | 1f6f4006a7ba712b2c8de9a9b8736b5d89e0bc96 |
refs/heads/master | <file_sep>require('total.js/debug')();<file_sep>exports.install = function() {
ROUTE('/', getMethod);
};
function getMethod() {
var self = this;
return self.view('index');
}<file_sep>require('total.js').http('test');<file_sep>exports.install = function() {
F.websocket('/', reader, ['json']);
};
function reader() {
var self = this;
self.on('message', function(client, message) {
switch (message.url) {
default:
client.send({ status: 404 });
break;
}
});
}<file_sep>require('total.js').http('release');
// require('total.js').cluster.http(2, 'release');<file_sep>import React, { useContext, useEffect } from "react";
import {State, Dispatch} from './Context';
export function Home() {
const dispatch = useContext(Dispatch);
const state = useContext(State);
useEffect(() => {
// async data fetching function
var myHeaders = new Headers();
myHeaders.append('Accept', 'application/json');
const fetchQuotes = async () => {
const response = await fetch(`/api/v1/items`, {headers: myHeaders});
const json = await response.json();
dispatch({
type: 'pays',
content: json
});
};
fetchQuotes();
}, []);
let pays = [];
if (state.pays){
state.pays.map((item) => {
pays.push(<div key={item.id}>{JSON.stringify(item)}</div>);
});
}else{
pays = (<div>loading...</div>);
}
return (
<div>{pays}</div>
);
}
<file_sep>[![MIT License][license-image]][license-url]
# Total.js + React Template
Full stack template with [react](reactjs.org) and [totaljs framework](totaljs.com)
## Installation
``` bash
npm install (or yarn install)
```
## Usage
Template simulate async request on the server.
Download two items from the NOSQL totaljs DB and show these items as json.
The react client is located in the `client` directory.
The API definition is in the `controllers`.
## Start
### Run in development mode
```bash
npm run dev
```
This will start all the server and webpack for hot-reloaded UI.
Open http://localhost:8080/ in the browser.
### Run in production mode
```bash
npm run build
npm run start
```
This will pack UI with rollup and start production server.
Open http://localhost:8000/ in the browser.
## License
The source-code is under __MIT license__.
[license-image]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat
[license-url]: license.txt
<file_sep>import React from "react";
export const Dispatch = React.createContext(null);
export const State = React.createContext(null);<file_sep>import React, { useReducer } from "react";
import {State, Dispatch} from './Context';
import {Home} from './Home';
// State Reducer
const initialState = {pays: []};
function reducer(state, action) {
switch (action.type) {
case 'pays':
return {pays: action.content};
// case 'increment':
// return {count: state.count + 1};
// case 'decrement':
// return {count: state.count - 1};
default:
throw new Error();
}
}
// Main App
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<Dispatch.Provider value={dispatch}>
<State.Provider value={state}>
<Home></Home>
</State.Provider>
</Dispatch.Provider>
);
};
export default App; | 5f9a211da20eca92fb41bad8696daa66d6856545 | [
"JavaScript",
"Markdown"
]
| 9 | JavaScript | vasekd/totaljs_react_teamplate | 1d7cd413957b318a68d9faee4e69386ddf4c0cf0 | 513f1b9bb7786a1a7362fbe4b035148db028ffa9 |
refs/heads/master | <file_sep>addEventHandler("onClientResourceStart", getRootElement(),
function ()
bindKey("F2", "down", VisibleWindow)
end
)
function dxDrawArea(posX, posY, posW, posH, color)
dxDrawRectangle(posX, posY, posW, posH, color)
dxDrawLine(posX , posY , posX+posW, posY , tocolor( 255, 255, 255))
dxDrawLine(posX , posY , posX , posY+posH, tocolor( 255, 255, 255))
dxDrawLine(posX , posY+posH , posX+posW, posY+posH, tocolor( 255, 255, 255))
dxDrawLine(posX+posW, posY , posX+posW, posY+posH, tocolor( 255, 255, 255))
end
function isMouseInPosition ( x, y, width, height )
if ( not isCursorShowing( ) ) then
return false
end
local sx, sy = guiGetScreenSize ( )
local cx, cy = getCursorPosition ( )
local cx, cy = ( cx * sx ), ( cy * sy )
if ( cx >= x and cx <= x + width ) and ( cy >= y and cy <= y + height ) then
return true
else
return false
end
end<file_sep>local sW,sH = guiGetScreenSize()
local img = dxCreateTexture("logo.png")
local switch = false
local w = 370
local h = 105
local m = 5
local x = math.random(0,sW/2- w)
local y = math.random(0,sH - h)
local x1 = math.random(sW/2,sW - w)
local y1 = math.random(0,sH - h)
addEventHandler("onClientResourceStart", getRootElement(),
function ()
bindKey("F3", "down", VisibleIdleScreen)
end
)
function VisibleIdleScreen()
if switch == false then
switch = true
showChat(false)
setPlayerHudComponentVisible( "all", false)
addEventHandler ("onClientRender", getRootElement(), Draw )
addEventHandler ("onClientRender", getRootElement(), dxIdleScreen1 )
addEventHandler ("onClientRender", getRootElement(), dxIdleScreen2 )
x = math.random(0,sW/2- w)
x1 = math.random(sW/2,sW - w)
y = math.random(0,sH - h)
y1 = math.random(0,sH - h)
color = tocolor(math.random(0,255),math.random(0,255),math.random(0,255),255)
color1 = tocolor(math.random(0,255),math.random(0,255),math.random(0,255),255)
else
switch = false
showChat(true)
setPlayerHudComponentVisible( "all", true)
removeEventHandler("onClientRender", getRootElement(), Draw )
removeEventHandler("onClientRender", getRootElement(), dxIdleScreen1)
removeEventHandler("onClientRender", getRootElement(), dxIdleScreen2)
end
end
function dxIdleScreen1()
if (x <= 0) or (x >= (sW/2) - w) then
V = change(V)
color = tocolor(math.random(0,255),math.random(0,255),math.random(0,255),255)
end
if (y <= 0) or (y >= sH - h) then
H = change(H)
color = tocolor(math.random(0,255),math.random(0,255),math.random(0,255),255)
end
x = x + incDec(V)
y = y + incDec(H)
dxDrawImage( x, y, w, h, img, 0, 0, 0,color)
end
function dxIdleScreen2()
if (x1 <= sW/2) or (x1 >= sW - w) then
V1 = change(V1)
color1 = tocolor(math.random(0,255),math.random(0,255),math.random(0,255),255)
end
if (y1 <= 0) or (y1 >= sH - h) then
H1 = change(H1)
color1 = tocolor(math.random(0,255),math.random(0,255),math.random(0,255),255)
end
x1 = x1 + incDec(V1)
y1 = y1 + incDec(H1)
dxDrawImage( x1, y1, w, h, img, 0, 0, 0,color1)
end
function change( param )
if param == true then
return false
else
return true
end
end
function incDec( param )
if param == true then
return m
else
return -m
end
end
function Draw()
dxDrawRectangle(0,0,sW,sH,tocolor(0,0,0,220))
end<file_sep>local sW,sH = guiGetScreenSize()
local switch = false
local choice, page, player
local players = {{},{},{}}
local name, surname, address
local selEditBox = 'none'
local editBoxes = {
['name'] = '',
['surname'] = '',
['address'] = '',
['page'] = '',
}
addEventHandler("onClientResourceStart", getRootElement(),
function ()
bindKey("mouse_wheel_up", "down", scrollBase)
bindKey("mouse_wheel_down", "down", scrollBase)
end
)
function scrollBase( button, state)
if state == "down" then
if button == "mouse_wheel_up" and page ~= 0 then
if page > 0 then
page = page - 1
end
end
if button == "mouse_wheel_down" and players[1][35]~="" and players[2][35]~="" and players[3][35]~="" then
page = page + 1
end
triggerServerEvent("onReadPlayer", getRootElement())
players[1][35] = ""
players[2][35] = ""
players[3][35] = ""
end
end
function BDMassive( id, name, surname, address)
if page < tonumber(id) then
players[1][tonumber(id) - page] = name
players[2][tonumber(id) - page] = surname
players[3][tonumber(id) - page] = address
end
end
function VisibleWindow()
if switch == false then
switch = true
page = 0
triggerServerEvent("onReadPlayer", getRootElement())
addEventHandler("onClientRender", getRootElement(), dxDrawWindow )
addEventHandler("onClientClick" , getRootElement(), dxClickWindow )
showCursor(true)
showChat(false)
setPlayerHudComponentVisible( "all", false )
else
switch = false
removeEventHandler("onClientRender", getRootElement(), dxDrawWindow )
removeEventHandler("onClientRender", getRootElement(), dxDrawDelete )
removeEventHandler("onClientRender", getRootElement(), dxDrawMenu )
removeEventHandler("onClientClick" , getRootElement(), dxClickWindow )
removeEventHandler("onClientClick" , getRootElement(), dxClickMenu )
showCursor(false)
showChat(true)
setPlayerHudComponentVisible( "all", true)
end
end
function dxClickWindow(button, state)
if isMouseInPosition((sW / 2) - 380, (sH / 2) - 260, 767, 544) and (state == "down") then
addEventHandler( 'onClientKey', getRootElement(), lockKeysEditBox )
addEventHandler( 'onClientCharacter', getRootElement(), forEditBoxes )
addEventHandler( 'onClientClick', getRootElement(), clickEditBox )
addEventHandler("onClientRender", getRootElement(), dxDrawMenu )
addEventHandler("onClientClick" , getRootElement(), dxClickMenu )
if (button == "middle") then
choice = 1
editBoxes.name = ""
editBoxes.surname = ""
editBoxes.address = ""
addEventHandler( 'onClientRender', getRootElement(), dxEditBox )
end
if (button == "left") then
choice = 2
editBoxes.name = players[1][player]
editBoxes.surname = players[2][player]
editBoxes.address = players[3][player]
addEventHandler( 'onClientRender', getRootElement(), dxEditBox )
end
if (button == "right") then
choice = 3
end
removeEventHandler("onClientRender", getRootElement(), dxDrawWindow )
removeEventHandler("onClientClick" , getRootElement(), dxClickWindow)
end
end
function dxDrawWindow()
dxDrawArea((sW / 2) - 400, (sH / 2) - 300, 800, 600, tocolor(0,0,0,200))
dxDrawArea((sW / 2) - 383, (sH / 2) - 284, 767, 568, tocolor(0,0,0,255))
dxDrawLine((sW / 2) - 375, (sH / 2) - 260, (sW / 2) + 375, (sH / 2) - 260, tocolor( 255, 255, 255))
dxDrawLine((sW / 2) - 267, (sH / 2) - 278, (sW / 2) - 267, (sH / 2) + 278, tocolor( 255, 255, 255))
dxDrawLine((sW / 2) - 117, (sH / 2) - 278, (sW / 2) - 117, (sH / 2) + 278, tocolor( 255, 255, 255))
dxDrawText(" Прокрутка страницы на колесико мыши!", (sW / 2) - 400, (sH / 2) - 300, 800, 14, tocolor( 255, 255, 0, 255 ), 1.02, "default" )
dxDrawText("Имя", (sW / 2) - 375, (sH / 2) - 276, sW, sH, tocolor( 255, 255, 255, 255 ), 1.02, "default" )
dxDrawText("Фамилия", (sW / 2) - 260, (sH / 2) - 276, sW, sH, tocolor( 255, 255, 255, 255 ), 1.02, "default" )
dxDrawText("Адрес", (sW / 2) - 110, (sH / 2) - 276, sW, sH, tocolor( 255, 255, 255, 255 ), 1.02, "default" )
dxDrawText(" ЛКМ - Изменить СКМ - Создать ПКМ - Удалить", (sW / 2) - 400, (sH / 2) + 286, sW, 14, tocolor( 255, 255, 0, 255 ), 1.02, "default" )
for i = 1,34,1 do
if isMouseInPosition((sW / 2) - 380, (sH / 2) - 276 + (16 * i), 767, 16) then
dxDrawRectangle ((sW / 2) - 380, (sH / 2) - 276 + (16 * i), 760, 16, tocolor(255,255,255,120))
player = i + page
end
dxDrawText(players[1][i], (sW / 2) - 375, (sH / 2) - 276 + (16 * i), (sW / 2) - 270, (sH / 2) - 260 + (16 * i), tocolor( 255, 255, 255, 255 ), 1.02, "default", "left", "top", true)
dxDrawText(players[2][i], (sW / 2) - 260, (sH / 2) - 276 + (16 * i), (sW / 2) - 120, (sH / 2) - 260 + (16 * i), tocolor( 255, 255, 255, 255 ), 1.02, "default", "left", "top", true )
dxDrawText(players[3][i], (sW / 2) - 110, (sH / 2) - 276 + (16 * i), (sW / 2) + 380, (sH / 2) - 260 + (16 * i), tocolor( 255, 255, 255, 255 ), 1.02, "default", "left", "top", true )
end
end
function dxDrawMenu()
if choice == 3 then
dxDrawArea((sW / 2) - 210, (sH / 2) - 75, 420, 150, tocolor(0,0,0,200))
dxDrawArea((sW / 2) - 194, (sH / 2) - 61, 388, 122, tocolor(0,0,0,255))
else
dxDrawArea((sW / 2) - 400, (sH / 2) - 75, 800, 150, tocolor(0,0,0,200))
dxDrawArea((sW / 2) - 383, (sH / 2) - 61, 767, 122, tocolor(0,0,0,255))
dxDrawLine((sW / 2) - 383, (sH / 2) - 43, (sW / 2) + 383, (sH / 2) - 43, tocolor( 255, 255, 255))
dxDrawText("Имя", (sW / 2) - 375, (sH / 2) - 40, sW, sH, tocolor( 255, 255, 255, 255 ), 1.02, "default" )
dxDrawText("Фамилия", (sW / 2) - 375, (sH / 2) - 20, sW, sH, tocolor( 255, 255, 255, 255 ), 1.02, "default" )
dxDrawText("Адрес", (sW / 2) - 375, (sH / 2), sW, sH, tocolor( 255, 255, 255, 255 ), 1.02, "default" )
dxDrawRectangle((sW / 2) - 300, (sH / 2) - 39, 673, 14, tocolor(255,255,255,255))
dxDrawRectangle((sW / 2) - 300, (sH / 2) - 19, 673, 14, tocolor(255,255,255,255))
dxDrawRectangle((sW / 2) - 300, (sH / 2) + 1, 673, 14, tocolor(255,255,255,255))
end
dxDrawArea((sW / 2) - 180, (sH / 2) + 20, 170, 35,tocolor(0,0,0,255))
dxDrawArea((sW / 2) + 10, (sH / 2) + 20, 170, 35,tocolor(0,0,0,255))
if isMouseInPosition((sW / 2) - 180, (sH / 2) + 20, 170, 35) then
dxDrawRectangle ((sW / 2) - 180, (sH / 2) + 20, 170, 35, tocolor(255,255,255,120))
elseif isMouseInPosition((sW / 2) + 10, (sH / 2) + 20, 170, 35) then
dxDrawRectangle ((sW / 2) + 10, (sH / 2) + 20, 170, 35, tocolor(255,255,255,120))
end
if choice == 1 then
dxDrawText("Окно создания пользователя", (sW / 2) - 75, (sH / 2) - 58, sW, sH, tocolor( 255, 255, 255, 255 ), 1.02, "default" )
dxDrawText("Создать" , (sW / 2) - 115, (sH / 2) + 30, sW, sH, tocolor( 0, 255, 0, 255 ), 1.02, "default" )
end
if choice == 2 then
dxDrawText("Окно редактирования пользователя", (sW / 2) - 100, (sH / 2) - 58, sW, sH, tocolor( 255, 255, 255, 255 ), 1.02, "default" )
dxDrawText("Изменить", (sW / 2) - 120, (sH / 2) + 30, sW, sH, tocolor( 0, 255, 0, 255 ), 1.02, "default" )
end
if choice == 3 then
dxDrawText("Удалить?", (sW / 2) - 75, (sH / 2) - 40, sW, sH, tocolor( 255, 255, 255, 255 ), 3, "default" )
dxDrawText("Подтвердить", (sW / 2) - 135, (sH / 2) + 30, sW, sH, tocolor( 0, 255, 0, 255 ), 1.02, "default" )
else
dxDrawText( editBoxes['name'] , (sW / 2) - 297, (sH / 2) - 39, (sW / 2) - 297 + 665, (sH / 2) - 23, tocolor( 0,0,0 ), 1.02, "default", "left", "top", true )
dxDrawText( editBoxes['surname'], (sW / 2) - 297, (sH / 2) - 19, (sW / 2) - 297 + 665, (sH / 2) - 3, tocolor( 0,0,0 ), 1.02, "default", "left", "top", true )
dxDrawText( editBoxes['address'], (sW / 2) - 297, (sH / 2) + 1, (sW / 2) - 297 + 665, (sH / 2) + 17, tocolor( 0,0,0 ), 1.02, "default", "left", "top", true )
end
dxDrawText("Отменить", (sW / 2) + 70, (sH / 2) + 30, sW, sH, tocolor( 255, 0, 0, 255 ), 1.02, "default" )
end
function dxClickMenu(button, state)
if (button == "left") and (state == "down") and (isMouseInPosition((sW / 2) - 180, (sH / 2) + 20, 170, 35) or isMouseInPosition((sW / 2) + 10, (sH / 2) + 20, 170, 35)) then
removeEventHandler("onClientRender", getRootElement(), dxDrawMenu )
removeEventHandler("onClientClick" , getRootElement(), dxClickMenu )
if (choice == 1) and isMouseInPosition((sW / 2) - 180, (sH / 2) + 20, 170, 35) then
triggerServerEvent("onCreatePlayer", getRootElement() , editBoxes['name'], editBoxes['surname'], editBoxes['address'] )
elseif (choice == 2) and isMouseInPosition((sW / 2) - 180, (sH / 2) + 20, 170, 35) then
triggerServerEvent("onUpdatePlayer", getRootElement() , editBoxes['name'], editBoxes['surname'], editBoxes['address'], player)
elseif (choice == 3) and isMouseInPosition((sW / 2) - 180, (sH / 2) + 20, 170, 35) then
triggerServerEvent("onDeletePlayer", getRootElement() , player )
end
for i = 1,3,1 do for j = 1,34,1 do players[i][j]="" end end
triggerServerEvent("onReadPlayer", getRootElement() )
removeEventHandler( 'onClientKey', getRootElement(), lockKeysEditBox )
removeEventHandler( 'onClientCharacter', getRootElement(), forEditBoxes)
removeEventHandler( 'onClientClick', getRootElement(), clickEditBox )
removeEventHandler( 'onClientRender', getRootElement(), dxEditBox )
addEventHandler("onClientRender" , getRootElement(), dxDrawWindow )
addEventHandler("onClientClick" , getRootElement(), dxClickWindow )
end
end
function dxEditBox ()
if selEditBox == 'name' then
dxDrawLine((sW / 2) - 300, (sH / 2) - 25, (sW / 2) + 373, (sH / 2) - 25, tocolor( 255,0,0,255 ))
elseif selEditBox == 'surname' then
dxDrawLine((sW / 2) - 300, (sH / 2) - 5, (sW / 2) + 373, (sH / 2) - 5, tocolor( 255,0,0,255 ))
elseif selEditBox == 'address' then
dxDrawLine((sW / 2) - 300, (sH / 2) + 15, (sW / 2) + 373, (sH / 2) + 15, tocolor( 255,0,0,255 ))
end
end
function clickEditBox ( button, state )
if state == 'down' then return end
if isMouseInPosition ( (sW / 2) - 300, (sH / 2) - 39, 673, 14 ) then
selEditBox = 'name'
elseif isMouseInPosition ( (sW / 2) - 300, (sH / 2) - 19, 673, 14 ) then
selEditBox = 'surname'
elseif isMouseInPosition ( (sW / 2) - 300, (sH / 2) + 1, 673, 14 ) then
selEditBox = 'address'
end
end
function forEditBoxes ( c )
if selEditBox ~= 'none' then
if utf8.len(editBoxes[selEditBox]) < 82 then
editBoxes[selEditBox] = editBoxes[selEditBox] .. c
print( editBoxes[selEditBox] )
end
end
end
function lockKeysEditBox ( button, press )
if button == 'backspace' and press then
if selEditBox ~= 'none' then
editBoxes[selEditBox] = utf8.sub(editBoxes[selEditBox], 1,utf8.len(editBoxes[selEditBox])-1)
print( editBoxes[selEditBox] )
end
else
cancelEvent()
end
end
addEvent("onBDMassive", true )
addEventHandler("onBDMassive", getRootElement(), BDMassive )<file_sep>dbSQL = dbConnect( "mysql", "host=db4free.net;port=3306;dbname=mta_players", "deadlineexe", "exeenildaed" )
function connectBaseSQL()
if (not dbSQL) then
outputDebugString("Ошибка: Соединение с БД не установлено!")
else
outputDebugString("Успешно: Соединение с БД установлено!")
triggerEvent("onAutoIndex", getRootElement())
end
end
function indexPlayerSQL()
dbExec ( dbSQL,
[[UPDATE players
SET id = (SELECT @a:= @a + 1 FROM (SELECT @a:= 0) as id)
ORDER BY id
]]
)
end
function createPlayerSQL( name, surname, address)
dbExec ( dbSQL,
[[INSERT
INTO players ( name, surname, address )
VALUES ( ?, ?, ? );
]]
, name, surname, address )
triggerEvent("onAutoIndex", getRootElement())
end
function readPlayerSQL()
triggerEvent("onAutoIndex", getRootElement())
dbQuery (
function ( queryHandle )
local resultTable, num, err = dbPoll( queryHandle, 0 )
if resultTable then
for rowNum, rowData in ipairs(resultTable) do
triggerClientEvent("onBDMassive", getRootElement(), rowData['id'], rowData['name'], rowData['surname'], rowData['address'])
end
end
end,
dbSQL,
"SELECT id , name, surname, address FROM players"
)
end
function updatePlayerSQL( name, surname, address, id)
dbExec ( dbSQL,
[[UPDATE players
SET name = ? , surname = ? , address = ?
WHERE id = ?;
]]
, name, surname, address, id )
end
function deletePlayerSQL(id)
dbExec ( dbSQL,
[[DELETE FROM players
WHERE id = ?;
]]
, id )
end
addEvent("onAutoIndex" , true )
addEvent("onCreatePlayer", true )
addEvent("onReadPlayer" , true )
addEvent("onUpdatePlayer", true )
addEvent("onDeletePlayer", true )
addEventHandler("onAutoIndex" , getRootElement(), indexPlayerSQL )
addEventHandler("onCreatePlayer" , getRootElement(), createPlayerSQL )
addEventHandler("onReadPlayer" , getRootElement(), readPlayerSQL )
addEventHandler("onUpdatePlayer" , getRootElement(), updatePlayerSQL )
addEventHandler("onDeletePlayer" , getRootElement(), deletePlayerSQL )
addEventHandler("onResourceStart", getRootElement(), connectBaseSQL) | 881937f501b0a6fe65f773998a260c1f258bb08a | [
"Lua"
]
| 4 | Lua | DeadLineExe/myscript | c4ca4b56dd5183115711d2ac1d4923f56a05086b | 11aa3ce7037a4568ed6e714f3ea172529d890aea |
refs/heads/main | <file_sep>import React from 'react';
import Navbar from '../../../components/navbar';
import { shallow } from 'enzyme';
describe('App', () => {
it('matches snapshot', () => {
const wrapper = shallow(<Navbar count={2} />);
expect(wrapper).toMatchSnapshot();
});
});<file_sep>import React from 'react';
const count = props => (
<div className="count-bubble">
{props.count}
</div>
)
export default count;<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import ContentEditable from "react-contenteditable";
import "./note.css"
const note = props => {
const { content, handleContentChange, title, handleDeleteNote, index, handleTitleChange } = props;
return (
<div className="note__container" data-testid="note-element" >
<ContentEditable
className={"note__title"}
// innerRef={this.contentEditable}
html={title} // innerHTML of the editable div
// disabled={false} // use true to disable editing
onChange={event => handleTitleChange(event, index)} // handle innerHTML change
// tagName='article' // Use a custom HTML tag (uses a div by default)
/>
<ContentEditable
className={"note__content"}
data-testid="note-content"
// innerRef={this.contentEditable}
html={content} // innerHTML of the editable div
// disabled={false} // use true to disable editing
onChange={event => handleContentChange(event, index)} // handle innerHTML change
// tagName='article' // Use a custom HTML tag (uses a div by default)
/>
<div className="note__line" />
<button className="note__btn" onClick={() => handleDeleteNote(index)}>Delete</button>
</div>
)
}
note.propTypes = {
index: PropTypes.number,
title: PropTypes.string,
handleDeleteNote: PropTypes.func,
content: PropTypes.string,
handleContentChange: PropTypes.func,
handleTitleChange: PropTypes.func
};
export default note;<file_sep>import React from 'react';
import Notes from '../../../components/notes';
import Note from '../../../components/notes/note';
import { shallow } from 'enzyme';
describe('App', () => {
const notes = [
{
title: "Greeting",
content: "hi"
},
{
title: "Kewl",
content: "yo"
}
]
it('matches snapshot', () => {
const wrapper = shallow(<Notes notes={notes} />);
expect(wrapper).toMatchSnapshot();
});
it('has two notes', () => {
const wrapper = shallow(<Notes notes={notes} />);
expect(wrapper.find(Note).length).toEqual(2);;
});
});<file_sep>import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import Header from "../components/navbar";
import Notes from "../components/notes";
import "./App.css";
function App() {
const [notes, setNotes] = useState([]);
const [post, setPostNumber] = useState(1);
useEffect(() => {
async function fetchNotes() {
if (post > 0) {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts/" + post
);
console.log(response);
const {
data: { title, body },
} = response;
const newNotes = Array.from(notes);
newNotes.push({ title, content: body });
setNotes(newNotes);
} catch (e) {
// ignore
}
}
}
fetchNotes();
}, [post]);
const handleNewNote = () => {
const newNotes = Array.from(notes);
newNotes.push({ title: "Edit Me!", content: "Edit Me!" });
setNotes(newNotes);
};
const handleDeleteNote = (index) => {
const newNotes = Array.from(notes);
newNotes.splice(index, 1);
setNotes(newNotes);
};
const handleContentChange = (event, index) => {
const {
target: { value },
} = event;
const newNotes = notes.slice();
const newNote = newNotes[index];
newNotes.splice(index, 1, { ...newNote, content: value });
setNotes(newNotes);
};
const handleTitleChange = (event, index) => {
const {
target: { value },
} = event;
const newNotes = notes.slice();
const newNote = newNotes[index];
newNotes.splice(index, 1, { ...newNote, title: value });
setNotes(newNotes);
};
const count = notes.length;
return (
<div className="app__container">
<Header count={count} />
<div className="new-note__container">
<button className="btn__add-note" onClick={handleNewNote}>
Add Note
</button>
</div>
<div className="new-note__container">
<label style={{ color: "whitesmoke" }}>
Change this number to fetch a new note:
</label>
<input
value={post}
className="input__postnumber"
data-testid="input__postnumber"
onChange={(e) => setPostNumber(e.target.value)}
/>
</div>
<Notes
notes={notes}
handleContentChange={handleContentChange}
handleTitleChange={handleTitleChange}
handleDeleteNote={handleDeleteNote}
/>
</div>
);
}
export default App;
<file_sep>import React from 'react';
import { Link } from "react-router-dom";
import Counter from "./counter";
import "./index.css"
const navbar = props => {
const { count } = props;
return (
<header className="navbar__container">
<h1>React Keep</h1>
<Link style={{color: "white"}} to="/page">NewPage</Link>
<Counter count={count} />
</header>
)
};
export default navbar;<file_sep>import React from 'react';
import Note from "./note";
import "./notes.css"
const notes = props => {
const { notes, handleContentChange, handleDeleteNote, handleTitleChange } = props;
return (
<div className="notes__container">
{notes.map((note, index) => <Note
key={index}
{...note}
index={index}
handleContentChange={handleContentChange}
handleTitleChange={handleTitleChange}
handleDeleteNote={handleDeleteNote}
/>)}
</div>
)
}
export default notes; | 5296a68cc5fc9ce3a8b1bd34a97983719ff6f1bc | [
"JavaScript"
]
| 7 | JavaScript | yogeshpatel2002/new-cloud-training | dc07fe1255a499e33d45574499d79f5d87268e61 | 4968ec66d406967dd027910b88b2df1731bf30db |
refs/heads/main | <file_sep>rm article-template-1-num.synctex.gz
rm elsarticle-template-1-num.spl
rm elsarticle-template-1-num.aux
rm elsarticle-template-1-num.log
rm elsarticle-template-1-num.blg
| 7f63ae328439e0c487bfc63e05e174ff53ff0663 | [
"Shell"
]
| 1 | Shell | vankampen92/Modelling-HIV-AIDS-epidemics-in-Madagascar-Main-Text- | e6dd3f5199132c499779227157511483315ec29f | 4321462e86a5cc2f7a5ac57d67885d8621e322b6 |
refs/heads/master | <repo_name>mrcarlao/opiniaodetudo<file_sep>/app/src/main/java/com/example/opiniaodetudo/ReviewRepository.kt
package com.example.opiniaodetudo
import android.content.Context
import java.util.*
class ReviewRepository{
private val reviewDao: ReviewDao
constructor(context: Context){
val reviewDatabase = ReviewDatabase.getInstance(context)
reviewDao = reviewDatabase.reviewDao()
}
fun save(name: String, review: String){
reviewDao.save(Review(UUID.randomUUID().toString(), name, review))
}
fun listAll(): List<Review> {
return reviewDao.listAll()
}
fun delete(item: Review) {
TODO("Not yet implemented")
}
}<file_sep>/app/src/main/java/com/example/opiniaodetudo/MainActivity.kt
package com.example.opiniaodetudo
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.room.*
import java.util.*
class MainActivity : AppCompatActivity() {
@SuppressLint("StaticFieldLeak")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val buttonSave= findViewById<Button>(R.id.button_save)
val textViewName = findViewById<TextView>(R.id.input_nome)
val textViewReview = findViewById<TextView>(R.id.input_review)
buttonSave.setOnClickListener{
object : AsyncTask<Void, Void, Unit>() {
override fun doInBackground(vararg params: Void?) {
val name = textViewName.text
val review = textViewReview.text
val repository = ReviewRepository([email protected])
repository.save(name.toString(), review.toString())
startActivity(Intent(this@MainActivity, ListActivity::class.java))
}
}.execute()
}
val mainContainer = findViewById<ConstraintLayout>(R.id.main_container)
mainContainer.setOnTouchListener { v, event ->
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
}
}
}
<file_sep>/app/src/main/java/com/example/opiniaodetudo/Review.kt
package com.example.opiniaodetudo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Review(
@PrimaryKey
val id: String,
val name: String,
val review: String?)<file_sep>/settings.gradle
include ':app'
rootProject.name='OpiniaoDeTudo'
<file_sep>/app/src/main/java/com/example/opiniaodetudo/ReviewDao.kt
package com.example.opiniaodetudo
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
@Dao
interface ReviewDao {
@Insert
fun save(review: Review)
@Query("SELECT * from ${ReviewTableInfo.TABLE_NAME}")
fun listAll():List<Review>
@Delete
fun delete(item: Review)
} | 24a6f1c354e7513783674ea1449453f53ebee8e1 | [
"Kotlin",
"Gradle"
]
| 5 | Kotlin | mrcarlao/opiniaodetudo | 636e0b4b7189cfb6cd15645f2b730d72dd1f7eb9 | 59649bcde9c6fdaac78a509fca3b5e2f7baaab54 |
refs/heads/main | <file_sep>export const aspects = [
{ name: "support", displayName: "Support" },
{ name: "teamwork", displayName: "Teamwork" },
{ name: "pawnsOrPlayers", displayName: "Pawns or players" },
{ name: "mission", displayName: "Mission" },
{ name: "suitableProcess", displayName: "Suitable process" },
{ name: "deliveringValue", displayName: "Delivering value" },
{ name: "learning", displayName: "Learning" },
{ name: "speed", displayName: "Speed" },
{ name: "easyToRelease", displayName: "Easy to release" },
{ name: "fun", displayName: "Fun" },
];
<file_sep>import { faCaretDown, faCaretUp, faEquals } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import styled from "styled-components";
import tinycolor from "tinycolor2";
const Container = styled.button`
background-color: ${(p) => (p.isSelected ? p.accentColor : "#e5e5e5")};
border-radius: 3px;
box-sizing: content-box;
color: #143628;
color: #3c3d41;
cursor: pointer;
display: inline-block;
font-family: "Inter", sans-serif;
font-size: 11pt;
font-weight: 700;
line-height: 11pt;
min-width: 5ch;
padding: 6px 7px;
text-align: center;
transition: all 200ms ease-in-out;
white-space: nowrap;
@media (hover: hover) {
&:hover {
background-color: ${(p) =>
p.isSelected
? tinycolor(p.accentColor).lighten(15).toString()
: p.accentColor};
color: #3b3b3c;
}
}
&:focus {
background-color: ${(p) =>
tinycolor(p.isSelected ? p.accentColor : "#e5e5e5")
.darken(p.isSelected ? 4 : 10)
.toString()};
}
&,
:hover,
:focus,
:active {
border: none;
outline: none;
}
> span {
margin-right: 3px;
text-transform: ${(p) => p.textTransform};
}
> svg {
font-size: ${(p) => p.iconSize}pt;
}
`;
const sentimentToColor = {
bad: "#ff7c7c",
ok: "#fbc47a",
good: "#00ff99",
};
const trendToIcon = {
down: faCaretDown,
nochange: faEquals,
up: faCaretUp,
};
export const FeedbackButton = (props) => {
const { sentiment, trend } = props;
const accentColor = sentimentToColor[sentiment];
return (
<Container
onClick={props.onClick}
isSelected={props.isSelected}
accentColor={accentColor}
iconSize={trend === "nochange" ? 9 : 11}
textTransform={sentiment === "ok" ? "uppercase" : "capitalize"}
>
<span>{sentiment}</span>
<FontAwesomeIcon icon={trendToIcon[trend]} />
</Container>
);
};
<file_sep>import some from "lodash.some";
import React, { useState } from "react";
import { useCookies } from "react-cookie";
import { submitResponse } from "../../apiClient";
import { BarButton, PlainContainer, SubHeader, TextArea } from "../../components/misc";
import { aspects } from "./aspects";
import { Completed } from "./completed";
import { FeedbackAspect } from "./feedbackAspect";
const initialEvaluations = aspects.reduce(
(evals, aspect) => ({
...evals,
[aspect.name]: { sentiment: null, trend: null },
}),
{}
);
export const Survey = (props) => {
const { date } = props;
const [aspectToEvaluation, setEvaluations] = useState(initialEvaluations);
const [comment, setComment] = useState("");
const [surveySubmitted, setSurveySubmitted] = useState(false);
const [isLoading, setisLoading] = useState(false);
const [cookies, setCookie] = useCookies();
const onFeedbackButtonClick = (aspect, newSentiment, newTrend) => {
const { sentiment, trend } = aspectToEvaluation[aspect];
const newAspectEvaluation =
newSentiment === sentiment && newTrend === trend
? { sentiment: null, trend: null }
: { sentiment: newSentiment, trend: newTrend };
setEvaluations({
...aspectToEvaluation,
[aspect]: newAspectEvaluation,
});
};
const onSubmit = async () => {
setisLoading(true);
const result = await submitResponse(aspectToEvaluation, comment, date);
if (result.isFail()) {
const message =
result.fail() === "ran_out_of_sheety"
? "It appears we've ran into a Sheety situation :/ The monthly request limits of your Sheety subscription have been exceeded. Try again later or upgrade your subscription!"
: "Something went terribly wrong. Try again later!";
alert(message);
setisLoading(false);
return;
}
setCookie(date, new Date().toISOString(), { path: "/" });
setSurveySubmitted(true);
setisLoading(false);
};
const feedbackButtonSelected = (aspect, selectedSentiment, selectedTrend) => {
const { sentiment, trend } = aspectToEvaluation[aspect];
return sentiment === selectedSentiment && trend === selectedTrend;
};
const canSubmit = !some(Object.values(aspectToEvaluation), [
"sentiment",
null,
]);
const renderCompletedPage = () => (
<Completed
presentlySubmitted={surveySubmitted}
completedOn={new Date(cookies[date])}
/>
);
const renderSurveyContents = () => (
<PlainContainer>
<div>
{aspects.map((a, i) => (
<FeedbackAspect
key={i}
onFeedbackButtonClick={onFeedbackButtonClick.bind(this, a.name)}
feedbackButtonSelected={feedbackButtonSelected.bind(this, a.name)}
>
{a.displayName}
</FeedbackAspect>
))}
</div>
<TextArea
placeholder="Additional remarks..."
rows="3"
value={comment}
onChange={(e) => setComment(e.target.value)}
/>
<BarButton disabled={!canSubmit} onClick={onSubmit}>
{isLoading ? "Submitting..." : "Submit"}
</BarButton>
</PlainContainer>
);
return (
<React.Fragment>
<SubHeader>
{"survey on " +
new Date(date).toLocaleDateString("en-gb", {
year: "numeric",
month: "long",
day: "numeric",
})}
</SubHeader>
{surveySubmitted || cookies[date]
? renderCompletedPage()
: renderSurveyContents()}
</React.Fragment>
);
};
<file_sep># Squad Health Check
Squad Health Check is a simple tool to conduct surveys on the mood of development teams. It helps
measure and visualize how the team is doing. It is inspired by a [post](https://engineering.atspotify.com/2014/09/16/squad-health-check-model/) in the [Spotify engineering blog](https://engineering.atspotify.com/).
As the blog post's author suggests, the primary audience is meant to be the team rather than management.
Read the blog post to learn more about the health check model and get more insights on the elements of the survey.
See a demo at [shc.myftija.com](https://shc.myftija.com/). The survey responses are persisted on a Google spreadsheet, so you can easily make charts out of them to visualize the _sentiments_ and _trends_. Check out an example at this [link](https://docs.google.com/spreadsheets/d/1M9t6lABTOY_TPStrJ21326a2tqEFxLaDff_tC-pZzgA/edit#gid=1904152999).
## Setup
Squad Health Check is a React app. [Sheety](https://sheety.co/) is being used for the API; it provides a layer
on top of the Google Sheets API which makes it easy and quick to create HTTP endpoints for manipulating data in spreadsheets.
### Deploying
It is quite straightforward to deploy the app and start using it in your team. This section goes over the steps.
1. Login into your Google account and import this [spreadsheet](https://docs.google.com/spreadsheets/d/1M9t6lABTOY_TPStrJ21326a2tqEFxLaDff_tC-pZzgA/edit#gid=361520908): `File` > `Make a copy`
2. Go to [Sheety](https://sheety.co/) and open an account.
3. Create a new Sheety project: `New Project` > `From Google Sheet...` > paste the URL of the spreadsheet you previously imported
4. Enable the `GET` method for the `surveys` sheet and the `POST` method for the `responses` sheet. Disable all other methods across all sheets.
5. Copy the Sheety API URL and export it as an environment variable under the name `REACT_APP_API_URL`. You can also do this by creating a `.env.production.local` file in the root directly and defining the variable there:
```shell
touch .env.production.local
echo "REACT_APP_API_URL=https://api.sheety.co/YOUR_SHEETY_USER_ID/SHEETY_PROJECT_NAME" > .env.production.local
```
Refer to [.env.production.local.template](./.env.production.local.template). Note that your Sheety API URL should not contain a sheet name.
6. Deploy the React app by a method of your choosing. There are abundant options which make it terribly easy to deploy. For example, deploying to [Netlify](https://www.netlify.com/) is as easy as executing the following commands:
```shell
npm install netlify-cli -g
yarn build
netlify deploy --dir ./build
```
Find out more about deploying React apps in the [docs](https://create-react-app.dev/docs/deployment).
That's it! You can start using the app now.
### Local Development
First, you need to either create a separate Sheety app as shown the previous section or mock the API locally.
This section goes with the latter approach and shows how to mock the Sheety API using [mockoon](https://mockoon.com/).
1. Install [mockoon-cli](https://github.com/mockoon/cli) and start the mock API server:
```shell
npm install -g @mockoon/cli
mockoon-cli start --data ./mockoon/sheety-api-mock.json -i 0
```
2. Export the mock API URL as an environment variable under the name `REACT_APP_API_URL`. You can also do this by creating a `.env.development.local` file in the root directly and defining the variable there:
```shell
touch .env.development.local
echo "REACT_APP_API_URL=http://localhost:8080" > .env.development.local
```
Refer to [.env.development.local.template](./.env.development.local.template).
3. Serve the React app:
```shell
yarn start
```
## Usage
Once you got the app all setup, start by removing the dummy data in your imported spreadsheet.
Clear the rows in the `responses` sheet. Next, clear the content of the `date` column in the `surveys` sheet; leave the `response_count` column intact as it contains a formula to count the responses.
To create a new survey, simply add a new date in the `surveys` sheet. Double click a cell in the `date` column to show a tooltip that prompts you to select a date. Do not modify the cells in the `response_count` column.
That's it! You can now share the link with your team and responses will be persisted in the spreadsheet.
The `charts` sheet will automatically be populated with data, so there is not need to modify anything besides selecting the date at the top row of the sheet. But you could of course add additional visualizations of your liking.
## Contributing
Contributions are welcome! Feel free to open a pull request or issue.
## License
[MIT](./LICENSE)
<file_sep>import styled from "styled-components";
const Container = styled.div`
cursor: pointer;
display: flex;
flex-direction: column;
margin: auto;
`;
const CircleContainer = styled.div`
margin: auto;
> div + div {
margin-left: 4px;
}
`;
const Circle = styled.div`
background-color: #00ff99;
border-radius: 4px;
display: inline-block;
height: 8px;
opacity: ${(p) => p.opacity};
width: 8px;
`;
const TextContainer = styled.div`
color: white;
font-size: 27pt;
font-weight: 800;
text-align: center;
`;
export const Logo = (props) => (
<Container onClick={props.onClick}>
<CircleContainer>
<Circle opacity={0.6} />
<Circle opacity={0.8} />
<Circle opacity={1} />
</CircleContainer>
<TextContainer>Squad Health Check</TextContainer>
</Container>
);
<file_sep>import { faCheck, faChevronRight } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React from "react";
import styled from "styled-components";
import tinycolor from "tinycolor2";
const Row = styled.button`
background-color: #fafafa;
color: #143628;
cursor: pointer;
display: flex;
flex-direction: row;
font-family: "Inter", sans-serif;
font-size: 14pt;
font-weight: 700;
padding: 20px 0;
transition: all 200ms ease-in-out;
white-space: nowrap;
width: 100%;
&,
:hover,
:focus,
:active {
border: none;
outline: none;
}
&:hover,
:focus {
background-color: ${tinycolor("#fafafa").darken(4).toString()};
& span#arrow {
color: #6633cc;
transform: translateX(5px);
}
& span#index {
color: #6633cc;
opacity: 1;
transform: translateX(-5px);
}
}
&:focus {
background-color: ${tinycolor("#fafafa").darken(8).toString()};
}
`;
const Index = styled.span.attrs({ id: "index" })`
transition: all 200ms ease-in-out;
opacity: 0.3;
text-align: right;
flex-grow: 1;
flex-basis: 0;
`;
const SurveyDate = styled.span`
text-align: center;
padding: 0 25px;
min-width: 11ch;
flex-basis: 0;
`;
const State = styled.span`
text-align: left;
flex-grow: 1;
flex-basis: 0;
display: flex;
align-items: center;
> span#responses {
font-size: 0.6em;
background-color: #dcdcdc;
padding: 2px 5px;
border-radius: 2px;
vertical-align: middle;
@media (max-width: 600px) {
display: none;
}
}
> span#checkmark {
margin-right: 15px;
color: #a4a4a4;
}
> span#arrow {
color: #a4a4a4;
transition: all 200ms ease-in-out;
}
`;
export const Survey = (props) => (
<Row onClick={props.onClick}>
<Index>#{props.index}</Index>
<SurveyDate>
{new Date(props.date).toLocaleDateString("en-gb", {
year: "numeric",
month: "short",
day: "numeric",
})}
</SurveyDate>
<State>
{props.completed ? (
<React.Fragment>
<span id="checkmark">
<FontAwesomeIcon icon={faCheck} />
</span>
<span id="responses">{props.responseCount} responses</span>
</React.Fragment>
) : (
<span id="arrow">
<FontAwesomeIcon icon={faChevronRight} />
</span>
)}
</State>
</Row>
);
| 8d96cf0ef16a946529a0da0d896ca0210beb76cd | [
"JavaScript",
"Markdown"
]
| 6 | JavaScript | myftija/squad-health-check | 6588504c3cb8a53e6476995551d6fea8c15c47cc | bbe461ff8e63d862d5d3bcdf40ec90885e5d416e |
refs/heads/master | <file_sep>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var validUrl = require('valid-url');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var sanitizeHtml = require('sanitize-html');
var port = process.env.PORT || 3000
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended : true
}));
app.use(bodyParser.json());
app.get('/', function(req, res){
if(!req.cookies.name || req.cookies.name == 'undefined')
{
res.redirect('sign');
}
res.sendFile(__dirname + '/index.html');
});
app.get('/sign', function(req, res){
res.sendFile(__dirname + '/sign.html');
});
app.post('/sign', function(req, res){
var name = req.param('name');
res.cookie('name', name);
res.redirect('/');
});
app.use("/assets", express.static(__dirname + '/assets'));
io.on('connection', function(socket){
socket.on('chat message', function(input){
var response = {};
response.text = sanitizeHtml(input.message);
response.user = input.user;
var splited = input.message.split(' ');
for (i in splited)
{
if(validUrl.isUri(splited[i]))
{
response.media = '<img src="'+splited[i]+'" />';
}
}
io.emit('chat message', response);
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
<file_sep>$(function() {
definePanelHeight();
$('.panel-heading').append('as [' + getCookie('name') + ']');
$(window).on('resize', definePanelHeight);
var socket = io();
$('form').submit(function(e){
socket.emit('chat message', {
user : getCookie('name'),
message : $('#m').val()
});
$('#m').val('');
e.preventDefault();
});
socket.on('chat message', function(response){
var li = $('<li class="list-group-item">');
li.html($('<div>').addClass('user label label-primary').css('display', 'inline-block').html(response.user + ':'));
if(response.text)
{
li.append($('<div>').addClass('text').html(response.text));
}
if(response.media)
{
li.append($('<div>').addClass('media').html(response.media));
}
$('#messages').append(li);
$('.panel-body').scrollTop($('.panel-body').prop('scrollHeight'));
});
});
function definePanelHeight()
{
$('.panel-body').css('height',
$(window).height() - $('.panel-heading').height() - ($('.panel-footer').height() * 3.5)
);
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
}
return "";
} | 28fe98c88c45b6dd663cffeb6fdce87d52d35334 | [
"JavaScript"
]
| 2 | JavaScript | marcosrjjunior/chat-example | 06d4eea4f843ed8fa49bd0ca1276d3bb36092262 | 43aa15b927c2af98c6748d84365a93e12eaafab0 |
refs/heads/master | <file_sep>#!/usr/bin/python
from twill.commands import *
from sys import stdout
#To count the number of characters
count = 0
#The test string
ch = ['a', 'a', 'a', 'a', 'a']
#The length of the current test string
length = len(ch)
while True :
#Logic to change the test password
ch[3] = chr(ord(ch[3])+1) #Changes only one.. improve it
#Convert the list to string
c = ''.join(ch)
#Logic to insert password
go("http://192.168.0.1/login.htm")
fv("1", "password", c)
submit()
res = show()
if res != '<html><head><meta HTTP-EQUIV="Pragma" CONTENT="no-cache"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script language=\'javascript\'>alert("Username or password error, try again!");</script></head><body onload="window.location.href=\'login.htm\';"></body></html>' :
print (ch + " is the found password.")
break
<file_sep>import urllib2
import MySQLdb as sql
import csv
#the link to be downloaded from
link = "https://api.thingspeak.com/stream/channels/210904/feeds?api_key=BS3RRU9E3SUTTKYC&timezone=UTC"
#getting the response from server
response = urllib2.urlopen(link)
#saving to csvfile
csvfile = response.read()
#to check what you got in request, uncomment the next line
#print csvfile
#writing into csv file
target = open("target.csv", 'w')
target.write(csvfile)
#deleting the first line from file since it contains columns
with open('target.csv', 'r') as fin:
data = fin.read().splitlines(True)
with open('target.csv', 'w') as fout:
fout.writelines(data[1:])
#connection to database
db = sql.Connection (host = "localhost", user = "root", passwd = "<PASSWORD>", db = "damn")
#cursor file
cur = db.cursor()
#creating database NOTE: RUN ONLY ONCE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#cur.execute("CREATE DATABASE damn;")
#Necesarry shit NOTE: IF YOU WANT TO KEEP THE TABLE BEFORE NEXT EXECUTION, COMMENT THE NEXT LINE AND THE LINE AFTER THAT.
cur.execute("DROP TABLE IF EXISTS hell;")
#create the hell(after all i am the creator here.. xD)
cur.execute("CREATE TABLE hell(datentime VARCHAR, someshit INTEGER, someothershit FLOAT);")
#insert into the TABLE
#reading from file
csv_data = csv.reader(file('target.csv'))
for row in csv_data:
cur.execute('INSERT INTO hell VALUES("%s", "%s", "%s")', row)
#Commiting for further use
cur.commit()
cur.execute("SELECT * FROM hell")
cur.close()
<file_sep>import hashlib
import json
from time import time
class Blockchain(object):
def __init__(self):
self.chain = []
self.current_transactions = []
#creates the genesis block
self.new_block(proof=100, previous_hash=1)
def new_block(self, proof, previous_hash=None):
#Creates a new block and adds it to the chain
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.chain[-1]),
}
#reset the current list of transactions
self.current_transactions = []
self.chain.append(block)
return block
def new_transaction(self, sender, recipient, amount):
#Adds a new transaction to the list of transactions
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount,
})
return self.last_block['index'] + 1
@staticmethod
def hash(block):
#Creates a SHA-256 hash of a block
#We must ensure that the dictionary is ordered, or we'll have inconsistent hashes
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
@property
def last_block(self):
#Returns the last block in the chain
return self.chain[-1]
| d17e5fbd57b1f7157db2f4d0ade1036da1ff8d54 | [
"Python"
]
| 3 | Python | visheshnayak/Python | ec63d5a3f2893cc68915d2d3b18e808bf0ba5837 | 56356d1776a46bc0ecf42f51e9c3af5590e5c2b7 |
HEAD | <file_sep><?php
$_SERVER['DEVELOP'] = strpos($_SERVER['HTTP_HOST'], 'dev.') !== false;
$incPath = get_include_path();
$rootPath = realpath(dirname(__FILE__));
set_include_path($rootPath.':'.$incPath);
<file_sep><?php
class ContentHandler extends Page {
const PreviewRecangle = 750;
public function showFullPostImage() {
$args = func_get_arg(0);
$basePath = $args[0].'/'.$args[1].'/'.$args[2].'/'.$args[3];
$sourcePath = '../upload/'.$basePath;
$destPath = 'image/full/'.$basePath;
$this->showPostImage($destPath, $sourcePath, 1280);
}
public function showSmallPostImage() {
$args = func_get_arg(0);
$basePath = $args[0].'/'.$args[1].'/'.$args[2].'/'.$args[3];
$sourcePath = '../upload/'.$basePath;
$destPath = 'image/small/'.$basePath;
$this->showPostImage($destPath, $sourcePath, self::PreviewRecangle);
}
private function showPostImage($destPath, $sourcePath, $maxSize) {
if(file_exists($sourcePath)) {
@mkdir(dirname($destPath), 0777, true);
$sourceImage = imagecreatefromjpeg($sourcePath);
$sizes = getimagesize($sourcePath);
if($sizes[0] > $sizes[1]) {
if($sizes[0] > $maxSize) {
$width = $maxSize;
$height = ($width / $sizes[0]) * $sizes[1];
}
else {
$width = $sizes[0];
$height = $sizes[1];
}
}
else {
if($sizes[1] > $maxSize) {
$height = $maxSize;
$width = ($height / $sizes[1]) * $sizes[0];
}
else {
$width = $sizes[0];
$height = $sizes[1];
}
}
$destImage = imagecreatetruecolor($width, $height);
imagecopyresampled($destImage, $sourceImage, 0, 0, 0, 0, $width, $height, $sizes[0], $sizes[1]);
imagedestroy($sourceImage);
imagejpeg($destImage, $destPath, 90);
imagedestroy($destImage);
$this->getSlim()->response()->header('Content-Type', 'image/jpeg');
echo file_get_contents($destPath);
}
else {
$this->getSlim()->response()->status(404);
return;
}
}
}
<file_sep>$(document).ready(function () {
var posts = $('span.rating a.vote');
posts.click(function () {
var url = $(this).attr('href');
var item = $(this).parent();
$.getJSON(url, function (data) {
if (!data.error) {
$('span.count', item).text(' ' + data.rating + ' ');
$('a', item).remove();
} else {
console.log(data.msg);
}
});
return false;
});
});<file_sep><?php
abstract class Page {
/**
* @var Slim\Slim
*/
private $slim;
public function __construct($slim) {
$this->slim = $slim;
}
/**
* @return Slim\Slim
*/
protected final function getSlim() {
return $this->slim;
}
protected final function displayTemplate($template) {
//$template = $this->parseTemplateName($template);
$this->getSlim()->view()->display($template);
}
private function parseTemplateName($template) {
if($this->slim->request()->isAjax()) {
return $this->ajaxTemplate($template);
}
return $template;
}
private function ajaxTemplate($template) {
$templateName = basename($template, '.twig');
$template = str_replace($templateName, $templateName.'.ajax', $template);
return $template;
}
protected final function appendDataToTemplate($data) {
$this->slim->view()->appendData($data);
}
protected final function checkAjaxPermissions() {
if(!$this->getSlim()->request()->isAjax() || !Application::isAdmin()) {
$this->getSlim()->halt(404);
}
}
}
<file_sep><?php
class Post {
private $data;
public function __construct($data = array()) {
if(is_null($data)) {
throw new InvalidArgumentException('post not found');
}
$this->data = $data;
}
public function getId() {
return $this->data['_id']->{'$id'};
}
public function getTitle() {
return $this->data['title'];
}
public function getDate() {
return $this->data['date'];
}
public function getFullImage() {
return '/image/full/'.$this->data['file'];
}
public function getSmallImage() {
return '/image/small/'.$this->data['file'];
}
public function getFile() {
return $this->data['file'];
}
public function setTitle($title) {
$this->data['title'] = $title;
}
public function getPhotographer() {
if(!isset($this->data['photographer'])) {
return '';
}
return $this->data['photographer'];
}
public function setPhotographer($photographer) {
$this->data['photographer'] = $photographer;
}
public function getData() {
return $this->data;
}
public function getInfo() {
if(!isset($this->data['info'])) {
$file = dirname(__FILE__).'/../../upload/'.$this->getFile();
$info = getimagesize($file);
$this->data['info'] = $info;
PostFactory::savePost($this);
return $info;
}
return $this->data['info'];
}
public function getSize() {
$info = $this->getInfo();
if(!isset($this->data['size'])) {
$size = array($info[0], $info[1]);
$this->data['size'] = $size;
PostFactory::savePost($this);
return $size;
}
return $this->data['size'];
}
public function getRating() {
if(!isset($this->data['rating'])) {
return null;
}
return $this->data['rating'];
}
public function setRating($rating) {
$this->data['rating'] = $rating;
}
}
<file_sep><?php
if($argc < 2) {
echo "Usage: php importQueue.php source/file \r\n";
exit;
}
$incPath = get_include_path();
$rootPath = realpath(dirname(__FILE__).'/../');
set_include_path($rootPath.':'.$incPath);
$_SERVER['DEVELOP'] = strpos($rootPath, 'develop') !== false;
require_once 'libs/MongoAssist.php';
$queue = MongoAssist::GetCollection('import_queue');
$source = $argv[1];
if(!file_exists($source)) {
echo "File: ".$source." not found\r\n";
exit;
}
$dest = '/var/www/deveaque/data/queue/'.basename($source);
copy($source, $dest);
$data = array(
'path' => $dest,
'time' => time()
);
$queue->insert($data);<file_sep><?php
require_once 'app/pages/Page.php';
require_once 'app/models/PostFactory.php';
class PostHandler extends Page {
private $uploadPath;
public function __construct($slim) {
parent::__construct($slim);
$this->uploadPath = $_SERVER['DOCUMENT_ROOT'].'/../upload/';
}
public function addPost() {
$files = $_FILES;
$titles = $this->getSlim()->request()->post('title');
$photographers = $this->getSlim()->request()->post('photographer');
foreach($files['image']['tmp_name'] as $id => $file) {
$title = $titles[$id];
$photographer = $photographers[$id];
$fileName = $this->uploadFile($file);
$post = new Post(array(
'title' => $title,
'file' => $fileName,
'date' => date('U'),
'photographer' => $photographer,
));
PostFactory::createPost($post);
}
$this->getSlim()->redirect('/');
}
public function editPost($id) {
$this->checkAjaxPermissions();
try {
$post = PostFactory::getPost($id);
$post->setTitle($this->getSlim()->request()->post('title'));
$post->setPhotographer($this->getSlim()->request()->post('photographer'));
PostFactory::savePost($post);
echo json_encode(array(
'saved' => true,
'title' => $post->getTitle(),
'photographer' => $post->getPhotographer())
);
}
catch(Exception $ex) {
echo json_encode(array('saved' => false, 'error' => $ex->getMessage()));
}
}
public function deletePost($id) {
$this->checkAjaxPermissions();
try {
PostFactory::deletePost($id);
}
catch(Exception $e) {
echo json_encode(array('error' => $e->getMessage()));
}
}
private function uploadFile($file) {
if(!file_exists($file)) {
throw new RuntimeException('А картинку прикрепить?');
}
$datePath = date('Y').'/'.date('m').'/'.date('d').'/';
$imageDir = $this->uploadPath.$datePath;
@mkdir($imageDir, 0777, true);
$fileName = md5($file).'.jpg';
move_uploaded_file($file, $imageDir.$fileName);
$fileName = $datePath.$fileName;
return $fileName;
}
}
<file_sep><?php
$incPath = get_include_path();
$rootPath = realpath(dirname(__FILE__).'/../');
set_include_path($rootPath.':'.$incPath);
$_SERVER['DEVELOP'] = strpos($rootPath, 'develop') !== false;
require_once 'libs/MongoAssist.php';
require_once 'models/PostFactory.php';
require_once 'models/Tags.php';
$args = array();
for($i = 1; $i < $argc; $i++) {
$arg = explode('=', $argv[$i]);
$args[$arg[0]] = $arg[1];
}
if(isset($args['file'])) {
$file = file_get_contents(realpath($args['file']));
$data = (array)json_decode($file);
if(!isset($data['file'])) {
die("need image path");
}
if(!isset($data['date'])) {
$data['date'] = date('U');
}
if(isset($data['tags'])) {
$tags = $data['tags'];
unset($data['tags']);
}
$post = new Post($data);
PostFactory::createPost($post);
if(isset($tags)) {
foreach($tags as $tag) {
Tags::saveTag($tag);
Tags::attachPost($tag, $post->getId());
}
}
}<file_sep><?php
$_SERVER['DEVELOP'] = strpos(getcwd(), 'develop') !== false;
$incPath = get_include_path();
$rootPath = realpath(dirname(__FILE__).'/../');
set_include_path($rootPath.':'.$incPath);
require_once 'CronExec.php';
try {
$cron = new CronExec();
$cron->run();
}
catch(InvalidArgumentException $iae) {
echo "Usage: php cron.php ModuleName [options]\r\n";
}
catch(RuntimeException $re) {
echo "Module file not found (".$re->getMessage().")\r\n";
}
<file_sep><?php
require_once 'libs/MongoAssist.php';
require_once 'PostFactory.php';
class Votes {
/**
* @var MongoCollection
*/
private static $votes = null;
public static function getRating($postId) {
self::checkCollecktion();
$count = self::$votes->count(array('post' => $postId, 'dir' => 'asc'));
$count -= self::$votes->count(array('post' => $postId, 'dir' => 'desc'));
return $count;
}
public static function rateUp($postId, $userId) {
self::checkCollecktion();
if(self::$votes->count(array('post' => $postId, 'user' => $userId)) == 0) {
self::$votes->insert(array('post' => $postId, 'user' => $userId, 'dir' => 'asc'));
self::updateRating($postId);
}
}
private static function updateRating($postId) {
$post = PostFactory::getPost($postId);
$post->setRating(self::getRating($postId));
PostFactory::savePost($post);
}
public static function rateDown($postId, $userId) {
self::checkCollecktion();
if(self::$votes->count(array('post' => $postId, 'user' => $userId)) == 0) {
self::$votes->insert(array('post' => $postId, 'user' => $userId, 'dir' => 'desc'));
self::updateRating($postId);
}
}
public static function isVoted($postId, $userId) {
self::checkCollecktion();
return self::$votes->count(array('post' => $postId, 'user' => $userId)) != 0;
}
private static function checkCollecktion() {
if(is_null(self::$votes)) {
self::$votes = MongoAssist::GetCollection('votes');
}
}
}
<file_sep><?php
require_once 'Page.php';
require_once 'app/models/PostFactory.php';
class AdminPage extends Page {
public function showUpload() {
$this->getSlim()->view()->display('upload.twig');
}
}
<file_sep><?php
require_once 'app/pages/Page.php';
require_once 'app/models/Tags.php';
class TagHandler extends Page {
public function saveTag() {
$this->checkAjaxPermissions();
$tagTitle = $this->getSlim()->request()->post('title');
try {
Tags::saveTag($tagTitle);
$result = array('success' => true, 'tag' => $tagTitle);
}
catch(Exception $ex) {
$result = array('success' => false, 'error' => $ex->getMessage());
}
echo json_encode($result);
}
public function attachTagToPost($tagTitle, $postId) {
$this->checkAjaxPermissions();
$result = array('success' => false);
try {
Tags::attachPost($tagTitle, $postId);
$result = array('success' => true);
}
catch(Exception $ex) {
$result['error'] = $ex->getMessage();
}
echo json_encode($result);
}
public function deattachTag($tagId, $postId) {
$this->checkAjaxPermissions();
try {
Tags::deattachPost($tagId, $postId);
$result = array('success' => true, 'tag' => $tagId, 'post' => $postId);
}
catch(Exception $ex) {
$result = array('success' => false, 'error' => $ex->getMessage());
}
echo json_encode($result);
}
}
<file_sep><?php
class TestModule implements CronModule {
public function exec($params = array()) {
var_dump($params);
}
}
<file_sep><?php
class MemcacheAssist {
/**
* @var Memcache
*/
private static $mmc = null;
public static function getValue($key) {
self::connectToMemcache();
return self::$mmc->get($key);
}
public static function setValue($key, $value) {
self::connectToMemcache();
self::$mmc->set($key, $value, 0, 80399);
}
public static function deleteValue($key) {
self::connectToMemcache();
self::$mmc->delete($key);
}
public static function isExists($key) {
return self::$mmc->get($key) !== false;
}
private static function connectToMemcache() {
if(is_null(self::$mmc)) {
self::$mmc = new Memcache();
self::$mmc->connect('unix:///tmp/memcached.sock', 0);
}
}
}
<file_sep><?php
interface GenericUser {
public function isGuest();
public function getData();
public function getId();
}
<file_sep><?php
require_once 'GenericUser.php';
class Guest implements GenericUser {
public function isGuest() {
return true;
}
public function getData() {
return array();
}
public function getId() {
return null;
}
}
<file_sep><?php
class RegisterHandler extends Page {
public function showRegister() {
if(!Users::getCurrentUser()->isGuest()) {
$this->getSlim()->redirect($_SERVER['HTTP_REFERER']);
}
$this->displayTemplate('forms/register.twig');
}
public function register() {
$email = $this->getSlim()->request()->post('email');
$pass = $this->getSlim()->request()->post('pass');
$pass1 = $this->getSlim()->request()->post('pass_second');
if(empty($email) || empty($pass) || empty($pass1)) {
$this->appendDataToTemplate(array('empty' => true));
$this->displayTemplate('forms/register.twig');
return;
}
if($pass != $pass1) {
$this->appendDataToTemplate(array('pass' => true));
$this->displayTemplate('forms/register.twig');
return;
}
try {
Users::registerUser($email, $pass);
}
catch(Exception $e) {
var_dump($e->getMessage());
}
$this->getSlim()->redirect('/');
}
public function login() {
$back = $_SERVER['HTTP_REFERER'];
$email = $this->getSlim()->request()->post('email');
$pass = $this->getSlim()->request()->post('pass');
Users::loginByPass($email, $pass);
$this->getSlim()->redirect($back);
}
public function logout() {
Users::logout();
$back = $_SERVER['HTTP_REFERER'];
$this->getSlim()->redirect($back);
}
public function showUserSettings() {
$back = $_SERVER['HTTP_REFERER'];
$this->getSlim()->redirect($back);
}
}
<file_sep><?php
class MongoAssist {
const dbName = 'deveaque';
/**
* @var Mongo
*/
private static $mongo = null;
/**
* @var MongoDB
*/
private static $db = null;
private static $collections = array();
/**
* @param $collection
*
* @return MongoCollection
*/
public static function GetCollection($collection) {
self::checkMongoConnection();
$collection = self::detectDevelopCollection($collection);
self::loadCollection($collection);
return self::$collections[$collection];
}
private static function detectDevelopCollection($collection)
{
$collection = ($_SERVER['DEVELOP'] ? $collection . '_dev' : $collection);
return $collection;
}
private static function loadCollection($collection) {
if(!array_key_exists($collection, self::$collections)) {
self::$collections[$collection] = self::$db->selectCollection($collection);
}
}
private static function checkMongoConnection() {
if(is_null(self::$mongo)) {
self::$mongo = new Mongo();
}
if(is_null(self::$db)) {
self::$db = self::$mongo->selectDB(self::dbName);
}
}
}
<file_sep><?php
interface CronModule {
public function exec($params = array());
}
<file_sep><?php
require_once 'app/models/PostFactory.php';
require_once 'app/models/Users.php';
require_once 'app/models/Votes.php';
class VotingHandler extends Page {
public function rateUp($postId) {
if(!$this->getSlim()->request()->isAjax()) {
$this->getSlim()->redirect('/');
return;
}
$user = Users::getCurrentUser();
if($user->isGuest()) {
echo json_encode(array(
'msg' => 'unregistered user',
'error' => true));
return;
}
if(is_null(PostFactory::getPost($postId))) {
echo json_encode(array(
'msg' => 'unknown post',
'error' => true));
return;
}
Votes::rateUp($postId, $user->getId());
$this->sendRating($postId);
}
private function sendRating($postId) {
echo json_encode(array(
'rating' => Votes::getRating($postId),
'error' => false
));
}
public function rateDown($postId) {
if(!$this->getSlim()->request()->isAjax()) {
$this->getSlim()->redirect('/');
return;
}
$user = Users::getCurrentUser();
if($user->isGuest()) {
echo json_encode(array(
'msg' => 'unregistered user',
'error' => true));
return;
}
if(is_null(PostFactory::getPost($postId))) {
echo json_encode(array(
'msg' => 'unknown post',
'error' => true));
return;
}
Votes::rateDown($postId, $user->getId());
$this->sendRating($postId);
}
}
<file_sep><?php
require_once 'GenericUser.php';
class User implements GenericUser {
private $userInfo;
public function __construct($userInfo) {
$this->userInfo = $userInfo;
}
public function isGuest() {
return false;
}
public function getData() {
return $this->userInfo;
}
public function getId() {
if(isset($this->userInfo['_id'])) {
return $this->userInfo['_id']->{'$id'};
}
return null;
}
}
<file_sep><?php
require_once 'app/pages/Page.php';
require_once 'app/models/PostFactory.php';
class EditorsHandler extends Page {
public function getPostEditor($id) {
$post = PostFactory::getPost($id);
$postData = array(
'id' => $post->getId(),
'title' => $post->getTitle(),
'photographer' => $post->getPhotographer()
);
$this->appendDataToTemplate(array('post' => $postData));
$this->displayTemplate('forms/editor.twig');
}
public function getTagEditor($id) {
$this->appendDataToTemplate(array('postId' => $id));
$this->displayTemplate('forms/tagEditor.twig');
}
}
<file_sep><?php
require_once 'libs/MongoAssist.php';
require_once 'app/models/PostFactory.php';
require_once 'app/models/Tags.php';
class ImportQueue implements CronModule {
/**
* @var MongoCollection
*/
private $queueCollection;
private $uploadPath = '';
private $shortTags = array(
'b' => 'bw',
'c' => 'colour',
'se' => 'sepia',
'u' => 'upright',
'r' => 'recumbent',
'bl' => 'blonde',
'br' => 'brunette',
'dr' => 'dressed',
'n' => 'nude',
'td' => 'top-dressed',
'bd' => 'bottom-dressed',
'un' => 'underwear',
'hs' => 'headdress',
'l' => 'lanscape',
'st' => 'studio',
'f' => 'flat',
'i' => 'industrial',
'a' => 'architecture',
'p' => 'portrait',
't' => 'torso',
's' => 'stature',
'e' => 'eyes',
'h' => 'hair',
'co' => 'cosplay',
'cs' => 'chiaroscuro',
'w' => 'water',
'ti' => 'tits',
'tt' => 'tatto',
'tm' => 'tummy',
'lg' => 'legs',
'mp' => 'makeup',
);
public function exec($params = array()) {
$this->uploadPath = dirname(__FILE__).'/../../upload/';
$this->queueCollection = MongoAssist::GetCollection('import_queue');
$this->parseQueue();
}
private function parseQueue() {
$cursor = $this->queueCollection->find()->sort(array('time' => -1))->limit(10);
while($cursor->hasNext()) {
$item = $cursor->getNext();
try {
$this->parseItem($item['path']);
$this->queueCollection->remove(array('_id' => $item['_id']));
}
catch(Exception $e) {
echo $e->getMessage()."\r\n";
}
}
}
private function parseItem($path) {
$baseName = explode('.', basename($path));
preg_match_all('/\[([\w|\s|,|-]*)\]/is', $baseName[0], $matches, PREG_SET_ORDER);
$title = $matches[0][1];
$photographer = $matches[1][1];
$tags = explode(',', $matches[2][1]);
$file = $this->importImage($path);
$post = new Post(array(
'date' => date('U'),
'photographer' => empty($photographer) ? null : $photographer,
'file' => $file,
'title' => empty($title) ? null : $title,
));
PostFactory::createPost($post);
foreach($tags as $tag) {
if(isset($this->shortTags[$tag])) {
Tags::attachPost($this->shortTags[$tag], $post->getId());
}
else {
Tags::attachPost($tag, $post->getId());
}
}
sleep(1);
}
private function importImage($file) {
$datePath = date('Y').'/'.date('m').'/'.date('d').'/';
$destPath = $this->uploadPath.$datePath;
$baseName = explode('.', basename($file));
$fileName = md5($baseName[0]).'.'.$baseName[1];
if(!file_exists($file)) {
throw new InvalidArgumentException('file '.$file.' not found');
}
@mkdir($destPath, 0777, true);
copy($file, $destPath.$fileName);
unlink($file);
return $datePath.$fileName;
}
}
<file_sep><?php
require_once 'app/pages/Page.php';
class Command {
private $slim;
private $command;
public function __construct($slim, $command) {
$this->slim = $slim;
$this->command = $command;
}
public function execute() {
$classFile = $_SERVER['DOCUMENT_ROOT'].'/../app/pages/'.$this->command[0].'.php';
if(!file_exists($classFile)) {
throw new InvalidArgumentException('Handler not found ('.$classFile.')');
}
require_once $classFile;
$className = $this->command[0];
$class = new $className($this->slim);
switch(func_num_args()) {
case 0:
call_user_func(array($class, $this->command[1]));
break;
case 1:
call_user_func(array($class, $this->command[1]), func_get_arg(0));
break;
case 2:
call_user_func(array($class, $this->command[1]), func_get_arg(0), func_get_arg(1));
break;
case 3:
call_user_func(array($class, $this->command[1]), func_get_arg(0), func_get_arg(1), func_get_arg(2));
break;
default:
call_user_func(array($class, $this->command[1]), func_get_args());
break;
}
}
public function getCallback() {
return array($this, 'execute');
}
}
<file_sep><?php
class Tags {
/**
* @var MongoCollection
*/
private static $linkCollection = null;
/**
* @var MongoCollection
*/
private static $tagCollection = null;
public static function getItemList($postId) {
self::checkCollections();
$tagLinks = self::$linkCollection->find(array('postId' => $postId));
$result = array();
while($tagLinks->hasNext()) {
$tagLink = $tagLinks->getNext();
$tag = self::$tagCollection->findOne(array('_id' => new MongoId($tagLink['tagId'])));
$result[] = $tag['title'];
}
return $result;
}
private static function checkCollections() {
if(is_null(self::$linkCollection)) self::$linkCollection = MongoAssist::GetCollection('posts_tags');
if(is_null(self::$tagCollection)) self::$tagCollection = MongoAssist::GetCollection('tags');
}
public static function saveTag($tagTitle) {
self::checkCollections();
$tag = self::$tagCollection->findOne(array('title' => $tagTitle));
if(is_null($tag)) {
self::$tagCollection->save(array('title' => $tagTitle));
}
}
public static function attachPost($tagTitle, $postId) {
self::checkCollections();
$tagId = self::getTagIdByTitle($tagTitle);
$link = self::$linkCollection->findOne(array('tagId' => $tagId, 'postId' => $postId));
if(is_null($link)) {
self::$linkCollection->save(array('tagId' => $tagId, 'postId' => $postId));
}
else {
throw new InvalidArgumentException();
}
}
private static function getTagIdByTitle($tagTitle) {
$tagId = self::$tagCollection->findOne(array('title' => $tagTitle));
if(is_null($tagId)) throw new InvalidArgumentException();
return $tagId['_id']->{'$id'};
}
public static function deattachPost($tagTitle, $postId) {
self::checkCollections();
$tagId = self::getTagIdByTitle($tagTitle);
$link = self::$linkCollection->findOne(array('tagId' => $tagId, 'postId' => $postId));
if(!is_null($link)) {
self::$linkCollection->remove(array('_id' => $link['_id']));
}
else {
throw new InvalidArgumentException();
}
}
public static function getAttachedPosts($tagTitle) {
self::checkCollections();
$tagId = self::getTagIdByTitle($tagTitle);
$cursor = self::$linkCollection->find(array('tagId' => $tagId));
$posts = array();
while($cursor->hasNext()) {
$post = $cursor->getNext();
$posts[] = new MongoId($post['postId']);
}
return $posts;
}
public static function searchTags($term) {
self::checkCollections();
$tags = array();
$cursor = self::$tagCollection->find(array('title' => new MongoRegex('/'.$term.'/')));
while($cursor->hasNext()) {
$tag = $cursor->getNext();
$tags[] = $tag['title'];
}
return $tags;
}
}
<file_sep><?php
require_once 'CronModule.php';
class CronExec {
private $moduleName;
private $params = array();
public function __construct($options = array()) {
$this->checkArguments();
$this->moduleName = $_SERVER['argv'][1];
$this->fillParams();
}
private function fillParams() {
if($_SERVER['argc'] > 2) {
$this->params = array_slice($_SERVER['argv'], 2);
}
}
private function checkArguments() {
if($_SERVER['argc'] < 2) {
throw new InvalidArgumentException();
}
}
public function run() {
$this->loadModule();
$module = new $this->moduleName;
$module->exec($this->params);
}
private function loadModule() {
$file = getcwd().'/modules/'.$this->moduleName.'.php';
if(!file_exists($file)) {
throw new RuntimeException($file);
}
require_once $file;
}
}
<file_sep><?php
use \Slim\Slim;
require_once 'libs/MongoAssist.php';
require_once 'libs/Slim/Slim.php';
Slim::registerAutoloader();
require_once 'libs/TwigAutoloader.php';
Twig_Extensions_Autoloader::register();
require_once 'libs/TwigView.php';
require_once 'app/Command.php';
require_once 'app/models/Users.php';
class Application {
const Title = 'Deveaque.com - inspiration girls';
/**
* @var Slim
*/
private $slim;
public function __construct() {
$this->initializeSession();
$this->initializeSlim();
$this->createRoutes();
$this->slim->run();
}
private function initializeSession() {
$twoWeeksInSeconds = 1209600;
session_set_cookie_params($twoWeeksInSeconds);
session_start();
}
private function createRoutes() {
$this->createBaseSiteCommands();
$this->createUserHandlerCommands();
$this->createVotingCommands();
$this->createContentCommands();
$this->createAdminCommands();
}
private function createVotingCommands() {
$this->addGetCommand('/post/vote/up/:postId', 'VotingHandler', 'rateUp');
$this->addGetCommand('/post/vote/down/:postId', 'VotingHandler', 'rateDown');
}
private function createUserHandlerCommands() {
$this->addGetCommand('/register', 'RegisterHandler', 'showRegister');
$this->addGetCommand('/user', 'RegisterHandler', 'showUserSettings');
$this->addGetCommand('/logout', 'RegisterHandler', 'logout');
$this->addPostCommand('/login', 'RegisterHandler', 'login');
$this->addPostCommand('/register', 'RegisterHandler', 'register');
}
private function createBaseSiteCommands() {
$this->addGetCommand('/(page:pageId)', 'MainSitePages', 'showDefault');
$this->addGetCommand('/post/:title/(page:pageId)', 'MainSitePages', 'showByTitle');
$this->addGetCommand('/post/:id', 'MainSitePages', 'showPost');
$this->addGetCommand('/tag/:tag/(page:pageId)', 'MainSitePages', 'showByTag');
$this->addGetCommand('/tag/search', 'MainSitePages', 'searchTag');
$this->addGetCommand('/best/(page:pageId)', 'MainSitePages', 'showBest');
}
private function createContentCommands() {
$this->addGetCommand('/image/full/:year/:month/:day/:image', 'ContentHandler', 'showFullPostImage');
$this->addGetCommand('/image/small/:year/:month/:day/:image', 'ContentHandler', 'showSmallPostImage');
}
private function createAdminCommands() {
$this->addGetAdminCommand('/upload', 'AdminPage', 'showUpload');
$this->addPostAdminCommand('/post/add', 'PostHandler', 'addPost');
$this->addPostAdminCommand('/post/edit/:id', 'PostHandler', 'editPost');
$this->addGetAdminCommand('/post/delete/:id', 'PostHandler', 'deletePost');
$this->addPostAdminCommand('/tag/save', 'TagHandler', 'saveTag');
$this->addGetAdminCommand('/tag/:tag/attach/:post', 'TagHandler', 'attachTagToPost');
$this->addGetAdminCommand('/tag/:tag/deattach/:post', 'TagHandler', 'deattachTag');
$this->addGetAdminCommand('/editors/post/:id', 'EditorsHandler', 'getPostEditor');
$this->addGetAdminCommand('/editors/tag/:id', 'EditorsHandler', 'getTagEditor');
}
private function addGetCommand($path, $class, $method) {
$command = new Command($this->getSlim(), array($class, $method));
$this->slim->get($path, $command->getCallback());
}
private function addPostCommand($path, $class, $method) {
$command = new Command($this->getSlim(), array($class, $method));
$this->slim->post($path, $command->getCallback());
}
private function addGetAdminCommand($path, $class, $method) {
if(!self::isAdmin()) return;
$command = new Command($this->getSlim(), array($class, $method));
$this->slim->get($path, $command->getCallback());
}
private function addPostAdminCommand($path, $class, $method) {
if(!self::isAdmin()) return;
$command = new Command($this->getSlim(), array($class, $method));
$this->slim->post($path, $command->getCallback());
}
private function initializeSlim() {
$this->slim = new Slim(array(
'view' => new TwigView(),
'debug' => $_SERVER['DEVELOP'],
'log.enable' => true,
'log.path' => '../slim-log',
'log.level' => 4,
'templates.path' => '../templates'
));
$this->setErrorPage();
$this->setNotFoundPage();
$this->setupGlobalTemplateData();
}
private function setNotFoundPage() {
$slim = $this->getSlim();
$this->getSlim()->notFound(function () use ($slim) {
$slim->view()->appendData(array('errorNumber' => 404, 'errorMessage' => 'Страница не найдена'));
$slim->view()->display('error.twig');
});
}
private function setErrorPage() {
$slim = $this->getSlim();
$this->getSlim()->error(function (Exception $e) use ($slim) {
$slim->view()->appendData(array(
'errorNumber' => $e->getCode(),
'errorMessage' => $e->getMessage(),
'errorTrace' => print_r($e->getTrace(), true)
));
$slim->view()->display('error.twig');
});
}
private function setupGlobalTemplateData() {
$this->getSlim()->view()->appendData(array('siteTitle' => self::Title));
$this->getSlim()->view()->appendData(array('logoTitle' => self::Title));
$this->getSlim()->view()->appendData(array('isAdmin' => self::isAdmin()));
$this->getSlim()->view()->appendData(array('isDevelop' => $_SERVER['DEVELOP']));
$user = Users::getCurrentUser();
$this->getSlim()->view()->appendData(array('user' => $user->isGuest() ? null : $user->getData()));
$this->getSlim()->view()->appendData(array('isRegisterUser' => !$user->isGuest()));
$this->getSlim()->view()->appendData(array('isGuest' => $user->isGuest()));
}
public static function isAdmin() {
$user = Users::getCurrentUser();
if($user->isGuest()) {
return false;
}
$userId = $user->getId();
$admins = array(
'50b9b6ef15f0bf031c000000',
'50b9cb2c15f0bfd71f000001',
);
return in_array($userId, $admins);
}
private function getSlim() {
return $this->slim;
}
}
<file_sep><?php
//test commit into dev
require_once '../startup.php';
require_once 'app/Application.php';
$app = new Application();
echo 'huiem buem' ;<file_sep>$(document).keyup(function (e) {
if (e.ctrlKey && e.which == 39) {
navigateNext();
}
if (e.ctrlKey && e.which == 37) {
navigatePrev();
}
});
function navigatePrev() {
var currentPage = $('.pages:first > span');
var prev = currentPage.prev('a');
if (prev.attr('href') != undefined) {
location.href = prev.attr('href');
}
}
function navigateNext() {
var currentPage = $('.pages:first > span');
var next = currentPage.next('a');
if (next.attr('href') != undefined) {
location.href = next.attr('href');
}
}<file_sep><?php
require_once 'users/User.php';
require_once 'users/Guest.php';
class Users {
/**
* @var MongoCollection
*/
private static $collection = null;
/**
* @var User
*/
private static $user = null;
private static function setCollection() {
self::$collection = MongoAssist::GetCollection('users');
}
public static function getCurrentUser() {
self::setCollection();
self::autoLogin();
return self::$user;
}
private static function autoLogin() {
if(is_null(self::$user)) {
$sesid = session_id();
if(empty($sesid) || !isset($_SESSION['email'])) {
self::$user = new Guest();
}
else {
$email = $_SESSION['email'];
$userInfo = self::$collection->findOne(array('email' => $email));
self::$user = new User($userInfo);
}
}
}
public static function registerUser($email, $pass) {
self::setCollection();
$userInfo = self::$collection->findOne(array('email' => $email));
if($userInfo) {
throw new InvalidArgumentException('user exists');
}
$user = new User(
array(
'email' => $email,
'pass' => md5($pass.'<PASSWORD>')
)
);
self::$collection->save($user->getData());
self::loginByPass($email, $pass);
}
public static function loginByPass($email, $pass) {
self::setCollection();
$userInfo = self::$collection->findOne(array('email' => $email, 'pass' => md5($pass.'<PASSWORD>')));
if(empty($userInfo)) {
self::$user = new Guest();
return;
}
self::$user = new User($userInfo);
$_SESSION['email'] = $userInfo['email'];
}
public static function logout() {
self::$user = new Guest();
unset($_SESSION['email']);
}
}
<file_sep><?php
require_once 'app/models/PostFactory.php';
require_once 'app/models/Tags.php';
require_once 'app/pages/ContentHandler.php';
require_once 'app/models/Votes.php';
require_once 'Page.php';
class MainSitePages extends Page {
const PostPerPage = 20;
public function showDefault($page = -1) {
$pages = ceil(PostFactory::getCount() / self::PostPerPage);
$page = $this->setupPage($page, $pages);
$posts = $this->loadPosts(($page - 1) * self::PostPerPage, self::PostPerPage);
$preload = '/';
if($page < $pages) {
$preload = '/page'.($pages - $page);
}
$this->appendDataToTemplate(array(
'posts' => $posts,
'page' => $page,
'pages' => $pages,
'preloadPage' => $preload,
));
$this->displayTemplate('main.twig');
}
private function setupPage($page, $pages) {
if($page == -1) {
$page = $pages;
}
$page = $pages - $page + 1;
if($page < 0) {
$this->getSlim()->notFound();
}
return $page;
}
private function loadPosts($offset) {
$postsList = PostFactory::getPosts($offset, self::PostPerPage);
return $this->buildPosts($postsList);
}
public function showByTitle($title, $page = -1) {
$this->getSlim()->view()->setData('siteTitle', $title.' - '.Application::Title);
$pages = ceil(PostFactory::getCount(array('title' => $title)) / self::PostPerPage);
$page = $this->setupPage($page, $pages);
$preload = '/';
if($page < $pages) {
$preload = '/post/'.$title.'/page'.($pages - $page);
}
$posts = $this->loadPostsByTitle($title, ($page - 1) * self::PostPerPage);
$this->appendDataToTemplate(array(
'posts' => $posts,
'page' => $page,
'pages' => $pages,
'preloadPage' => $preload,
'baseLink' => '/post/'.$title
));
$this->displayTemplate('main.twig');
}
private function loadPostsByTitle($title, $offset) {
$postsList = PostFactory::getPostsByTitle($title, $offset, self::PostPerPage);
return $this->buildPosts($postsList);
}
public function showByTag($tag, $page = -1) {
$this->getSlim()->view()->setData('siteTitle', $tag.' - '.Application::Title);
try {
$postIds = Tags::getAttachedPosts($tag);
}
catch(Exception $e) {
$this->getSlim()->notFound();
}
$pages = ceil(count($postIds) / self::PostPerPage);
$page = $this->setupPage($page, $pages);
$preload = '/';
if($page < $pages) {
$preload = '/tag/'.$tag.'/page'.($pages - $page);
}
$postsList = PostFactory::getPostsByIds($postIds, ($page - 1) * self::PostPerPage, self::PostPerPage);
$posts = $this->buildPosts($postsList);
$this->appendDataToTemplate(array(
'posts' => $posts,
'page' => $page,
'pages' => $pages,
'preloadPage' => $preload,
'baseLink' => '/tag/'.$tag
));
$this->displayTemplate('main.twig');
}
private function buildPosts($postsList) {
$posts = array();
foreach($postsList as $item) {
$size = $item->getSize();
$zoomable = ($size[0] > ContentHandler::PreviewRecangle || $size[1] > ContentHandler::PreviewRecangle);
if(is_null($item->getRating())) {
$item->setRating(Votes::getRating($item->getId()));
PostFactory::savePost($item);
}
$post = array(
'id' => $item->getId(),
'title' => $item->getTitle(),
'tmb' => $item->getSmallImage(),
'image' => $item->getFullImage(),
'date' => date('Y-m-d H:i:s', $item->getDate()),
'tags' => Tags::getItemList($item->getId()),
'photographer' => $item->getPhotographer(),
'object' => $item,
'zoomable' => $zoomable,
'rating' => $item->getRating(),
'canVote' => !Votes::isVoted($item->getId(), Users::getCurrentUser()->getId()),
);
$posts[] = $post;
}
return $posts;
}
public function showPost($postId) {
try {
$post = PostFactory::getPost($postId);
}
catch(InvalidArgumentException $e) {
$this->getSlim()->notFound();
}
$formattedDateLine = date('d F Y H:i', $post->getDate());
$postTitle = $post->getTitle();
$title = (!empty($postTitle)) ?
$postTitle.' - posted @ '.$formattedDateLine :
'Post from '.$formattedDateLine;
$this->getSlim()->view()->setData('siteTitle', $title.' - '.Application::Title);
$post = $this->buildPosts(array($post));
$preload = '/';
$this->appendDataToTemplate(array(
'item' => $post[0],
'preloadPage' => $preload,
));
$this->displayTemplate('singlePost.twig');
}
public function searchTag() {
$term = $this->getSlim()->request()->get('term');
$tags = Tags::searchTags($term);
echo json_encode($tags);
}
public function showBest($page = -1) {
$pages = ceil(PostFactory::getCount() / self::PostPerPage);
$page = $this->setupPage($page, $pages);
$posts = $this->loadPostsByRating(($page - 1) * self::PostPerPage, self::PostPerPage);
$preload = '/';
if($page < $pages) {
$preload = '/best/page'.($pages - $page);
}
$this->appendDataToTemplate(array(
'posts' => $posts,
'page' => $page,
'pages' => $pages,
'preloadPage' => $preload,
'baseLink' => '/best',
));
$this->displayTemplate('main.twig');
}
private function loadPostsByRating($offset) {
$postsList = PostFactory::getPostsByRating($offset, self::PostPerPage);
return $this->buildPosts($postsList);
}
}
<file_sep><?php
require_once 'Post.php';
class PostFactory {
/**
* @var MongoCollection
*/
private static $collection = null;
public static function createPost(Post $post) {
self::setCollection();
self::$collection
->insert($post->getData());
}
private static function setCollection() {
if(is_null(self::$collection)) {
self::$collection = MongoAssist::GetCollection('posts');
}
}
public static function getPosts($offset, $limit) {
self::setCollection();
$cursor = self::$collection->find()
->sort(array('date' => -1))
->skip($offset)->limit($limit);
$result = array();
while($cursor->hasNext()) {
$result[] = new Post($cursor->getNext());
}
return $result;
}
public static function getCount($query = array()) {
self::setCollection();
return self::$collection->count($query);
}
public static function deletePost($id) {
self::setCollection();
$post = self::getPost($id);
self::deleteFiles($post);
self::$collection->remove(array('_id' => new MongoId($id)));
}
private static function deleteFiles(Post $post) {
$originFile = $_SERVER['DOCUMENT_ROOT'].'/../upload/'.$post->getFile();
$fullFile = $_SERVER['DOCUMENT_ROOT'].$post->getFullImage();
$smallFile = $_SERVER['DOCUMENT_ROOT'].$post->getSmallImage();
@unlink($originFile);
@unlink($fullFile);
@unlink($smallFile);
}
/**
* @param $id
*
* @return Post
*/
public static function getPost($id) {
self::setCollection();
return new Post(self::$collection->findOne(array('_id' => new MongoId($id))));
}
public static function getPostsByTitle($title, $offset, $limit) {
self::setCollection();
$cursor = self::$collection->find(array('title' => $title))
->sort(array('date' => -1))
->skip($offset)->limit($limit);
$result = array();
while($cursor->hasNext()) {
$result[] = new Post($cursor->getNext());
}
return $result;
}
public static function savePost(Post $post) {
self::setCollection();
self::$collection->save($post->getData());
}
public static function getPostsByIds($postIds, $offset, $limit) {
self::setCollection();
$cursor = self::$collection->find(array('_id' => array('$in' => $postIds)))
->sort(array('date' => -1))
->skip($offset)->limit($limit);
$result = array();
while($cursor->hasNext()) {
$result[] = new Post($cursor->getNext());
}
return $result;
}
public static function getPostsByRating($offset, $limit) {
self::setCollection();
$cursor = self::$collection->find()
->sort(array('rating' => -1))
->skip($offset)->limit($limit);
$result = array();
while($cursor->hasNext()) {
$result[] = new Post($cursor->getNext());
}
return $result;
}
}
| d88024f6349d3118afb331977a9d07a2cf7d4a60 | [
"JavaScript",
"PHP"
]
| 32 | PHP | theinpu/deveaque.com | 769d90ac33a00ed9e4c7a5a4bb89b42c8ae99d9c | c95ecb883d968ee35030016f662cb7dad5cf558a |
refs/heads/master | <repo_name>iterativo/aind-recognizer<file_sep>/my_model_selectors.py
import math
import statistics
import warnings
import numpy as np
from hmmlearn.hmm import GaussianHMM
from sklearn.model_selection import KFold
from asl_utils import combine_sequences
class ModelSelector(object):
'''
base class for model selection (strategy design pattern)
'''
def __init__(self, all_word_sequences: dict, all_word_Xlengths: dict, this_word: str,
n_constant=3,
min_n_components=2, max_n_components=10,
random_state=14, verbose=False):
self.words = all_word_sequences
self.hwords = all_word_Xlengths
self.sequences = all_word_sequences[this_word]
self.X, self.lengths = all_word_Xlengths[this_word]
self.this_word = this_word
self.n_constant = n_constant
self.min_n_components = min_n_components
self.max_n_components = max_n_components
self.random_state = random_state
self.verbose = verbose
def select(self):
raise NotImplementedError
def base_model(self, num_states):
# with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
# warnings.filterwarnings("ignore", category=RuntimeWarning)
try:
hmm_model = GaussianHMM(n_components=num_states, covariance_type="diag", n_iter=1000,
random_state=self.random_state, verbose=False).fit(self.X, self.lengths)
if self.verbose:
print("model created for {} with {} states".format(self.this_word, num_states))
return hmm_model
except:
if self.verbose:
print("failure on {} with {} states".format(self.this_word, num_states))
return None
class SelectorConstant(ModelSelector):
""" select the model with value self.n_constant
"""
def select(self):
""" select based on n_constant value
:return: GaussianHMM object
"""
best_num_components = self.n_constant
return self.base_model(best_num_components)
class SelectorBIC(ModelSelector):
""" select the model with the lowest Bayesian Information Criterion(BIC) score
http://www2.imm.dtu.dk/courses/02433/doc/ch6_slides.pdf
Bayesian information criteria: BIC = -2 * logL + p * logN
"""
def select(self):
""" select the best model for self.this_word based on
BIC score for n between self.min_n_components and self.max_n_components
:return: GaussianHMM object
"""
warnings.filterwarnings("ignore", category=DeprecationWarning)
best_score, best_model = float("-inf"), None
# DONE implement model selection based on BIC scores
for n in range(self.min_n_components, self.max_n_components + 1):
# Guard for exception thrown by hmmlearn bug as explained here:
# https://discussions.udacity.com/t/hmmlearn-valueerror-rows-of-transmat--must-sum-to-1-0/229995/4
try:
model = self.base_model(n)
logL = model.score(self.X, self.lengths)
# https://discussions.udacity.com/t/number-of-parameters-bic-calculation/233235/3
# Initial state occupation probabilities = numStates
# Transition probabilities = numStates*(numStates - 1)
# Emission probabilities = numStates*numFeatures*2 = numMeans+numCovars
# Parameters = Initial state occupation probabilities + Transition probabilities + Emission probabilities
p = n + (n * (n - 1)) + (n * self.X.shape[1] * 2)
logN = np.log(self.X.shape[0])
bic = p * logN - 2 * logL
# https://en.wikipedia.org/wiki/Bayesian_information_criterion
# The model with the lowest BIC is preferred
if bic < best_score:
best_score = bic
best_model = model
except:
continue
if best_model is None:
return self.base_model(self.n_constant)
return best_model
class SelectorDIC(ModelSelector):
''' select best model based on Discriminative Information Criterion
<NAME>. "A model selection criterion for classification: Application to hmm topology optimization."
Document Analysis and Recognition, 2003. Proceedings. Seventh International Conference on. IEEE, 2003.
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf
DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))
More on the meaning of this formula here:
https://discussions.udacity.com/t/dic-score-calculation/238907
- log(P(X(i)) is simply the log likelyhood (score) that is returned from
the model by calling model.score.
- log(P(X(j)); where j != i is just the model score when evaluating the
model on all words other than the word for which we are training this
particular model. 1/(M-1)SUM(log(P(X(all but i)) is simply the average
of the model scores for all other words.
'''
def select(self):
warnings.filterwarnings("ignore", category=DeprecationWarning)
# DONE implement model selection based on DIC scores
best_score, best_model = float("-inf"), None
for n in range(self.min_n_components, self.max_n_components + 1):
# Guard for exception thrown by hmmlearn bug as explained here:
# https://discussions.udacity.com/t/hmmlearn-valueerror-rows-of-transmat--must-sum-to-1-0/229995/4
try:
model = self.base_model(n)
logL = model.score(self.X, self.lengths)
other_logL_lst = []
for other_word in (w for w in self.hwords if w != self.this_word):
x, lengths = self.hwords[other_word]
other_logL_lst.append(model.score(x, lengths))
other_logL = np.average(other_logL_lst)
score = logL - other_logL
if score > best_score:
best_score = score
best_model = model
except:
continue
if best_model is None:
return self.base_model(self.n_constant)
return best_model
class SelectorCV(ModelSelector):
''' select best model based on average log Likelihood of cross-validation folds
'''
def select(self):
warnings.filterwarnings("ignore", category=DeprecationWarning)
# DONE implement model selection using CV
best_score, best_model = float("-inf"), None
n_splits = 2 # could be injected
# evaluate model for each n_components between min and max
for n in range(self.min_n_components, self.max_n_components + 1):
kfold = KFold(random_state=self.random_state, n_splits=n_splits)
# calculate average score for all splits and update best model
logL_lst = []
model = None
# Guard for exception thrown by hmmlearn bug as explained here:
# https://discussions.udacity.com/t/hmmlearn-valueerror-rows-of-transmat--must-sum-to-1-0/229995/4
try:
for train_index, test_index in kfold.split(self.sequences):
x_train, len_train = combine_sequences(train_index, self.sequences)
x_test, len_test = combine_sequences(test_index, self.sequences)
model = GaussianHMM(n_components=n, n_iter=1000).fit(x_train, len_train)
logL_lst.append(model.score(x_test, len_test))
except:
break
avg = np.average(logL_lst) if len(logL_lst) > 0 else float("-inf")
if avg > best_score:
best_score = avg
best_model = model
if best_model is None:
return self.base_model(self.n_constant)
return best_model
<file_sep>/asl_recognizer.html
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" />
<title>asl_recognizer</title><script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style type="text/css">
/*!
*
* Twitter Bootstrap
*
*/
/*!
* Bootstrap v3.3.7 (http://getbootstrap.com)
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
html {
font-family: sans-serif;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}
body {
margin: 0;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
audio,
canvas,
progress,
video {
display: inline-block;
vertical-align: baseline;
}
audio:not([controls]) {
display: none;
height: 0;
}
[hidden],
template {
display: none;
}
a {
background-color: transparent;
}
a:active,
a:hover {
outline: 0;
}
abbr[title] {
border-bottom: 1px dotted;
}
b,
strong {
font-weight: bold;
}
dfn {
font-style: italic;
}
h1 {
font-size: 2em;
margin: 0.67em 0;
}
mark {
background: #ff0;
color: #000;
}
small {
font-size: 80%;
}
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
img {
border: 0;
}
svg:not(:root) {
overflow: hidden;
}
figure {
margin: 1em 40px;
}
hr {
box-sizing: content-box;
height: 0;
}
pre {
overflow: auto;
}
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
button,
input,
optgroup,
select,
textarea {
color: inherit;
font: inherit;
margin: 0;
}
button {
overflow: visible;
}
button,
select {
text-transform: none;
}
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
cursor: pointer;
}
button[disabled],
html input[disabled] {
cursor: default;
}
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
input {
line-height: normal;
}
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box;
padding: 0;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
input[type="search"] {
-webkit-appearance: textfield;
box-sizing: content-box;
}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
legend {
border: 0;
padding: 0;
}
textarea {
overflow: auto;
}
optgroup {
font-weight: bold;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */
@media print {
*,
*:before,
*:after {
background: transparent !important;
color: #000 !important;
box-shadow: none !important;
text-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
a[href^="#"]:after,
a[href^="javascript:"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
.navbar {
display: none;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
}
.table td,
.table th {
background-color: #fff !important;
}
.table-bordered th,
.table-bordered td {
border: 1px solid #ddd !important;
}
}
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../components/bootstrap/fonts/glyphicons-halflings-regular.eot');
src: url('../components/bootstrap/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../components/bootstrap/fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../components/bootstrap/fonts/glyphicons-halflings-regular.woff') format('woff'), url('../components/bootstrap/fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../components/bootstrap/fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}
.glyphicon {
position: relative;
top: 1px;
display: inline-block;
font-family: 'Glyphicons Halflings';
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.glyphicon-asterisk:before {
content: "\002a";
}
.glyphicon-plus:before {
content: "\002b";
}
.glyphicon-euro:before,
.glyphicon-eur:before {
content: "\20ac";
}
.glyphicon-minus:before {
content: "\2212";
}
.glyphicon-cloud:before {
content: "\2601";
}
.glyphicon-envelope:before {
content: "\2709";
}
.glyphicon-pencil:before {
content: "\270f";
}
.glyphicon-glass:before {
content: "\e001";
}
.glyphicon-music:before {
content: "\e002";
}
.glyphicon-search:before {
content: "\e003";
}
.glyphicon-heart:before {
content: "\e005";
}
.glyphicon-star:before {
content: "\e006";
}
.glyphicon-star-empty:before {
content: "\e007";
}
.glyphicon-user:before {
content: "\e008";
}
.glyphicon-film:before {
content: "\e009";
}
.glyphicon-th-large:before {
content: "\e010";
}
.glyphicon-th:before {
content: "\e011";
}
.glyphicon-th-list:before {
content: "\e012";
}
.glyphicon-ok:before {
content: "\e013";
}
.glyphicon-remove:before {
content: "\e014";
}
.glyphicon-zoom-in:before {
content: "\e015";
}
.glyphicon-zoom-out:before {
content: "\e016";
}
.glyphicon-off:before {
content: "\e017";
}
.glyphicon-signal:before {
content: "\e018";
}
.glyphicon-cog:before {
content: "\e019";
}
.glyphicon-trash:before {
content: "\e020";
}
.glyphicon-home:before {
content: "\e021";
}
.glyphicon-file:before {
content: "\e022";
}
.glyphicon-time:before {
content: "\e023";
}
.glyphicon-road:before {
content: "\e024";
}
.glyphicon-download-alt:before {
content: "\e025";
}
.glyphicon-download:before {
content: "\e026";
}
.glyphicon-upload:before {
content: "\e027";
}
.glyphicon-inbox:before {
content: "\e028";
}
.glyphicon-play-circle:before {
content: "\e029";
}
.glyphicon-repeat:before {
content: "\e030";
}
.glyphicon-refresh:before {
content: "\e031";
}
.glyphicon-list-alt:before {
content: "\e032";
}
.glyphicon-lock:before {
content: "\e033";
}
.glyphicon-flag:before {
content: "\e034";
}
.glyphicon-headphones:before {
content: "\e035";
}
.glyphicon-volume-off:before {
content: "\e036";
}
.glyphicon-volume-down:before {
content: "\e037";
}
.glyphicon-volume-up:before {
content: "\e038";
}
.glyphicon-qrcode:before {
content: "\e039";
}
.glyphicon-barcode:before {
content: "\e040";
}
.glyphicon-tag:before {
content: "\e041";
}
.glyphicon-tags:before {
content: "\e042";
}
.glyphicon-book:before {
content: "\e043";
}
.glyphicon-bookmark:before {
content: "\e044";
}
.glyphicon-print:before {
content: "\e045";
}
.glyphicon-camera:before {
content: "\e046";
}
.glyphicon-font:before {
content: "\e047";
}
.glyphicon-bold:before {
content: "\e048";
}
.glyphicon-italic:before {
content: "\e049";
}
.glyphicon-text-height:before {
content: "\e050";
}
.glyphicon-text-width:before {
content: "\e051";
}
.glyphicon-align-left:before {
content: "\e052";
}
.glyphicon-align-center:before {
content: "\e053";
}
.glyphicon-align-right:before {
content: "\e054";
}
.glyphicon-align-justify:before {
content: "\e055";
}
.glyphicon-list:before {
content: "\e056";
}
.glyphicon-indent-left:before {
content: "\e057";
}
.glyphicon-indent-right:before {
content: "\e058";
}
.glyphicon-facetime-video:before {
content: "\e059";
}
.glyphicon-picture:before {
content: "\e060";
}
.glyphicon-map-marker:before {
content: "\e062";
}
.glyphicon-adjust:before {
content: "\e063";
}
.glyphicon-tint:before {
content: "\e064";
}
.glyphicon-edit:before {
content: "\e065";
}
.glyphicon-share:before {
content: "\e066";
}
.glyphicon-check:before {
content: "\e067";
}
.glyphicon-move:before {
content: "\e068";
}
.glyphicon-step-backward:before {
content: "\e069";
}
.glyphicon-fast-backward:before {
content: "\e070";
}
.glyphicon-backward:before {
content: "\e071";
}
.glyphicon-play:before {
content: "\e072";
}
.glyphicon-pause:before {
content: "\e073";
}
.glyphicon-stop:before {
content: "\e074";
}
.glyphicon-forward:before {
content: "\e075";
}
.glyphicon-fast-forward:before {
content: "\e076";
}
.glyphicon-step-forward:before {
content: "\e077";
}
.glyphicon-eject:before {
content: "\e078";
}
.glyphicon-chevron-left:before {
content: "\e079";
}
.glyphicon-chevron-right:before {
content: "\e080";
}
.glyphicon-plus-sign:before {
content: "\e081";
}
.glyphicon-minus-sign:before {
content: "\e082";
}
.glyphicon-remove-sign:before {
content: "\e083";
}
.glyphicon-ok-sign:before {
content: "\e084";
}
.glyphicon-question-sign:before {
content: "\e085";
}
.glyphicon-info-sign:before {
content: "\e086";
}
.glyphicon-screenshot:before {
content: "\e087";
}
.glyphicon-remove-circle:before {
content: "\e088";
}
.glyphicon-ok-circle:before {
content: "\e089";
}
.glyphicon-ban-circle:before {
content: "\e090";
}
.glyphicon-arrow-left:before {
content: "\e091";
}
.glyphicon-arrow-right:before {
content: "\e092";
}
.glyphicon-arrow-up:before {
content: "\e093";
}
.glyphicon-arrow-down:before {
content: "\e094";
}
.glyphicon-share-alt:before {
content: "\e095";
}
.glyphicon-resize-full:before {
content: "\e096";
}
.glyphicon-resize-small:before {
content: "\e097";
}
.glyphicon-exclamation-sign:before {
content: "\e101";
}
.glyphicon-gift:before {
content: "\e102";
}
.glyphicon-leaf:before {
content: "\e103";
}
.glyphicon-fire:before {
content: "\e104";
}
.glyphicon-eye-open:before {
content: "\e105";
}
.glyphicon-eye-close:before {
content: "\e106";
}
.glyphicon-warning-sign:before {
content: "\e107";
}
.glyphicon-plane:before {
content: "\e108";
}
.glyphicon-calendar:before {
content: "\e109";
}
.glyphicon-random:before {
content: "\e110";
}
.glyphicon-comment:before {
content: "\e111";
}
.glyphicon-magnet:before {
content: "\e112";
}
.glyphicon-chevron-up:before {
content: "\e113";
}
.glyphicon-chevron-down:before {
content: "\e114";
}
.glyphicon-retweet:before {
content: "\e115";
}
.glyphicon-shopping-cart:before {
content: "\e116";
}
.glyphicon-folder-close:before {
content: "\e117";
}
.glyphicon-folder-open:before {
content: "\e118";
}
.glyphicon-resize-vertical:before {
content: "\e119";
}
.glyphicon-resize-horizontal:before {
content: "\e120";
}
.glyphicon-hdd:before {
content: "\e121";
}
.glyphicon-bullhorn:before {
content: "\e122";
}
.glyphicon-bell:before {
content: "\e123";
}
.glyphicon-certificate:before {
content: "\e124";
}
.glyphicon-thumbs-up:before {
content: "\e125";
}
.glyphicon-thumbs-down:before {
content: "\e126";
}
.glyphicon-hand-right:before {
content: "\e127";
}
.glyphicon-hand-left:before {
content: "\e128";
}
.glyphicon-hand-up:before {
content: "\e129";
}
.glyphicon-hand-down:before {
content: "\e130";
}
.glyphicon-circle-arrow-right:before {
content: "\e131";
}
.glyphicon-circle-arrow-left:before {
content: "\e132";
}
.glyphicon-circle-arrow-up:before {
content: "\e133";
}
.glyphicon-circle-arrow-down:before {
content: "\e134";
}
.glyphicon-globe:before {
content: "\e135";
}
.glyphicon-wrench:before {
content: "\e136";
}
.glyphicon-tasks:before {
content: "\e137";
}
.glyphicon-filter:before {
content: "\e138";
}
.glyphicon-briefcase:before {
content: "\e139";
}
.glyphicon-fullscreen:before {
content: "\e140";
}
.glyphicon-dashboard:before {
content: "\e141";
}
.glyphicon-paperclip:before {
content: "\e142";
}
.glyphicon-heart-empty:before {
content: "\e143";
}
.glyphicon-link:before {
content: "\e144";
}
.glyphicon-phone:before {
content: "\e145";
}
.glyphicon-pushpin:before {
content: "\e146";
}
.glyphicon-usd:before {
content: "\e148";
}
.glyphicon-gbp:before {
content: "\e149";
}
.glyphicon-sort:before {
content: "\e150";
}
.glyphicon-sort-by-alphabet:before {
content: "\e151";
}
.glyphicon-sort-by-alphabet-alt:before {
content: "\e152";
}
.glyphicon-sort-by-order:before {
content: "\e153";
}
.glyphicon-sort-by-order-alt:before {
content: "\e154";
}
.glyphicon-sort-by-attributes:before {
content: "\e155";
}
.glyphicon-sort-by-attributes-alt:before {
content: "\e156";
}
.glyphicon-unchecked:before {
content: "\e157";
}
.glyphicon-expand:before {
content: "\e158";
}
.glyphicon-collapse-down:before {
content: "\e159";
}
.glyphicon-collapse-up:before {
content: "\e160";
}
.glyphicon-log-in:before {
content: "\e161";
}
.glyphicon-flash:before {
content: "\e162";
}
.glyphicon-log-out:before {
content: "\e163";
}
.glyphicon-new-window:before {
content: "\e164";
}
.glyphicon-record:before {
content: "\e165";
}
.glyphicon-save:before {
content: "\e166";
}
.glyphicon-open:before {
content: "\e167";
}
.glyphicon-saved:before {
content: "\e168";
}
.glyphicon-import:before {
content: "\e169";
}
.glyphicon-export:before {
content: "\e170";
}
.glyphicon-send:before {
content: "\e171";
}
.glyphicon-floppy-disk:before {
content: "\e172";
}
.glyphicon-floppy-saved:before {
content: "\e173";
}
.glyphicon-floppy-remove:before {
content: "\e174";
}
.glyphicon-floppy-save:before {
content: "\e175";
}
.glyphicon-floppy-open:before {
content: "\e176";
}
.glyphicon-credit-card:before {
content: "\e177";
}
.glyphicon-transfer:before {
content: "\e178";
}
.glyphicon-cutlery:before {
content: "\e179";
}
.glyphicon-header:before {
content: "\e180";
}
.glyphicon-compressed:before {
content: "\e181";
}
.glyphicon-earphone:before {
content: "\e182";
}
.glyphicon-phone-alt:before {
content: "\e183";
}
.glyphicon-tower:before {
content: "\e184";
}
.glyphicon-stats:before {
content: "\e185";
}
.glyphicon-sd-video:before {
content: "\e186";
}
.glyphicon-hd-video:before {
content: "\e187";
}
.glyphicon-subtitles:before {
content: "\e188";
}
.glyphicon-sound-stereo:before {
content: "\e189";
}
.glyphicon-sound-dolby:before {
content: "\e190";
}
.glyphicon-sound-5-1:before {
content: "\e191";
}
.glyphicon-sound-6-1:before {
content: "\e192";
}
.glyphicon-sound-7-1:before {
content: "\e193";
}
.glyphicon-copyright-mark:before {
content: "\e194";
}
.glyphicon-registration-mark:before {
content: "\e195";
}
.glyphicon-cloud-download:before {
content: "\e197";
}
.glyphicon-cloud-upload:before {
content: "\e198";
}
.glyphicon-tree-conifer:before {
content: "\e199";
}
.glyphicon-tree-deciduous:before {
content: "\e200";
}
.glyphicon-cd:before {
content: "\e201";
}
.glyphicon-save-file:before {
content: "\e202";
}
.glyphicon-open-file:before {
content: "\e203";
}
.glyphicon-level-up:before {
content: "\e204";
}
.glyphicon-copy:before {
content: "\e205";
}
.glyphicon-paste:before {
content: "\e206";
}
.glyphicon-alert:before {
content: "\e209";
}
.glyphicon-equalizer:before {
content: "\e210";
}
.glyphicon-king:before {
content: "\e211";
}
.glyphicon-queen:before {
content: "\e212";
}
.glyphicon-pawn:before {
content: "\e213";
}
.glyphicon-bishop:before {
content: "\e214";
}
.glyphicon-knight:before {
content: "\e215";
}
.glyphicon-baby-formula:before {
content: "\e216";
}
.glyphicon-tent:before {
content: "\26fa";
}
.glyphicon-blackboard:before {
content: "\e218";
}
.glyphicon-bed:before {
content: "\e219";
}
.glyphicon-apple:before {
content: "\f8ff";
}
.glyphicon-erase:before {
content: "\e221";
}
.glyphicon-hourglass:before {
content: "\231b";
}
.glyphicon-lamp:before {
content: "\e223";
}
.glyphicon-duplicate:before {
content: "\e224";
}
.glyphicon-piggy-bank:before {
content: "\e225";
}
.glyphicon-scissors:before {
content: "\e226";
}
.glyphicon-bitcoin:before {
content: "\e227";
}
.glyphicon-btc:before {
content: "\e227";
}
.glyphicon-xbt:before {
content: "\e227";
}
.glyphicon-yen:before {
content: "\00a5";
}
.glyphicon-jpy:before {
content: "\00a5";
}
.glyphicon-ruble:before {
content: "\20bd";
}
.glyphicon-rub:before {
content: "\20bd";
}
.glyphicon-scale:before {
content: "\e230";
}
.glyphicon-ice-lolly:before {
content: "\e231";
}
.glyphicon-ice-lolly-tasted:before {
content: "\e232";
}
.glyphicon-education:before {
content: "\e233";
}
.glyphicon-option-horizontal:before {
content: "\e234";
}
.glyphicon-option-vertical:before {
content: "\e235";
}
.glyphicon-menu-hamburger:before {
content: "\e236";
}
.glyphicon-modal-window:before {
content: "\e237";
}
.glyphicon-oil:before {
content: "\e238";
}
.glyphicon-grain:before {
content: "\e239";
}
.glyphicon-sunglasses:before {
content: "\e240";
}
.glyphicon-text-size:before {
content: "\e241";
}
.glyphicon-text-color:before {
content: "\e242";
}
.glyphicon-text-background:before {
content: "\e243";
}
.glyphicon-object-align-top:before {
content: "\e244";
}
.glyphicon-object-align-bottom:before {
content: "\e245";
}
.glyphicon-object-align-horizontal:before {
content: "\e246";
}
.glyphicon-object-align-left:before {
content: "\e247";
}
.glyphicon-object-align-vertical:before {
content: "\e248";
}
.glyphicon-object-align-right:before {
content: "\e249";
}
.glyphicon-triangle-right:before {
content: "\e250";
}
.glyphicon-triangle-left:before {
content: "\e251";
}
.glyphicon-triangle-bottom:before {
content: "\e252";
}
.glyphicon-triangle-top:before {
content: "\e253";
}
.glyphicon-console:before {
content: "\e254";
}
.glyphicon-superscript:before {
content: "\e255";
}
.glyphicon-subscript:before {
content: "\e256";
}
.glyphicon-menu-left:before {
content: "\e257";
}
.glyphicon-menu-right:before {
content: "\e258";
}
.glyphicon-menu-down:before {
content: "\e259";
}
.glyphicon-menu-up:before {
content: "\e260";
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html {
font-size: 10px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 13px;
line-height: 1.42857143;
color: #000;
background-color: #fff;
}
input,
button,
select,
textarea {
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
a {
color: #337ab7;
text-decoration: none;
}
a:hover,
a:focus {
color: #23527c;
text-decoration: underline;
}
a:focus {
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
figure {
margin: 0;
}
img {
vertical-align: middle;
}
.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
display: block;
max-width: 100%;
height: auto;
}
.img-rounded {
border-radius: 3px;
}
.img-thumbnail {
padding: 4px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 2px;
-webkit-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
display: inline-block;
max-width: 100%;
height: auto;
}
.img-circle {
border-radius: 50%;
}
hr {
margin-top: 18px;
margin-bottom: 18px;
border: 0;
border-top: 1px solid #eeeeee;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
.sr-only-focusable:active,
.sr-only-focusable:focus {
position: static;
width: auto;
height: auto;
margin: 0;
overflow: visible;
clip: auto;
}
[role="button"] {
cursor: pointer;
}
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
h1 small,
h2 small,
h3 small,
h4 small,
h5 small,
h6 small,
.h1 small,
.h2 small,
.h3 small,
.h4 small,
.h5 small,
.h6 small,
h1 .small,
h2 .small,
h3 .small,
h4 .small,
h5 .small,
h6 .small,
.h1 .small,
.h2 .small,
.h3 .small,
.h4 .small,
.h5 .small,
.h6 .small {
font-weight: normal;
line-height: 1;
color: #777777;
}
h1,
.h1,
h2,
.h2,
h3,
.h3 {
margin-top: 18px;
margin-bottom: 9px;
}
h1 small,
.h1 small,
h2 small,
.h2 small,
h3 small,
.h3 small,
h1 .small,
.h1 .small,
h2 .small,
.h2 .small,
h3 .small,
.h3 .small {
font-size: 65%;
}
h4,
.h4,
h5,
.h5,
h6,
.h6 {
margin-top: 9px;
margin-bottom: 9px;
}
h4 small,
.h4 small,
h5 small,
.h5 small,
h6 small,
.h6 small,
h4 .small,
.h4 .small,
h5 .small,
.h5 .small,
h6 .small,
.h6 .small {
font-size: 75%;
}
h1,
.h1 {
font-size: 33px;
}
h2,
.h2 {
font-size: 27px;
}
h3,
.h3 {
font-size: 23px;
}
h4,
.h4 {
font-size: 17px;
}
h5,
.h5 {
font-size: 13px;
}
h6,
.h6 {
font-size: 12px;
}
p {
margin: 0 0 9px;
}
.lead {
margin-bottom: 18px;
font-size: 14px;
font-weight: 300;
line-height: 1.4;
}
@media (min-width: 768px) {
.lead {
font-size: 19.5px;
}
}
small,
.small {
font-size: 92%;
}
mark,
.mark {
background-color: #fcf8e3;
padding: .2em;
}
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.text-justify {
text-align: justify;
}
.text-nowrap {
white-space: nowrap;
}
.text-lowercase {
text-transform: lowercase;
}
.text-uppercase {
text-transform: uppercase;
}
.text-capitalize {
text-transform: capitalize;
}
.text-muted {
color: #777777;
}
.text-primary {
color: #337ab7;
}
a.text-primary:hover,
a.text-primary:focus {
color: #286090;
}
.text-success {
color: #3c763d;
}
a.text-success:hover,
a.text-success:focus {
color: #2b542c;
}
.text-info {
color: #31708f;
}
a.text-info:hover,
a.text-info:focus {
color: #245269;
}
.text-warning {
color: #8a6d3b;
}
a.text-warning:hover,
a.text-warning:focus {
color: #66512c;
}
.text-danger {
color: #a94442;
}
a.text-danger:hover,
a.text-danger:focus {
color: #843534;
}
.bg-primary {
color: #fff;
background-color: #337ab7;
}
a.bg-primary:hover,
a.bg-primary:focus {
background-color: #286090;
}
.bg-success {
background-color: #dff0d8;
}
a.bg-success:hover,
a.bg-success:focus {
background-color: #c1e2b3;
}
.bg-info {
background-color: #d9edf7;
}
a.bg-info:hover,
a.bg-info:focus {
background-color: #afd9ee;
}
.bg-warning {
background-color: #fcf8e3;
}
a.bg-warning:hover,
a.bg-warning:focus {
background-color: #f7ecb5;
}
.bg-danger {
background-color: #f2dede;
}
a.bg-danger:hover,
a.bg-danger:focus {
background-color: #e4b9b9;
}
.page-header {
padding-bottom: 8px;
margin: 36px 0 18px;
border-bottom: 1px solid #eeeeee;
}
ul,
ol {
margin-top: 0;
margin-bottom: 9px;
}
ul ul,
ol ul,
ul ol,
ol ol {
margin-bottom: 0;
}
.list-unstyled {
padding-left: 0;
list-style: none;
}
.list-inline {
padding-left: 0;
list-style: none;
margin-left: -5px;
}
.list-inline > li {
display: inline-block;
padding-left: 5px;
padding-right: 5px;
}
dl {
margin-top: 0;
margin-bottom: 18px;
}
dt,
dd {
line-height: 1.42857143;
}
dt {
font-weight: bold;
}
dd {
margin-left: 0;
}
@media (min-width: 541px) {
.dl-horizontal dt {
float: left;
width: 160px;
clear: left;
text-align: right;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dl-horizontal dd {
margin-left: 180px;
}
}
abbr[title],
abbr[data-original-title] {
cursor: help;
border-bottom: 1px dotted #777777;
}
.initialism {
font-size: 90%;
text-transform: uppercase;
}
blockquote {
padding: 9px 18px;
margin: 0 0 18px;
font-size: inherit;
border-left: 5px solid #eeeeee;
}
blockquote p:last-child,
blockquote ul:last-child,
blockquote ol:last-child {
margin-bottom: 0;
}
blockquote footer,
blockquote small,
blockquote .small {
display: block;
font-size: 80%;
line-height: 1.42857143;
color: #777777;
}
blockquote footer:before,
blockquote small:before,
blockquote .small:before {
content: '\2014 \00A0';
}
.blockquote-reverse,
blockquote.pull-right {
padding-right: 15px;
padding-left: 0;
border-right: 5px solid #eeeeee;
border-left: 0;
text-align: right;
}
.blockquote-reverse footer:before,
blockquote.pull-right footer:before,
.blockquote-reverse small:before,
blockquote.pull-right small:before,
.blockquote-reverse .small:before,
blockquote.pull-right .small:before {
content: '';
}
.blockquote-reverse footer:after,
blockquote.pull-right footer:after,
.blockquote-reverse small:after,
blockquote.pull-right small:after,
.blockquote-reverse .small:after,
blockquote.pull-right .small:after {
content: '\00A0 \2014';
}
address {
margin-bottom: 18px;
font-style: normal;
line-height: 1.42857143;
}
code,
kbd,
pre,
samp {
font-family: monospace;
}
code {
padding: 2px 4px;
font-size: 90%;
color: #c7254e;
background-color: #f9f2f4;
border-radius: 2px;
}
kbd {
padding: 2px 4px;
font-size: 90%;
color: #888;
background-color: transparent;
border-radius: 1px;
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.25);
}
kbd kbd {
padding: 0;
font-size: 100%;
font-weight: bold;
box-shadow: none;
}
pre {
display: block;
padding: 8.5px;
margin: 0 0 9px;
font-size: 12px;
line-height: 1.42857143;
word-break: break-all;
word-wrap: break-word;
color: #333333;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 2px;
}
pre code {
padding: 0;
font-size: inherit;
color: inherit;
white-space: pre-wrap;
background-color: transparent;
border-radius: 0;
}
.pre-scrollable {
max-height: 340px;
overflow-y: scroll;
}
.container {
margin-right: auto;
margin-left: auto;
padding-left: 0px;
padding-right: 0px;
}
@media (min-width: 768px) {
.container {
width: 768px;
}
}
@media (min-width: 992px) {
.container {
width: 940px;
}
}
@media (min-width: 1200px) {
.container {
width: 1140px;
}
}
.container-fluid {
margin-right: auto;
margin-left: auto;
padding-left: 0px;
padding-right: 0px;
}
.row {
margin-left: 0px;
margin-right: 0px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
position: relative;
min-height: 1px;
padding-left: 0px;
padding-right: 0px;
}
.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {
float: left;
}
.col-xs-12 {
width: 100%;
}
.col-xs-11 {
width: 91.66666667%;
}
.col-xs-10 {
width: 83.33333333%;
}
.col-xs-9 {
width: 75%;
}
.col-xs-8 {
width: 66.66666667%;
}
.col-xs-7 {
width: 58.33333333%;
}
.col-xs-6 {
width: 50%;
}
.col-xs-5 {
width: 41.66666667%;
}
.col-xs-4 {
width: 33.33333333%;
}
.col-xs-3 {
width: 25%;
}
.col-xs-2 {
width: 16.66666667%;
}
.col-xs-1 {
width: 8.33333333%;
}
.col-xs-pull-12 {
right: 100%;
}
.col-xs-pull-11 {
right: 91.66666667%;
}
.col-xs-pull-10 {
right: 83.33333333%;
}
.col-xs-pull-9 {
right: 75%;
}
.col-xs-pull-8 {
right: 66.66666667%;
}
.col-xs-pull-7 {
right: 58.33333333%;
}
.col-xs-pull-6 {
right: 50%;
}
.col-xs-pull-5 {
right: 41.66666667%;
}
.col-xs-pull-4 {
right: 33.33333333%;
}
.col-xs-pull-3 {
right: 25%;
}
.col-xs-pull-2 {
right: 16.66666667%;
}
.col-xs-pull-1 {
right: 8.33333333%;
}
.col-xs-pull-0 {
right: auto;
}
.col-xs-push-12 {
left: 100%;
}
.col-xs-push-11 {
left: 91.66666667%;
}
.col-xs-push-10 {
left: 83.33333333%;
}
.col-xs-push-9 {
left: 75%;
}
.col-xs-push-8 {
left: 66.66666667%;
}
.col-xs-push-7 {
left: 58.33333333%;
}
.col-xs-push-6 {
left: 50%;
}
.col-xs-push-5 {
left: 41.66666667%;
}
.col-xs-push-4 {
left: 33.33333333%;
}
.col-xs-push-3 {
left: 25%;
}
.col-xs-push-2 {
left: 16.66666667%;
}
.col-xs-push-1 {
left: 8.33333333%;
}
.col-xs-push-0 {
left: auto;
}
.col-xs-offset-12 {
margin-left: 100%;
}
.col-xs-offset-11 {
margin-left: 91.66666667%;
}
.col-xs-offset-10 {
margin-left: 83.33333333%;
}
.col-xs-offset-9 {
margin-left: 75%;
}
.col-xs-offset-8 {
margin-left: 66.66666667%;
}
.col-xs-offset-7 {
margin-left: 58.33333333%;
}
.col-xs-offset-6 {
margin-left: 50%;
}
.col-xs-offset-5 {
margin-left: 41.66666667%;
}
.col-xs-offset-4 {
margin-left: 33.33333333%;
}
.col-xs-offset-3 {
margin-left: 25%;
}
.col-xs-offset-2 {
margin-left: 16.66666667%;
}
.col-xs-offset-1 {
margin-left: 8.33333333%;
}
.col-xs-offset-0 {
margin-left: 0%;
}
@media (min-width: 768px) {
.col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
float: left;
}
.col-sm-12 {
width: 100%;
}
.col-sm-11 {
width: 91.66666667%;
}
.col-sm-10 {
width: 83.33333333%;
}
.col-sm-9 {
width: 75%;
}
.col-sm-8 {
width: 66.66666667%;
}
.col-sm-7 {
width: 58.33333333%;
}
.col-sm-6 {
width: 50%;
}
.col-sm-5 {
width: 41.66666667%;
}
.col-sm-4 {
width: 33.33333333%;
}
.col-sm-3 {
width: 25%;
}
.col-sm-2 {
width: 16.66666667%;
}
.col-sm-1 {
width: 8.33333333%;
}
.col-sm-pull-12 {
right: 100%;
}
.col-sm-pull-11 {
right: 91.66666667%;
}
.col-sm-pull-10 {
right: 83.33333333%;
}
.col-sm-pull-9 {
right: 75%;
}
.col-sm-pull-8 {
right: 66.66666667%;
}
.col-sm-pull-7 {
right: 58.33333333%;
}
.col-sm-pull-6 {
right: 50%;
}
.col-sm-pull-5 {
right: 41.66666667%;
}
.col-sm-pull-4 {
right: 33.33333333%;
}
.col-sm-pull-3 {
right: 25%;
}
.col-sm-pull-2 {
right: 16.66666667%;
}
.col-sm-pull-1 {
right: 8.33333333%;
}
.col-sm-pull-0 {
right: auto;
}
.col-sm-push-12 {
left: 100%;
}
.col-sm-push-11 {
left: 91.66666667%;
}
.col-sm-push-10 {
left: 83.33333333%;
}
.col-sm-push-9 {
left: 75%;
}
.col-sm-push-8 {
left: 66.66666667%;
}
.col-sm-push-7 {
left: 58.33333333%;
}
.col-sm-push-6 {
left: 50%;
}
.col-sm-push-5 {
left: 41.66666667%;
}
.col-sm-push-4 {
left: 33.33333333%;
}
.col-sm-push-3 {
left: 25%;
}
.col-sm-push-2 {
left: 16.66666667%;
}
.col-sm-push-1 {
left: 8.33333333%;
}
.col-sm-push-0 {
left: auto;
}
.col-sm-offset-12 {
margin-left: 100%;
}
.col-sm-offset-11 {
margin-left: 91.66666667%;
}
.col-sm-offset-10 {
margin-left: 83.33333333%;
}
.col-sm-offset-9 {
margin-left: 75%;
}
.col-sm-offset-8 {
margin-left: 66.66666667%;
}
.col-sm-offset-7 {
margin-left: 58.33333333%;
}
.col-sm-offset-6 {
margin-left: 50%;
}
.col-sm-offset-5 {
margin-left: 41.66666667%;
}
.col-sm-offset-4 {
margin-left: 33.33333333%;
}
.col-sm-offset-3 {
margin-left: 25%;
}
.col-sm-offset-2 {
margin-left: 16.66666667%;
}
.col-sm-offset-1 {
margin-left: 8.33333333%;
}
.col-sm-offset-0 {
margin-left: 0%;
}
}
@media (min-width: 992px) {
.col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
float: left;
}
.col-md-12 {
width: 100%;
}
.col-md-11 {
width: 91.66666667%;
}
.col-md-10 {
width: 83.33333333%;
}
.col-md-9 {
width: 75%;
}
.col-md-8 {
width: 66.66666667%;
}
.col-md-7 {
width: 58.33333333%;
}
.col-md-6 {
width: 50%;
}
.col-md-5 {
width: 41.66666667%;
}
.col-md-4 {
width: 33.33333333%;
}
.col-md-3 {
width: 25%;
}
.col-md-2 {
width: 16.66666667%;
}
.col-md-1 {
width: 8.33333333%;
}
.col-md-pull-12 {
right: 100%;
}
.col-md-pull-11 {
right: 91.66666667%;
}
.col-md-pull-10 {
right: 83.33333333%;
}
.col-md-pull-9 {
right: 75%;
}
.col-md-pull-8 {
right: 66.66666667%;
}
.col-md-pull-7 {
right: 58.33333333%;
}
.col-md-pull-6 {
right: 50%;
}
.col-md-pull-5 {
right: 41.66666667%;
}
.col-md-pull-4 {
right: 33.33333333%;
}
.col-md-pull-3 {
right: 25%;
}
.col-md-pull-2 {
right: 16.66666667%;
}
.col-md-pull-1 {
right: 8.33333333%;
}
.col-md-pull-0 {
right: auto;
}
.col-md-push-12 {
left: 100%;
}
.col-md-push-11 {
left: 91.66666667%;
}
.col-md-push-10 {
left: 83.33333333%;
}
.col-md-push-9 {
left: 75%;
}
.col-md-push-8 {
left: 66.66666667%;
}
.col-md-push-7 {
left: 58.33333333%;
}
.col-md-push-6 {
left: 50%;
}
.col-md-push-5 {
left: 41.66666667%;
}
.col-md-push-4 {
left: 33.33333333%;
}
.col-md-push-3 {
left: 25%;
}
.col-md-push-2 {
left: 16.66666667%;
}
.col-md-push-1 {
left: 8.33333333%;
}
.col-md-push-0 {
left: auto;
}
.col-md-offset-12 {
margin-left: 100%;
}
.col-md-offset-11 {
margin-left: 91.66666667%;
}
.col-md-offset-10 {
margin-left: 83.33333333%;
}
.col-md-offset-9 {
margin-left: 75%;
}
.col-md-offset-8 {
margin-left: 66.66666667%;
}
.col-md-offset-7 {
margin-left: 58.33333333%;
}
.col-md-offset-6 {
margin-left: 50%;
}
.col-md-offset-5 {
margin-left: 41.66666667%;
}
.col-md-offset-4 {
margin-left: 33.33333333%;
}
.col-md-offset-3 {
margin-left: 25%;
}
.col-md-offset-2 {
margin-left: 16.66666667%;
}
.col-md-offset-1 {
margin-left: 8.33333333%;
}
.col-md-offset-0 {
margin-left: 0%;
}
}
@media (min-width: 1200px) {
.col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
float: left;
}
.col-lg-12 {
width: 100%;
}
.col-lg-11 {
width: 91.66666667%;
}
.col-lg-10 {
width: 83.33333333%;
}
.col-lg-9 {
width: 75%;
}
.col-lg-8 {
width: 66.66666667%;
}
.col-lg-7 {
width: 58.33333333%;
}
.col-lg-6 {
width: 50%;
}
.col-lg-5 {
width: 41.66666667%;
}
.col-lg-4 {
width: 33.33333333%;
}
.col-lg-3 {
width: 25%;
}
.col-lg-2 {
width: 16.66666667%;
}
.col-lg-1 {
width: 8.33333333%;
}
.col-lg-pull-12 {
right: 100%;
}
.col-lg-pull-11 {
right: 91.66666667%;
}
.col-lg-pull-10 {
right: 83.33333333%;
}
.col-lg-pull-9 {
right: 75%;
}
.col-lg-pull-8 {
right: 66.66666667%;
}
.col-lg-pull-7 {
right: 58.33333333%;
}
.col-lg-pull-6 {
right: 50%;
}
.col-lg-pull-5 {
right: 41.66666667%;
}
.col-lg-pull-4 {
right: 33.33333333%;
}
.col-lg-pull-3 {
right: 25%;
}
.col-lg-pull-2 {
right: 16.66666667%;
}
.col-lg-pull-1 {
right: 8.33333333%;
}
.col-lg-pull-0 {
right: auto;
}
.col-lg-push-12 {
left: 100%;
}
.col-lg-push-11 {
left: 91.66666667%;
}
.col-lg-push-10 {
left: 83.33333333%;
}
.col-lg-push-9 {
left: 75%;
}
.col-lg-push-8 {
left: 66.66666667%;
}
.col-lg-push-7 {
left: 58.33333333%;
}
.col-lg-push-6 {
left: 50%;
}
.col-lg-push-5 {
left: 41.66666667%;
}
.col-lg-push-4 {
left: 33.33333333%;
}
.col-lg-push-3 {
left: 25%;
}
.col-lg-push-2 {
left: 16.66666667%;
}
.col-lg-push-1 {
left: 8.33333333%;
}
.col-lg-push-0 {
left: auto;
}
.col-lg-offset-12 {
margin-left: 100%;
}
.col-lg-offset-11 {
margin-left: 91.66666667%;
}
.col-lg-offset-10 {
margin-left: 83.33333333%;
}
.col-lg-offset-9 {
margin-left: 75%;
}
.col-lg-offset-8 {
margin-left: 66.66666667%;
}
.col-lg-offset-7 {
margin-left: 58.33333333%;
}
.col-lg-offset-6 {
margin-left: 50%;
}
.col-lg-offset-5 {
margin-left: 41.66666667%;
}
.col-lg-offset-4 {
margin-left: 33.33333333%;
}
.col-lg-offset-3 {
margin-left: 25%;
}
.col-lg-offset-2 {
margin-left: 16.66666667%;
}
.col-lg-offset-1 {
margin-left: 8.33333333%;
}
.col-lg-offset-0 {
margin-left: 0%;
}
}
table {
background-color: transparent;
}
caption {
padding-top: 8px;
padding-bottom: 8px;
color: #777777;
text-align: left;
}
th {
text-align: left;
}
.table {
width: 100%;
max-width: 100%;
margin-bottom: 18px;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
border-top: 1px solid #ddd;
}
.table > thead > tr > th {
vertical-align: bottom;
border-bottom: 2px solid #ddd;
}
.table > caption + thead > tr:first-child > th,
.table > colgroup + thead > tr:first-child > th,
.table > thead:first-child > tr:first-child > th,
.table > caption + thead > tr:first-child > td,
.table > colgroup + thead > tr:first-child > td,
.table > thead:first-child > tr:first-child > td {
border-top: 0;
}
.table > tbody + tbody {
border-top: 2px solid #ddd;
}
.table .table {
background-color: #fff;
}
.table-condensed > thead > tr > th,
.table-condensed > tbody > tr > th,
.table-condensed > tfoot > tr > th,
.table-condensed > thead > tr > td,
.table-condensed > tbody > tr > td,
.table-condensed > tfoot > tr > td {
padding: 5px;
}
.table-bordered {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > thead > tr > td {
border-bottom-width: 2px;
}
.table-striped > tbody > tr:nth-of-type(odd) {
background-color: #f9f9f9;
}
.table-hover > tbody > tr:hover {
background-color: #f5f5f5;
}
table col[class*="col-"] {
position: static;
float: none;
display: table-column;
}
table td[class*="col-"],
table th[class*="col-"] {
position: static;
float: none;
display: table-cell;
}
.table > thead > tr > td.active,
.table > tbody > tr > td.active,
.table > tfoot > tr > td.active,
.table > thead > tr > th.active,
.table > tbody > tr > th.active,
.table > tfoot > tr > th.active,
.table > thead > tr.active > td,
.table > tbody > tr.active > td,
.table > tfoot > tr.active > td,
.table > thead > tr.active > th,
.table > tbody > tr.active > th,
.table > tfoot > tr.active > th {
background-color: #f5f5f5;
}
.table-hover > tbody > tr > td.active:hover,
.table-hover > tbody > tr > th.active:hover,
.table-hover > tbody > tr.active:hover > td,
.table-hover > tbody > tr:hover > .active,
.table-hover > tbody > tr.active:hover > th {
background-color: #e8e8e8;
}
.table > thead > tr > td.success,
.table > tbody > tr > td.success,
.table > tfoot > tr > td.success,
.table > thead > tr > th.success,
.table > tbody > tr > th.success,
.table > tfoot > tr > th.success,
.table > thead > tr.success > td,
.table > tbody > tr.success > td,
.table > tfoot > tr.success > td,
.table > thead > tr.success > th,
.table > tbody > tr.success > th,
.table > tfoot > tr.success > th {
background-color: #dff0d8;
}
.table-hover > tbody > tr > td.success:hover,
.table-hover > tbody > tr > th.success:hover,
.table-hover > tbody > tr.success:hover > td,
.table-hover > tbody > tr:hover > .success,
.table-hover > tbody > tr.success:hover > th {
background-color: #d0e9c6;
}
.table > thead > tr > td.info,
.table > tbody > tr > td.info,
.table > tfoot > tr > td.info,
.table > thead > tr > th.info,
.table > tbody > tr > th.info,
.table > tfoot > tr > th.info,
.table > thead > tr.info > td,
.table > tbody > tr.info > td,
.table > tfoot > tr.info > td,
.table > thead > tr.info > th,
.table > tbody > tr.info > th,
.table > tfoot > tr.info > th {
background-color: #d9edf7;
}
.table-hover > tbody > tr > td.info:hover,
.table-hover > tbody > tr > th.info:hover,
.table-hover > tbody > tr.info:hover > td,
.table-hover > tbody > tr:hover > .info,
.table-hover > tbody > tr.info:hover > th {
background-color: #c4e3f3;
}
.table > thead > tr > td.warning,
.table > tbody > tr > td.warning,
.table > tfoot > tr > td.warning,
.table > thead > tr > th.warning,
.table > tbody > tr > th.warning,
.table > tfoot > tr > th.warning,
.table > thead > tr.warning > td,
.table > tbody > tr.warning > td,
.table > tfoot > tr.warning > td,
.table > thead > tr.warning > th,
.table > tbody > tr.warning > th,
.table > tfoot > tr.warning > th {
background-color: #fcf8e3;
}
.table-hover > tbody > tr > td.warning:hover,
.table-hover > tbody > tr > th.warning:hover,
.table-hover > tbody > tr.warning:hover > td,
.table-hover > tbody > tr:hover > .warning,
.table-hover > tbody > tr.warning:hover > th {
background-color: #faf2cc;
}
.table > thead > tr > td.danger,
.table > tbody > tr > td.danger,
.table > tfoot > tr > td.danger,
.table > thead > tr > th.danger,
.table > tbody > tr > th.danger,
.table > tfoot > tr > th.danger,
.table > thead > tr.danger > td,
.table > tbody > tr.danger > td,
.table > tfoot > tr.danger > td,
.table > thead > tr.danger > th,
.table > tbody > tr.danger > th,
.table > tfoot > tr.danger > th {
background-color: #f2dede;
}
.table-hover > tbody > tr > td.danger:hover,
.table-hover > tbody > tr > th.danger:hover,
.table-hover > tbody > tr.danger:hover > td,
.table-hover > tbody > tr:hover > .danger,
.table-hover > tbody > tr.danger:hover > th {
background-color: #ebcccc;
}
.table-responsive {
overflow-x: auto;
min-height: 0.01%;
}
@media screen and (max-width: 767px) {
.table-responsive {
width: 100%;
margin-bottom: 13.5px;
overflow-y: hidden;
-ms-overflow-style: -ms-autohiding-scrollbar;
border: 1px solid #ddd;
}
.table-responsive > .table {
margin-bottom: 0;
}
.table-responsive > .table > thead > tr > th,
.table-responsive > .table > tbody > tr > th,
.table-responsive > .table > tfoot > tr > th,
.table-responsive > .table > thead > tr > td,
.table-responsive > .table > tbody > tr > td,
.table-responsive > .table > tfoot > tr > td {
white-space: nowrap;
}
.table-responsive > .table-bordered {
border: 0;
}
.table-responsive > .table-bordered > thead > tr > th:first-child,
.table-responsive > .table-bordered > tbody > tr > th:first-child,
.table-responsive > .table-bordered > tfoot > tr > th:first-child,
.table-responsive > .table-bordered > thead > tr > td:first-child,
.table-responsive > .table-bordered > tbody > tr > td:first-child,
.table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.table-responsive > .table-bordered > thead > tr > th:last-child,
.table-responsive > .table-bordered > tbody > tr > th:last-child,
.table-responsive > .table-bordered > tfoot > tr > th:last-child,
.table-responsive > .table-bordered > thead > tr > td:last-child,
.table-responsive > .table-bordered > tbody > tr > td:last-child,
.table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.table-responsive > .table-bordered > tbody > tr:last-child > th,
.table-responsive > .table-bordered > tfoot > tr:last-child > th,
.table-responsive > .table-bordered > tbody > tr:last-child > td,
.table-responsive > .table-bordered > tfoot > tr:last-child > td {
border-bottom: 0;
}
}
fieldset {
padding: 0;
margin: 0;
border: 0;
min-width: 0;
}
legend {
display: block;
width: 100%;
padding: 0;
margin-bottom: 18px;
font-size: 19.5px;
line-height: inherit;
color: #333333;
border: 0;
border-bottom: 1px solid #e5e5e5;
}
label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
font-weight: bold;
}
input[type="search"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
input[type="radio"],
input[type="checkbox"] {
margin: 4px 0 0;
margin-top: 1px \9;
line-height: normal;
}
input[type="file"] {
display: block;
}
input[type="range"] {
display: block;
width: 100%;
}
select[multiple],
select[size] {
height: auto;
}
input[type="file"]:focus,
input[type="radio"]:focus,
input[type="checkbox"]:focus {
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
output {
display: block;
padding-top: 7px;
font-size: 13px;
line-height: 1.42857143;
color: #555555;
}
.form-control {
display: block;
width: 100%;
height: 32px;
padding: 6px 12px;
font-size: 13px;
line-height: 1.42857143;
color: #555555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 2px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.form-control:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
.form-control::-moz-placeholder {
color: #999;
opacity: 1;
}
.form-control:-ms-input-placeholder {
color: #999;
}
.form-control::-webkit-input-placeholder {
color: #999;
}
.form-control::-ms-expand {
border: 0;
background-color: transparent;
}
.form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
background-color: #eeeeee;
opacity: 1;
}
.form-control[disabled],
fieldset[disabled] .form-control {
cursor: not-allowed;
}
textarea.form-control {
height: auto;
}
input[type="search"] {
-webkit-appearance: none;
}
@media screen and (-webkit-min-device-pixel-ratio: 0) {
input[type="date"].form-control,
input[type="time"].form-control,
input[type="datetime-local"].form-control,
input[type="month"].form-control {
line-height: 32px;
}
input[type="date"].input-sm,
input[type="time"].input-sm,
input[type="datetime-local"].input-sm,
input[type="month"].input-sm,
.input-group-sm input[type="date"],
.input-group-sm input[type="time"],
.input-group-sm input[type="datetime-local"],
.input-group-sm input[type="month"] {
line-height: 30px;
}
input[type="date"].input-lg,
input[type="time"].input-lg,
input[type="datetime-local"].input-lg,
input[type="month"].input-lg,
.input-group-lg input[type="date"],
.input-group-lg input[type="time"],
.input-group-lg input[type="datetime-local"],
.input-group-lg input[type="month"] {
line-height: 45px;
}
}
.form-group {
margin-bottom: 15px;
}
.radio,
.checkbox {
position: relative;
display: block;
margin-top: 10px;
margin-bottom: 10px;
}
.radio label,
.checkbox label {
min-height: 18px;
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
cursor: pointer;
}
.radio input[type="radio"],
.radio-inline input[type="radio"],
.checkbox input[type="checkbox"],
.checkbox-inline input[type="checkbox"] {
position: absolute;
margin-left: -20px;
margin-top: 4px \9;
}
.radio + .radio,
.checkbox + .checkbox {
margin-top: -5px;
}
.radio-inline,
.checkbox-inline {
position: relative;
display: inline-block;
padding-left: 20px;
margin-bottom: 0;
vertical-align: middle;
font-weight: normal;
cursor: pointer;
}
.radio-inline + .radio-inline,
.checkbox-inline + .checkbox-inline {
margin-top: 0;
margin-left: 10px;
}
input[type="radio"][disabled],
input[type="checkbox"][disabled],
input[type="radio"].disabled,
input[type="checkbox"].disabled,
fieldset[disabled] input[type="radio"],
fieldset[disabled] input[type="checkbox"] {
cursor: not-allowed;
}
.radio-inline.disabled,
.checkbox-inline.disabled,
fieldset[disabled] .radio-inline,
fieldset[disabled] .checkbox-inline {
cursor: not-allowed;
}
.radio.disabled label,
.checkbox.disabled label,
fieldset[disabled] .radio label,
fieldset[disabled] .checkbox label {
cursor: not-allowed;
}
.form-control-static {
padding-top: 7px;
padding-bottom: 7px;
margin-bottom: 0;
min-height: 31px;
}
.form-control-static.input-lg,
.form-control-static.input-sm {
padding-left: 0;
padding-right: 0;
}
.input-sm {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 1px;
}
select.input-sm {
height: 30px;
line-height: 30px;
}
textarea.input-sm,
select[multiple].input-sm {
height: auto;
}
.form-group-sm .form-control {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 1px;
}
.form-group-sm select.form-control {
height: 30px;
line-height: 30px;
}
.form-group-sm textarea.form-control,
.form-group-sm select[multiple].form-control {
height: auto;
}
.form-group-sm .form-control-static {
height: 30px;
min-height: 30px;
padding: 6px 10px;
font-size: 12px;
line-height: 1.5;
}
.input-lg {
height: 45px;
padding: 10px 16px;
font-size: 17px;
line-height: 1.3333333;
border-radius: 3px;
}
select.input-lg {
height: 45px;
line-height: 45px;
}
textarea.input-lg,
select[multiple].input-lg {
height: auto;
}
.form-group-lg .form-control {
height: 45px;
padding: 10px 16px;
font-size: 17px;
line-height: 1.3333333;
border-radius: 3px;
}
.form-group-lg select.form-control {
height: 45px;
line-height: 45px;
}
.form-group-lg textarea.form-control,
.form-group-lg select[multiple].form-control {
height: auto;
}
.form-group-lg .form-control-static {
height: 45px;
min-height: 35px;
padding: 11px 16px;
font-size: 17px;
line-height: 1.3333333;
}
.has-feedback {
position: relative;
}
.has-feedback .form-control {
padding-right: 40px;
}
.form-control-feedback {
position: absolute;
top: 0;
right: 0;
z-index: 2;
display: block;
width: 32px;
height: 32px;
line-height: 32px;
text-align: center;
pointer-events: none;
}
.input-lg + .form-control-feedback,
.input-group-lg + .form-control-feedback,
.form-group-lg .form-control + .form-control-feedback {
width: 45px;
height: 45px;
line-height: 45px;
}
.input-sm + .form-control-feedback,
.input-group-sm + .form-control-feedback,
.form-group-sm .form-control + .form-control-feedback {
width: 30px;
height: 30px;
line-height: 30px;
}
.has-success .help-block,
.has-success .control-label,
.has-success .radio,
.has-success .checkbox,
.has-success .radio-inline,
.has-success .checkbox-inline,
.has-success.radio label,
.has-success.checkbox label,
.has-success.radio-inline label,
.has-success.checkbox-inline label {
color: #3c763d;
}
.has-success .form-control {
border-color: #3c763d;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-success .form-control:focus {
border-color: #2b542c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168;
}
.has-success .input-group-addon {
color: #3c763d;
border-color: #3c763d;
background-color: #dff0d8;
}
.has-success .form-control-feedback {
color: #3c763d;
}
.has-warning .help-block,
.has-warning .control-label,
.has-warning .radio,
.has-warning .checkbox,
.has-warning .radio-inline,
.has-warning .checkbox-inline,
.has-warning.radio label,
.has-warning.checkbox label,
.has-warning.radio-inline label,
.has-warning.checkbox-inline label {
color: #8a6d3b;
}
.has-warning .form-control {
border-color: #8a6d3b;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-warning .form-control:focus {
border-color: #66512c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b;
}
.has-warning .input-group-addon {
color: #8a6d3b;
border-color: #8a6d3b;
background-color: #fcf8e3;
}
.has-warning .form-control-feedback {
color: #8a6d3b;
}
.has-error .help-block,
.has-error .control-label,
.has-error .radio,
.has-error .checkbox,
.has-error .radio-inline,
.has-error .checkbox-inline,
.has-error.radio label,
.has-error.checkbox label,
.has-error.radio-inline label,
.has-error.checkbox-inline label {
color: #a94442;
}
.has-error .form-control {
border-color: #a94442;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-error .form-control:focus {
border-color: #843534;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483;
}
.has-error .input-group-addon {
color: #a94442;
border-color: #a94442;
background-color: #f2dede;
}
.has-error .form-control-feedback {
color: #a94442;
}
.has-feedback label ~ .form-control-feedback {
top: 23px;
}
.has-feedback label.sr-only ~ .form-control-feedback {
top: 0;
}
.help-block {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #404040;
}
@media (min-width: 768px) {
.form-inline .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.form-inline .form-control-static {
display: inline-block;
}
.form-inline .input-group {
display: inline-table;
vertical-align: middle;
}
.form-inline .input-group .input-group-addon,
.form-inline .input-group .input-group-btn,
.form-inline .input-group .form-control {
width: auto;
}
.form-inline .input-group > .form-control {
width: 100%;
}
.form-inline .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio,
.form-inline .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio label,
.form-inline .checkbox label {
padding-left: 0;
}
.form-inline .radio input[type="radio"],
.form-inline .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.form-inline .has-feedback .form-control-feedback {
top: 0;
}
}
.form-horizontal .radio,
.form-horizontal .checkbox,
.form-horizontal .radio-inline,
.form-horizontal .checkbox-inline {
margin-top: 0;
margin-bottom: 0;
padding-top: 7px;
}
.form-horizontal .radio,
.form-horizontal .checkbox {
min-height: 25px;
}
.form-horizontal .form-group {
margin-left: 0px;
margin-right: 0px;
}
@media (min-width: 768px) {
.form-horizontal .control-label {
text-align: right;
margin-bottom: 0;
padding-top: 7px;
}
}
.form-horizontal .has-feedback .form-control-feedback {
right: 0px;
}
@media (min-width: 768px) {
.form-horizontal .form-group-lg .control-label {
padding-top: 11px;
font-size: 17px;
}
}
@media (min-width: 768px) {
.form-horizontal .form-group-sm .control-label {
padding-top: 6px;
font-size: 12px;
}
}
.btn {
display: inline-block;
margin-bottom: 0;
font-weight: normal;
text-align: center;
vertical-align: middle;
touch-action: manipulation;
cursor: pointer;
background-image: none;
border: 1px solid transparent;
white-space: nowrap;
padding: 6px 12px;
font-size: 13px;
line-height: 1.42857143;
border-radius: 2px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.btn:focus,
.btn:active:focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn.active.focus {
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
.btn:hover,
.btn:focus,
.btn.focus {
color: #333;
text-decoration: none;
}
.btn:active,
.btn.active {
outline: 0;
background-image: none;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
.btn.disabled,
.btn[disabled],
fieldset[disabled] .btn {
cursor: not-allowed;
opacity: 0.65;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
}
a.btn.disabled,
fieldset[disabled] a.btn {
pointer-events: none;
}
.btn-default {
color: #333;
background-color: #fff;
border-color: #ccc;
}
.btn-default:focus,
.btn-default.focus {
color: #333;
background-color: #e6e6e6;
border-color: #8c8c8c;
}
.btn-default:hover {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
.btn-default:active:hover,
.btn-default.active:hover,
.open > .dropdown-toggle.btn-default:hover,
.btn-default:active:focus,
.btn-default.active:focus,
.open > .dropdown-toggle.btn-default:focus,
.btn-default:active.focus,
.btn-default.active.focus,
.open > .dropdown-toggle.btn-default.focus {
color: #333;
background-color: #d4d4d4;
border-color: #8c8c8c;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
background-image: none;
}
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled.focus,
.btn-default[disabled].focus,
fieldset[disabled] .btn-default.focus {
background-color: #fff;
border-color: #ccc;
}
.btn-default .badge {
color: #fff;
background-color: #333;
}
.btn-primary {
color: #fff;
background-color: #337ab7;
border-color: #2e6da4;
}
.btn-primary:focus,
.btn-primary.focus {
color: #fff;
background-color: #286090;
border-color: #122b40;
}
.btn-primary:hover {
color: #fff;
background-color: #286090;
border-color: #204d74;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
color: #fff;
background-color: #286090;
border-color: #204d74;
}
.btn-primary:active:hover,
.btn-primary.active:hover,
.open > .dropdown-toggle.btn-primary:hover,
.btn-primary:active:focus,
.btn-primary.active:focus,
.open > .dropdown-toggle.btn-primary:focus,
.btn-primary:active.focus,
.btn-primary.active.focus,
.open > .dropdown-toggle.btn-primary.focus {
color: #fff;
background-color: #204d74;
border-color: #122b40;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
background-image: none;
}
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled.focus,
.btn-primary[disabled].focus,
fieldset[disabled] .btn-primary.focus {
background-color: #337ab7;
border-color: #2e6da4;
}
.btn-primary .badge {
color: #337ab7;
background-color: #fff;
}
.btn-success {
color: #fff;
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success:focus,
.btn-success.focus {
color: #fff;
background-color: #449d44;
border-color: #255625;
}
.btn-success:hover {
color: #fff;
background-color: #449d44;
border-color: #398439;
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
color: #fff;
background-color: #449d44;
border-color: #398439;
}
.btn-success:active:hover,
.btn-success.active:hover,
.open > .dropdown-toggle.btn-success:hover,
.btn-success:active:focus,
.btn-success.active:focus,
.open > .dropdown-toggle.btn-success:focus,
.btn-success:active.focus,
.btn-success.active.focus,
.open > .dropdown-toggle.btn-success.focus {
color: #fff;
background-color: #398439;
border-color: #255625;
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
background-image: none;
}
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled.focus,
.btn-success[disabled].focus,
fieldset[disabled] .btn-success.focus {
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success .badge {
color: #5cb85c;
background-color: #fff;
}
.btn-info {
color: #fff;
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info:focus,
.btn-info.focus {
color: #fff;
background-color: #31b0d5;
border-color: #1b6d85;
}
.btn-info:hover {
color: #fff;
background-color: #31b0d5;
border-color: #269abc;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
color: #fff;
background-color: #31b0d5;
border-color: #269abc;
}
.btn-info:active:hover,
.btn-info.active:hover,
.open > .dropdown-toggle.btn-info:hover,
.btn-info:active:focus,
.btn-info.active:focus,
.open > .dropdown-toggle.btn-info:focus,
.btn-info:active.focus,
.btn-info.active.focus,
.open > .dropdown-toggle.btn-info.focus {
color: #fff;
background-color: #269abc;
border-color: #1b6d85;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
background-image: none;
}
.btn-info.disabled:hover,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info:hover,
.btn-info.disabled:focus,
.btn-info[disabled]:focus,
fieldset[disabled] .btn-info:focus,
.btn-info.disabled.focus,
.btn-info[disabled].focus,
fieldset[disabled] .btn-info.focus {
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info .badge {
color: #5bc0de;
background-color: #fff;
}
.btn-warning {
color: #fff;
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning:focus,
.btn-warning.focus {
color: #fff;
background-color: #ec971f;
border-color: #985f0d;
}
.btn-warning:hover {
color: #fff;
background-color: #ec971f;
border-color: #d58512;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
color: #fff;
background-color: #ec971f;
border-color: #d58512;
}
.btn-warning:active:hover,
.btn-warning.active:hover,
.open > .dropdown-toggle.btn-warning:hover,
.btn-warning:active:focus,
.btn-warning.active:focus,
.open > .dropdown-toggle.btn-warning:focus,
.btn-warning:active.focus,
.btn-warning.active.focus,
.open > .dropdown-toggle.btn-warning.focus {
color: #fff;
background-color: #d58512;
border-color: #985f0d;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
background-image: none;
}
.btn-warning.disabled:hover,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning:hover,
.btn-warning.disabled:focus,
.btn-warning[disabled]:focus,
fieldset[disabled] .btn-warning:focus,
.btn-warning.disabled.focus,
.btn-warning[disabled].focus,
fieldset[disabled] .btn-warning.focus {
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning .badge {
color: #f0ad4e;
background-color: #fff;
}
.btn-danger {
color: #fff;
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger:focus,
.btn-danger.focus {
color: #fff;
background-color: #c9302c;
border-color: #761c19;
}
.btn-danger:hover {
color: #fff;
background-color: #c9302c;
border-color: #ac2925;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
color: #fff;
background-color: #c9302c;
border-color: #ac2925;
}
.btn-danger:active:hover,
.btn-danger.active:hover,
.open > .dropdown-toggle.btn-danger:hover,
.btn-danger:active:focus,
.btn-danger.active:focus,
.open > .dropdown-toggle.btn-danger:focus,
.btn-danger:active.focus,
.btn-danger.active.focus,
.open > .dropdown-toggle.btn-danger.focus {
color: #fff;
background-color: #ac2925;
border-color: #761c19;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
background-image: none;
}
.btn-danger.disabled:hover,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger:hover,
.btn-danger.disabled:focus,
.btn-danger[disabled]:focus,
fieldset[disabled] .btn-danger:focus,
.btn-danger.disabled.focus,
.btn-danger[disabled].focus,
fieldset[disabled] .btn-danger.focus {
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger .badge {
color: #d9534f;
background-color: #fff;
}
.btn-link {
color: #337ab7;
font-weight: normal;
border-radius: 0;
}
.btn-link,
.btn-link:active,
.btn-link.active,
.btn-link[disabled],
fieldset[disabled] .btn-link {
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
.btn-link,
.btn-link:hover,
.btn-link:focus,
.btn-link:active {
border-color: transparent;
}
.btn-link:hover,
.btn-link:focus {
color: #23527c;
text-decoration: underline;
background-color: transparent;
}
.btn-link[disabled]:hover,
fieldset[disabled] .btn-link:hover,
.btn-link[disabled]:focus,
fieldset[disabled] .btn-link:focus {
color: #777777;
text-decoration: none;
}
.btn-lg,
.btn-group-lg > .btn {
padding: 10px 16px;
font-size: 17px;
line-height: 1.3333333;
border-radius: 3px;
}
.btn-sm,
.btn-group-sm > .btn {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 1px;
}
.btn-xs,
.btn-group-xs > .btn {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 1px;
}
.btn-block {
display: block;
width: 100%;
}
.btn-block + .btn-block {
margin-top: 5px;
}
input[type="submit"].btn-block,
input[type="reset"].btn-block,
input[type="button"].btn-block {
width: 100%;
}
.fade {
opacity: 0;
-webkit-transition: opacity 0.15s linear;
-o-transition: opacity 0.15s linear;
transition: opacity 0.15s linear;
}
.fade.in {
opacity: 1;
}
.collapse {
display: none;
}
.collapse.in {
display: block;
}
tr.collapse.in {
display: table-row;
}
tbody.collapse.in {
display: table-row-group;
}
.collapsing {
position: relative;
height: 0;
overflow: hidden;
-webkit-transition-property: height, visibility;
transition-property: height, visibility;
-webkit-transition-duration: 0.35s;
transition-duration: 0.35s;
-webkit-transition-timing-function: ease;
transition-timing-function: ease;
}
.caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: 4px dashed;
border-top: 4px solid \9;
border-right: 4px solid transparent;
border-left: 4px solid transparent;
}
.dropup,
.dropdown {
position: relative;
}
.dropdown-toggle:focus {
outline: 0;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
list-style: none;
font-size: 13px;
text-align: left;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 2px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
background-clip: padding-box;
}
.dropdown-menu.pull-right {
right: 0;
left: auto;
}
.dropdown-menu .divider {
height: 1px;
margin: 8px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.dropdown-menu > li > a {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333333;
white-space: nowrap;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
text-decoration: none;
color: #262626;
background-color: #f5f5f5;
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
color: #fff;
text-decoration: none;
outline: 0;
background-color: #337ab7;
}
.dropdown-menu > .disabled > a,
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
color: #777777;
}
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
text-decoration: none;
background-color: transparent;
background-image: none;
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
cursor: not-allowed;
}
.open > .dropdown-menu {
display: block;
}
.open > a {
outline: 0;
}
.dropdown-menu-right {
left: auto;
right: 0;
}
.dropdown-menu-left {
left: 0;
right: auto;
}
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: 12px;
line-height: 1.42857143;
color: #777777;
white-space: nowrap;
}
.dropdown-backdrop {
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
z-index: 990;
}
.pull-right > .dropdown-menu {
right: 0;
left: auto;
}
.dropup .caret,
.navbar-fixed-bottom .dropdown .caret {
border-top: 0;
border-bottom: 4px dashed;
border-bottom: 4px solid \9;
content: "";
}
.dropup .dropdown-menu,
.navbar-fixed-bottom .dropdown .dropdown-menu {
top: auto;
bottom: 100%;
margin-bottom: 2px;
}
@media (min-width: 541px) {
.navbar-right .dropdown-menu {
left: auto;
right: 0;
}
.navbar-right .dropdown-menu-left {
left: 0;
right: auto;
}
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
.btn-group > .btn,
.btn-group-vertical > .btn {
position: relative;
float: left;
}
.btn-group > .btn:hover,
.btn-group-vertical > .btn:hover,
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus,
.btn-group > .btn:active,
.btn-group-vertical > .btn:active,
.btn-group > .btn.active,
.btn-group-vertical > .btn.active {
z-index: 2;
}
.btn-group .btn + .btn,
.btn-group .btn + .btn-group,
.btn-group .btn-group + .btn,
.btn-group .btn-group + .btn-group {
margin-left: -1px;
}
.btn-toolbar {
margin-left: -5px;
}
.btn-toolbar .btn,
.btn-toolbar .btn-group,
.btn-toolbar .input-group {
float: left;
}
.btn-toolbar > .btn,
.btn-toolbar > .btn-group,
.btn-toolbar > .input-group {
margin-left: 5px;
}
.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
border-radius: 0;
}
.btn-group > .btn:first-child {
margin-left: 0;
}
.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.btn-group > .btn:last-child:not(:first-child),
.btn-group > .dropdown-toggle:not(:first-child) {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
.btn-group > .btn-group {
float: left;
}
.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
.btn-group .dropdown-toggle:active,
.btn-group.open .dropdown-toggle {
outline: 0;
}
.btn-group > .btn + .dropdown-toggle {
padding-left: 8px;
padding-right: 8px;
}
.btn-group > .btn-lg + .dropdown-toggle {
padding-left: 12px;
padding-right: 12px;
}
.btn-group.open .dropdown-toggle {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
.btn-group.open .dropdown-toggle.btn-link {
-webkit-box-shadow: none;
box-shadow: none;
}
.btn .caret {
margin-left: 0;
}
.btn-lg .caret {
border-width: 5px 5px 0;
border-bottom-width: 0;
}
.dropup .btn-lg .caret {
border-width: 0 5px 5px;
}
.btn-group-vertical > .btn,
.btn-group-vertical > .btn-group,
.btn-group-vertical > .btn-group > .btn {
display: block;
float: none;
width: 100%;
max-width: 100%;
}
.btn-group-vertical > .btn-group > .btn {
float: none;
}
.btn-group-vertical > .btn + .btn,
.btn-group-vertical > .btn + .btn-group,
.btn-group-vertical > .btn-group + .btn,
.btn-group-vertical > .btn-group + .btn-group {
margin-top: -1px;
margin-left: 0;
}
.btn-group-vertical > .btn:not(:first-child):not(:last-child) {
border-radius: 0;
}
.btn-group-vertical > .btn:first-child:not(:last-child) {
border-top-right-radius: 2px;
border-top-left-radius: 2px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn:last-child:not(:first-child) {
border-top-right-radius: 0;
border-top-left-radius: 0;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 2px;
}
.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.btn-group-justified {
display: table;
width: 100%;
table-layout: fixed;
border-collapse: separate;
}
.btn-group-justified > .btn,
.btn-group-justified > .btn-group {
float: none;
display: table-cell;
width: 1%;
}
.btn-group-justified > .btn-group .btn {
width: 100%;
}
.btn-group-justified > .btn-group .dropdown-menu {
left: auto;
}
[data-toggle="buttons"] > .btn input[type="radio"],
[data-toggle="buttons"] > .btn-group > .btn input[type="radio"],
[data-toggle="buttons"] > .btn input[type="checkbox"],
[data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] {
position: absolute;
clip: rect(0, 0, 0, 0);
pointer-events: none;
}
.input-group {
position: relative;
display: table;
border-collapse: separate;
}
.input-group[class*="col-"] {
float: none;
padding-left: 0;
padding-right: 0;
}
.input-group .form-control {
position: relative;
z-index: 2;
float: left;
width: 100%;
margin-bottom: 0;
}
.input-group .form-control:focus {
z-index: 3;
}
.input-group-lg > .form-control,
.input-group-lg > .input-group-addon,
.input-group-lg > .input-group-btn > .btn {
height: 45px;
padding: 10px 16px;
font-size: 17px;
line-height: 1.3333333;
border-radius: 3px;
}
select.input-group-lg > .form-control,
select.input-group-lg > .input-group-addon,
select.input-group-lg > .input-group-btn > .btn {
height: 45px;
line-height: 45px;
}
textarea.input-group-lg > .form-control,
textarea.input-group-lg > .input-group-addon,
textarea.input-group-lg > .input-group-btn > .btn,
select[multiple].input-group-lg > .form-control,
select[multiple].input-group-lg > .input-group-addon,
select[multiple].input-group-lg > .input-group-btn > .btn {
height: auto;
}
.input-group-sm > .form-control,
.input-group-sm > .input-group-addon,
.input-group-sm > .input-group-btn > .btn {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 1px;
}
select.input-group-sm > .form-control,
select.input-group-sm > .input-group-addon,
select.input-group-sm > .input-group-btn > .btn {
height: 30px;
line-height: 30px;
}
textarea.input-group-sm > .form-control,
textarea.input-group-sm > .input-group-addon,
textarea.input-group-sm > .input-group-btn > .btn,
select[multiple].input-group-sm > .form-control,
select[multiple].input-group-sm > .input-group-addon,
select[multiple].input-group-sm > .input-group-btn > .btn {
height: auto;
}
.input-group-addon,
.input-group-btn,
.input-group .form-control {
display: table-cell;
}
.input-group-addon:not(:first-child):not(:last-child),
.input-group-btn:not(:first-child):not(:last-child),
.input-group .form-control:not(:first-child):not(:last-child) {
border-radius: 0;
}
.input-group-addon,
.input-group-btn {
width: 1%;
white-space: nowrap;
vertical-align: middle;
}
.input-group-addon {
padding: 6px 12px;
font-size: 13px;
font-weight: normal;
line-height: 1;
color: #555555;
text-align: center;
background-color: #eeeeee;
border: 1px solid #ccc;
border-radius: 2px;
}
.input-group-addon.input-sm {
padding: 5px 10px;
font-size: 12px;
border-radius: 1px;
}
.input-group-addon.input-lg {
padding: 10px 16px;
font-size: 17px;
border-radius: 3px;
}
.input-group-addon input[type="radio"],
.input-group-addon input[type="checkbox"] {
margin-top: 0;
}
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.input-group-addon:first-child {
border-right: 0;
}
.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group > .btn,
.input-group-btn:last-child > .dropdown-toggle,
.input-group-btn:first-child > .btn:not(:first-child),
.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
.input-group-addon:last-child {
border-left: 0;
}
.input-group-btn {
position: relative;
font-size: 0;
white-space: nowrap;
}
.input-group-btn > .btn {
position: relative;
}
.input-group-btn > .btn + .btn {
margin-left: -1px;
}
.input-group-btn > .btn:hover,
.input-group-btn > .btn:focus,
.input-group-btn > .btn:active {
z-index: 2;
}
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group {
margin-right: -1px;
}
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group {
z-index: 2;
margin-left: -1px;
}
.nav {
margin-bottom: 0;
padding-left: 0;
list-style: none;
}
.nav > li {
position: relative;
display: block;
}
.nav > li > a {
position: relative;
display: block;
padding: 10px 15px;
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: #eeeeee;
}
.nav > li.disabled > a {
color: #777777;
}
.nav > li.disabled > a:hover,
.nav > li.disabled > a:focus {
color: #777777;
text-decoration: none;
background-color: transparent;
cursor: not-allowed;
}
.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
background-color: #eeeeee;
border-color: #337ab7;
}
.nav .nav-divider {
height: 1px;
margin: 8px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.nav > li > a > img {
max-width: none;
}
.nav-tabs {
border-bottom: 1px solid #ddd;
}
.nav-tabs > li {
float: left;
margin-bottom: -1px;
}
.nav-tabs > li > a {
margin-right: 2px;
line-height: 1.42857143;
border: 1px solid transparent;
border-radius: 2px 2px 0 0;
}
.nav-tabs > li > a:hover {
border-color: #eeeeee #eeeeee #ddd;
}
.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
color: #555555;
background-color: #fff;
border: 1px solid #ddd;
border-bottom-color: transparent;
cursor: default;
}
.nav-tabs.nav-justified {
width: 100%;
border-bottom: 0;
}
.nav-tabs.nav-justified > li {
float: none;
}
.nav-tabs.nav-justified > li > a {
text-align: center;
margin-bottom: 5px;
}
.nav-tabs.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs.nav-justified > li > a {
margin-right: 0;
border-radius: 2px;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 2px 2px 0 0;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.nav-pills > li {
float: left;
}
.nav-pills > li > a {
border-radius: 2px;
}
.nav-pills > li + li {
margin-left: 2px;
}
.nav-pills > li.active > a,
.nav-pills > li.active > a:hover,
.nav-pills > li.active > a:focus {
color: #fff;
background-color: #337ab7;
}
.nav-stacked > li {
float: none;
}
.nav-stacked > li + li {
margin-top: 2px;
margin-left: 0;
}
.nav-justified {
width: 100%;
}
.nav-justified > li {
float: none;
}
.nav-justified > li > a {
text-align: center;
margin-bottom: 5px;
}
.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs-justified {
border-bottom: 0;
}
.nav-tabs-justified > li > a {
margin-right: 0;
border-radius: 2px;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 2px 2px 0 0;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.tab-content > .tab-pane {
display: none;
}
.tab-content > .active {
display: block;
}
.nav-tabs .dropdown-menu {
margin-top: -1px;
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.navbar {
position: relative;
min-height: 30px;
margin-bottom: 18px;
border: 1px solid transparent;
}
@media (min-width: 541px) {
.navbar {
border-radius: 2px;
}
}
@media (min-width: 541px) {
.navbar-header {
float: left;
}
}
.navbar-collapse {
overflow-x: visible;
padding-right: 0px;
padding-left: 0px;
border-top: 1px solid transparent;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
-webkit-overflow-scrolling: touch;
}
.navbar-collapse.in {
overflow-y: auto;
}
@media (min-width: 541px) {
.navbar-collapse {
width: auto;
border-top: 0;
box-shadow: none;
}
.navbar-collapse.collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
}
.navbar-collapse.in {
overflow-y: visible;
}
.navbar-fixed-top .navbar-collapse,
.navbar-static-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
padding-left: 0;
padding-right: 0;
}
}
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 340px;
}
@media (max-device-width: 540px) and (orientation: landscape) {
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 200px;
}
}
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: 0px;
margin-left: 0px;
}
@media (min-width: 541px) {
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
}
.navbar-static-top {
z-index: 1000;
border-width: 0 0 1px;
}
@media (min-width: 541px) {
.navbar-static-top {
border-radius: 0;
}
}
.navbar-fixed-top,
.navbar-fixed-bottom {
position: fixed;
right: 0;
left: 0;
z-index: 1030;
}
@media (min-width: 541px) {
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
}
.navbar-fixed-top {
top: 0;
border-width: 0 0 1px;
}
.navbar-fixed-bottom {
bottom: 0;
margin-bottom: 0;
border-width: 1px 0 0;
}
.navbar-brand {
float: left;
padding: 6px 0px;
font-size: 17px;
line-height: 18px;
height: 30px;
}
.navbar-brand:hover,
.navbar-brand:focus {
text-decoration: none;
}
.navbar-brand > img {
display: block;
}
@media (min-width: 541px) {
.navbar > .container .navbar-brand,
.navbar > .container-fluid .navbar-brand {
margin-left: 0px;
}
}
.navbar-toggle {
position: relative;
float: right;
margin-right: 0px;
padding: 9px 10px;
margin-top: -2px;
margin-bottom: -2px;
background-color: transparent;
background-image: none;
border: 1px solid transparent;
border-radius: 2px;
}
.navbar-toggle:focus {
outline: 0;
}
.navbar-toggle .icon-bar {
display: block;
width: 22px;
height: 2px;
border-radius: 1px;
}
.navbar-toggle .icon-bar + .icon-bar {
margin-top: 4px;
}
@media (min-width: 541px) {
.navbar-toggle {
display: none;
}
}
.navbar-nav {
margin: 3px 0px;
}
.navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 18px;
}
@media (max-width: 540px) {
.navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
box-shadow: none;
}
.navbar-nav .open .dropdown-menu > li > a,
.navbar-nav .open .dropdown-menu .dropdown-header {
padding: 5px 15px 5px 25px;
}
.navbar-nav .open .dropdown-menu > li > a {
line-height: 18px;
}
.navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-nav .open .dropdown-menu > li > a:focus {
background-image: none;
}
}
@media (min-width: 541px) {
.navbar-nav {
float: left;
margin: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
padding-top: 6px;
padding-bottom: 6px;
}
}
.navbar-form {
margin-left: 0px;
margin-right: 0px;
padding: 10px 0px;
border-top: 1px solid transparent;
border-bottom: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
margin-top: -1px;
margin-bottom: -1px;
}
@media (min-width: 768px) {
.navbar-form .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.navbar-form .form-control-static {
display: inline-block;
}
.navbar-form .input-group {
display: inline-table;
vertical-align: middle;
}
.navbar-form .input-group .input-group-addon,
.navbar-form .input-group .input-group-btn,
.navbar-form .input-group .form-control {
width: auto;
}
.navbar-form .input-group > .form-control {
width: 100%;
}
.navbar-form .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio,
.navbar-form .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio label,
.navbar-form .checkbox label {
padding-left: 0;
}
.navbar-form .radio input[type="radio"],
.navbar-form .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.navbar-form .has-feedback .form-control-feedback {
top: 0;
}
}
@media (max-width: 540px) {
.navbar-form .form-group {
margin-bottom: 5px;
}
.navbar-form .form-group:last-child {
margin-bottom: 0;
}
}
@media (min-width: 541px) {
.navbar-form {
width: auto;
border: 0;
margin-left: 0;
margin-right: 0;
padding-top: 0;
padding-bottom: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
}
.navbar-nav > li > .dropdown-menu {
margin-top: 0;
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
margin-bottom: 0;
border-top-right-radius: 2px;
border-top-left-radius: 2px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.navbar-btn {
margin-top: -1px;
margin-bottom: -1px;
}
.navbar-btn.btn-sm {
margin-top: 0px;
margin-bottom: 0px;
}
.navbar-btn.btn-xs {
margin-top: 4px;
margin-bottom: 4px;
}
.navbar-text {
margin-top: 6px;
margin-bottom: 6px;
}
@media (min-width: 541px) {
.navbar-text {
float: left;
margin-left: 0px;
margin-right: 0px;
}
}
@media (min-width: 541px) {
.navbar-left {
float: left !important;
float: left;
}
.navbar-right {
float: right !important;
float: right;
margin-right: 0px;
}
.navbar-right ~ .navbar-right {
margin-right: 0;
}
}
.navbar-default {
background-color: #f8f8f8;
border-color: #e7e7e7;
}
.navbar-default .navbar-brand {
color: #777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: #5e5e5e;
background-color: transparent;
}
.navbar-default .navbar-text {
color: #777;
}
.navbar-default .navbar-nav > li > a {
color: #777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav > .disabled > a,
.navbar-default .navbar-nav > .disabled > a:hover,
.navbar-default .navbar-nav > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
.navbar-default .navbar-toggle {
border-color: #ddd;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #ddd;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #888;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
border-color: #e7e7e7;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
background-color: #e7e7e7;
color: #555;
}
@media (max-width: 540px) {
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #777;
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
}
.navbar-default .navbar-link {
color: #777;
}
.navbar-default .navbar-link:hover {
color: #333;
}
.navbar-default .btn-link {
color: #777;
}
.navbar-default .btn-link:hover,
.navbar-default .btn-link:focus {
color: #333;
}
.navbar-default .btn-link[disabled]:hover,
fieldset[disabled] .navbar-default .btn-link:hover,
.navbar-default .btn-link[disabled]:focus,
fieldset[disabled] .navbar-default .btn-link:focus {
color: #ccc;
}
.navbar-inverse {
background-color: #222;
border-color: #080808;
}
.navbar-inverse .navbar-brand {
color: #9d9d9d;
}
.navbar-inverse .navbar-brand:hover,
.navbar-inverse .navbar-brand:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-text {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav > li > a {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav > .disabled > a,
.navbar-inverse .navbar-nav > .disabled > a:hover,
.navbar-inverse .navbar-nav > .disabled > a:focus {
color: #444;
background-color: transparent;
}
.navbar-inverse .navbar-toggle {
border-color: #333;
}
.navbar-inverse .navbar-toggle:hover,
.navbar-inverse .navbar-toggle:focus {
background-color: #333;
}
.navbar-inverse .navbar-toggle .icon-bar {
background-color: #fff;
}
.navbar-inverse .navbar-collapse,
.navbar-inverse .navbar-form {
border-color: #101010;
}
.navbar-inverse .navbar-nav > .open > a,
.navbar-inverse .navbar-nav > .open > a:hover,
.navbar-inverse .navbar-nav > .open > a:focus {
background-color: #080808;
color: #fff;
}
@media (max-width: 540px) {
.navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
border-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #444;
background-color: transparent;
}
}
.navbar-inverse .navbar-link {
color: #9d9d9d;
}
.navbar-inverse .navbar-link:hover {
color: #fff;
}
.navbar-inverse .btn-link {
color: #9d9d9d;
}
.navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link:focus {
color: #fff;
}
.navbar-inverse .btn-link[disabled]:hover,
fieldset[disabled] .navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link[disabled]:focus,
fieldset[disabled] .navbar-inverse .btn-link:focus {
color: #444;
}
.breadcrumb {
padding: 8px 15px;
margin-bottom: 18px;
list-style: none;
background-color: #f5f5f5;
border-radius: 2px;
}
.breadcrumb > li {
display: inline-block;
}
.breadcrumb > li + li:before {
content: "/\00a0";
padding: 0 5px;
color: #5e5e5e;
}
.breadcrumb > .active {
color: #777777;
}
.pagination {
display: inline-block;
padding-left: 0;
margin: 18px 0;
border-radius: 2px;
}
.pagination > li {
display: inline;
}
.pagination > li > a,
.pagination > li > span {
position: relative;
float: left;
padding: 6px 12px;
line-height: 1.42857143;
text-decoration: none;
color: #337ab7;
background-color: #fff;
border: 1px solid #ddd;
margin-left: -1px;
}
.pagination > li:first-child > a,
.pagination > li:first-child > span {
margin-left: 0;
border-bottom-left-radius: 2px;
border-top-left-radius: 2px;
}
.pagination > li:last-child > a,
.pagination > li:last-child > span {
border-bottom-right-radius: 2px;
border-top-right-radius: 2px;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
z-index: 2;
color: #23527c;
background-color: #eeeeee;
border-color: #ddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
z-index: 3;
color: #fff;
background-color: #337ab7;
border-color: #337ab7;
cursor: default;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
color: #777777;
background-color: #fff;
border-color: #ddd;
cursor: not-allowed;
}
.pagination-lg > li > a,
.pagination-lg > li > span {
padding: 10px 16px;
font-size: 17px;
line-height: 1.3333333;
}
.pagination-lg > li:first-child > a,
.pagination-lg > li:first-child > span {
border-bottom-left-radius: 3px;
border-top-left-radius: 3px;
}
.pagination-lg > li:last-child > a,
.pagination-lg > li:last-child > span {
border-bottom-right-radius: 3px;
border-top-right-radius: 3px;
}
.pagination-sm > li > a,
.pagination-sm > li > span {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
}
.pagination-sm > li:first-child > a,
.pagination-sm > li:first-child > span {
border-bottom-left-radius: 1px;
border-top-left-radius: 1px;
}
.pagination-sm > li:last-child > a,
.pagination-sm > li:last-child > span {
border-bottom-right-radius: 1px;
border-top-right-radius: 1px;
}
.pager {
padding-left: 0;
margin: 18px 0;
list-style: none;
text-align: center;
}
.pager li {
display: inline;
}
.pager li > a,
.pager li > span {
display: inline-block;
padding: 5px 14px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 15px;
}
.pager li > a:hover,
.pager li > a:focus {
text-decoration: none;
background-color: #eeeeee;
}
.pager .next > a,
.pager .next > span {
float: right;
}
.pager .previous > a,
.pager .previous > span {
float: left;
}
.pager .disabled > a,
.pager .disabled > a:hover,
.pager .disabled > a:focus,
.pager .disabled > span {
color: #777777;
background-color: #fff;
cursor: not-allowed;
}
.label {
display: inline;
padding: .2em .6em .3em;
font-size: 75%;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25em;
}
a.label:hover,
a.label:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
.label:empty {
display: none;
}
.btn .label {
position: relative;
top: -1px;
}
.label-default {
background-color: #777777;
}
.label-default[href]:hover,
.label-default[href]:focus {
background-color: #5e5e5e;
}
.label-primary {
background-color: #337ab7;
}
.label-primary[href]:hover,
.label-primary[href]:focus {
background-color: #286090;
}
.label-success {
background-color: #5cb85c;
}
.label-success[href]:hover,
.label-success[href]:focus {
background-color: #449d44;
}
.label-info {
background-color: #5bc0de;
}
.label-info[href]:hover,
.label-info[href]:focus {
background-color: #31b0d5;
}
.label-warning {
background-color: #f0ad4e;
}
.label-warning[href]:hover,
.label-warning[href]:focus {
background-color: #ec971f;
}
.label-danger {
background-color: #d9534f;
}
.label-danger[href]:hover,
.label-danger[href]:focus {
background-color: #c9302c;
}
.badge {
display: inline-block;
min-width: 10px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
color: #fff;
line-height: 1;
vertical-align: middle;
white-space: nowrap;
text-align: center;
background-color: #777777;
border-radius: 10px;
}
.badge:empty {
display: none;
}
.btn .badge {
position: relative;
top: -1px;
}
.btn-xs .badge,
.btn-group-xs > .btn .badge {
top: 0;
padding: 1px 5px;
}
a.badge:hover,
a.badge:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
.list-group-item.active > .badge,
.nav-pills > .active > a > .badge {
color: #337ab7;
background-color: #fff;
}
.list-group-item > .badge {
float: right;
}
.list-group-item > .badge + .badge {
margin-right: 5px;
}
.nav-pills > li > a > .badge {
margin-left: 3px;
}
.jumbotron {
padding-top: 30px;
padding-bottom: 30px;
margin-bottom: 30px;
color: inherit;
background-color: #eeeeee;
}
.jumbotron h1,
.jumbotron .h1 {
color: inherit;
}
.jumbotron p {
margin-bottom: 15px;
font-size: 20px;
font-weight: 200;
}
.jumbotron > hr {
border-top-color: #d5d5d5;
}
.container .jumbotron,
.container-fluid .jumbotron {
border-radius: 3px;
padding-left: 0px;
padding-right: 0px;
}
.jumbotron .container {
max-width: 100%;
}
@media screen and (min-width: 768px) {
.jumbotron {
padding-top: 48px;
padding-bottom: 48px;
}
.container .jumbotron,
.container-fluid .jumbotron {
padding-left: 60px;
padding-right: 60px;
}
.jumbotron h1,
.jumbotron .h1 {
font-size: 59px;
}
}
.thumbnail {
display: block;
padding: 4px;
margin-bottom: 18px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 2px;
-webkit-transition: border 0.2s ease-in-out;
-o-transition: border 0.2s ease-in-out;
transition: border 0.2s ease-in-out;
}
.thumbnail > img,
.thumbnail a > img {
margin-left: auto;
margin-right: auto;
}
a.thumbnail:hover,
a.thumbnail:focus,
a.thumbnail.active {
border-color: #337ab7;
}
.thumbnail .caption {
padding: 9px;
color: #000;
}
.alert {
padding: 15px;
margin-bottom: 18px;
border: 1px solid transparent;
border-radius: 2px;
}
.alert h4 {
margin-top: 0;
color: inherit;
}
.alert .alert-link {
font-weight: bold;
}
.alert > p,
.alert > ul {
margin-bottom: 0;
}
.alert > p + p {
margin-top: 5px;
}
.alert-dismissable,
.alert-dismissible {
padding-right: 35px;
}
.alert-dismissable .close,
.alert-dismissible .close {
position: relative;
top: -2px;
right: -21px;
color: inherit;
}
.alert-success {
background-color: #dff0d8;
border-color: #d6e9c6;
color: #3c763d;
}
.alert-success hr {
border-top-color: #c9e2b3;
}
.alert-success .alert-link {
color: #2b542c;
}
.alert-info {
background-color: #d9edf7;
border-color: #bce8f1;
color: #31708f;
}
.alert-info hr {
border-top-color: #a6e1ec;
}
.alert-info .alert-link {
color: #245269;
}
.alert-warning {
background-color: #fcf8e3;
border-color: #faebcc;
color: #8a6d3b;
}
.alert-warning hr {
border-top-color: #f7e1b5;
}
.alert-warning .alert-link {
color: #66512c;
}
.alert-danger {
background-color: #f2dede;
border-color: #ebccd1;
color: #a94442;
}
.alert-danger hr {
border-top-color: #e4b9c0;
}
.alert-danger .alert-link {
color: #843534;
}
@-webkit-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
.progress {
overflow: hidden;
height: 18px;
margin-bottom: 18px;
background-color: #f5f5f5;
border-radius: 2px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}
.progress-bar {
float: left;
width: 0%;
height: 100%;
font-size: 12px;
line-height: 18px;
color: #fff;
text-align: center;
background-color: #337ab7;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
-webkit-transition: width 0.6s ease;
-o-transition: width 0.6s ease;
transition: width 0.6s ease;
}
.progress-striped .progress-bar,
.progress-bar-striped {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-size: 40px 40px;
}
.progress.active .progress-bar,
.progress-bar.active {
-webkit-animation: progress-bar-stripes 2s linear infinite;
-o-animation: progress-bar-stripes 2s linear infinite;
animation: progress-bar-stripes 2s linear infinite;
}
.progress-bar-success {
background-color: #5cb85c;
}
.progress-striped .progress-bar-success {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.progress-bar-info {
background-color: #5bc0de;
}
.progress-striped .progress-bar-info {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.progress-bar-warning {
background-color: #f0ad4e;
}
.progress-striped .progress-bar-warning {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.progress-bar-danger {
background-color: #d9534f;
}
.progress-striped .progress-bar-danger {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.media {
margin-top: 15px;
}
.media:first-child {
margin-top: 0;
}
.media,
.media-body {
zoom: 1;
overflow: hidden;
}
.media-body {
width: 10000px;
}
.media-object {
display: block;
}
.media-object.img-thumbnail {
max-width: none;
}
.media-right,
.media > .pull-right {
padding-left: 10px;
}
.media-left,
.media > .pull-left {
padding-right: 10px;
}
.media-left,
.media-right,
.media-body {
display: table-cell;
vertical-align: top;
}
.media-middle {
vertical-align: middle;
}
.media-bottom {
vertical-align: bottom;
}
.media-heading {
margin-top: 0;
margin-bottom: 5px;
}
.media-list {
padding-left: 0;
list-style: none;
}
.list-group {
margin-bottom: 20px;
padding-left: 0;
}
.list-group-item {
position: relative;
display: block;
padding: 10px 15px;
margin-bottom: -1px;
background-color: #fff;
border: 1px solid #ddd;
}
.list-group-item:first-child {
border-top-right-radius: 2px;
border-top-left-radius: 2px;
}
.list-group-item:last-child {
margin-bottom: 0;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 2px;
}
a.list-group-item,
button.list-group-item {
color: #555;
}
a.list-group-item .list-group-item-heading,
button.list-group-item .list-group-item-heading {
color: #333;
}
a.list-group-item:hover,
button.list-group-item:hover,
a.list-group-item:focus,
button.list-group-item:focus {
text-decoration: none;
color: #555;
background-color: #f5f5f5;
}
button.list-group-item {
width: 100%;
text-align: left;
}
.list-group-item.disabled,
.list-group-item.disabled:hover,
.list-group-item.disabled:focus {
background-color: #eeeeee;
color: #777777;
cursor: not-allowed;
}
.list-group-item.disabled .list-group-item-heading,
.list-group-item.disabled:hover .list-group-item-heading,
.list-group-item.disabled:focus .list-group-item-heading {
color: inherit;
}
.list-group-item.disabled .list-group-item-text,
.list-group-item.disabled:hover .list-group-item-text,
.list-group-item.disabled:focus .list-group-item-text {
color: #777777;
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
z-index: 2;
color: #fff;
background-color: #337ab7;
border-color: #337ab7;
}
.list-group-item.active .list-group-item-heading,
.list-group-item.active:hover .list-group-item-heading,
.list-group-item.active:focus .list-group-item-heading,
.list-group-item.active .list-group-item-heading > small,
.list-group-item.active:hover .list-group-item-heading > small,
.list-group-item.active:focus .list-group-item-heading > small,
.list-group-item.active .list-group-item-heading > .small,
.list-group-item.active:hover .list-group-item-heading > .small,
.list-group-item.active:focus .list-group-item-heading > .small {
color: inherit;
}
.list-group-item.active .list-group-item-text,
.list-group-item.active:hover .list-group-item-text,
.list-group-item.active:focus .list-group-item-text {
color: #c7ddef;
}
.list-group-item-success {
color: #3c763d;
background-color: #dff0d8;
}
a.list-group-item-success,
button.list-group-item-success {
color: #3c763d;
}
a.list-group-item-success .list-group-item-heading,
button.list-group-item-success .list-group-item-heading {
color: inherit;
}
a.list-group-item-success:hover,
button.list-group-item-success:hover,
a.list-group-item-success:focus,
button.list-group-item-success:focus {
color: #3c763d;
background-color: #d0e9c6;
}
a.list-group-item-success.active,
button.list-group-item-success.active,
a.list-group-item-success.active:hover,
button.list-group-item-success.active:hover,
a.list-group-item-success.active:focus,
button.list-group-item-success.active:focus {
color: #fff;
background-color: #3c763d;
border-color: #3c763d;
}
.list-group-item-info {
color: #31708f;
background-color: #d9edf7;
}
a.list-group-item-info,
button.list-group-item-info {
color: #31708f;
}
a.list-group-item-info .list-group-item-heading,
button.list-group-item-info .list-group-item-heading {
color: inherit;
}
a.list-group-item-info:hover,
button.list-group-item-info:hover,
a.list-group-item-info:focus,
button.list-group-item-info:focus {
color: #31708f;
background-color: #c4e3f3;
}
a.list-group-item-info.active,
button.list-group-item-info.active,
a.list-group-item-info.active:hover,
button.list-group-item-info.active:hover,
a.list-group-item-info.active:focus,
button.list-group-item-info.active:focus {
color: #fff;
background-color: #31708f;
border-color: #31708f;
}
.list-group-item-warning {
color: #8a6d3b;
background-color: #fcf8e3;
}
a.list-group-item-warning,
button.list-group-item-warning {
color: #8a6d3b;
}
a.list-group-item-warning .list-group-item-heading,
button.list-group-item-warning .list-group-item-heading {
color: inherit;
}
a.list-group-item-warning:hover,
button.list-group-item-warning:hover,
a.list-group-item-warning:focus,
button.list-group-item-warning:focus {
color: #8a6d3b;
background-color: #faf2cc;
}
a.list-group-item-warning.active,
button.list-group-item-warning.active,
a.list-group-item-warning.active:hover,
button.list-group-item-warning.active:hover,
a.list-group-item-warning.active:focus,
button.list-group-item-warning.active:focus {
color: #fff;
background-color: #8a6d3b;
border-color: #8a6d3b;
}
.list-group-item-danger {
color: #a94442;
background-color: #f2dede;
}
a.list-group-item-danger,
button.list-group-item-danger {
color: #a94442;
}
a.list-group-item-danger .list-group-item-heading,
button.list-group-item-danger .list-group-item-heading {
color: inherit;
}
a.list-group-item-danger:hover,
button.list-group-item-danger:hover,
a.list-group-item-danger:focus,
button.list-group-item-danger:focus {
color: #a94442;
background-color: #ebcccc;
}
a.list-group-item-danger.active,
button.list-group-item-danger.active,
a.list-group-item-danger.active:hover,
button.list-group-item-danger.active:hover,
a.list-group-item-danger.active:focus,
button.list-group-item-danger.active:focus {
color: #fff;
background-color: #a94442;
border-color: #a94442;
}
.list-group-item-heading {
margin-top: 0;
margin-bottom: 5px;
}
.list-group-item-text {
margin-bottom: 0;
line-height: 1.3;
}
.panel {
margin-bottom: 18px;
background-color: #fff;
border: 1px solid transparent;
border-radius: 2px;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}
.panel-body {
padding: 15px;
}
.panel-heading {
padding: 10px 15px;
border-bottom: 1px solid transparent;
border-top-right-radius: 1px;
border-top-left-radius: 1px;
}
.panel-heading > .dropdown .dropdown-toggle {
color: inherit;
}
.panel-title {
margin-top: 0;
margin-bottom: 0;
font-size: 15px;
color: inherit;
}
.panel-title > a,
.panel-title > small,
.panel-title > .small,
.panel-title > small > a,
.panel-title > .small > a {
color: inherit;
}
.panel-footer {
padding: 10px 15px;
background-color: #f5f5f5;
border-top: 1px solid #ddd;
border-bottom-right-radius: 1px;
border-bottom-left-radius: 1px;
}
.panel > .list-group,
.panel > .panel-collapse > .list-group {
margin-bottom: 0;
}
.panel > .list-group .list-group-item,
.panel > .panel-collapse > .list-group .list-group-item {
border-width: 1px 0;
border-radius: 0;
}
.panel > .list-group:first-child .list-group-item:first-child,
.panel > .panel-collapse > .list-group:first-child .list-group-item:first-child {
border-top: 0;
border-top-right-radius: 1px;
border-top-left-radius: 1px;
}
.panel > .list-group:last-child .list-group-item:last-child,
.panel > .panel-collapse > .list-group:last-child .list-group-item:last-child {
border-bottom: 0;
border-bottom-right-radius: 1px;
border-bottom-left-radius: 1px;
}
.panel > .panel-heading + .panel-collapse > .list-group .list-group-item:first-child {
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.panel-heading + .list-group .list-group-item:first-child {
border-top-width: 0;
}
.list-group + .panel-footer {
border-top-width: 0;
}
.panel > .table,
.panel > .table-responsive > .table,
.panel > .panel-collapse > .table {
margin-bottom: 0;
}
.panel > .table caption,
.panel > .table-responsive > .table caption,
.panel > .panel-collapse > .table caption {
padding-left: 15px;
padding-right: 15px;
}
.panel > .table:first-child,
.panel > .table-responsive:first-child > .table:first-child {
border-top-right-radius: 1px;
border-top-left-radius: 1px;
}
.panel > .table:first-child > thead:first-child > tr:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child {
border-top-left-radius: 1px;
border-top-right-radius: 1px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
border-top-left-radius: 1px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
border-top-right-radius: 1px;
}
.panel > .table:last-child,
.panel > .table-responsive:last-child > .table:last-child {
border-bottom-right-radius: 1px;
border-bottom-left-radius: 1px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child {
border-bottom-left-radius: 1px;
border-bottom-right-radius: 1px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
border-bottom-left-radius: 1px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
border-bottom-right-radius: 1px;
}
.panel > .panel-body + .table,
.panel > .panel-body + .table-responsive,
.panel > .table + .panel-body,
.panel > .table-responsive + .panel-body {
border-top: 1px solid #ddd;
}
.panel > .table > tbody:first-child > tr:first-child th,
.panel > .table > tbody:first-child > tr:first-child td {
border-top: 0;
}
.panel > .table-bordered,
.panel > .table-responsive > .table-bordered {
border: 0;
}
.panel > .table-bordered > thead > tr > th:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,
.panel > .table-bordered > tbody > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,
.panel > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-bordered > thead > tr > td:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,
.panel > .table-bordered > tbody > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,
.panel > .table-bordered > tfoot > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.panel > .table-bordered > thead > tr > th:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,
.panel > .table-bordered > tbody > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,
.panel > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-bordered > thead > tr > td:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,
.panel > .table-bordered > tbody > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,
.panel > .table-bordered > tfoot > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.panel > .table-bordered > thead > tr:first-child > td,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,
.panel > .table-bordered > tbody > tr:first-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,
.panel > .table-bordered > thead > tr:first-child > th,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,
.panel > .table-bordered > tbody > tr:first-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {
border-bottom: 0;
}
.panel > .table-bordered > tbody > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,
.panel > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-bordered > tbody > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,
.panel > .table-bordered > tfoot > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {
border-bottom: 0;
}
.panel > .table-responsive {
border: 0;
margin-bottom: 0;
}
.panel-group {
margin-bottom: 18px;
}
.panel-group .panel {
margin-bottom: 0;
border-radius: 2px;
}
.panel-group .panel + .panel {
margin-top: 5px;
}
.panel-group .panel-heading {
border-bottom: 0;
}
.panel-group .panel-heading + .panel-collapse > .panel-body,
.panel-group .panel-heading + .panel-collapse > .list-group {
border-top: 1px solid #ddd;
}
.panel-group .panel-footer {
border-top: 0;
}
.panel-group .panel-footer + .panel-collapse .panel-body {
border-bottom: 1px solid #ddd;
}
.panel-default {
border-color: #ddd;
}
.panel-default > .panel-heading {
color: #333333;
background-color: #f5f5f5;
border-color: #ddd;
}
.panel-default > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ddd;
}
.panel-default > .panel-heading .badge {
color: #f5f5f5;
background-color: #333333;
}
.panel-default > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ddd;
}
.panel-primary {
border-color: #337ab7;
}
.panel-primary > .panel-heading {
color: #fff;
background-color: #337ab7;
border-color: #337ab7;
}
.panel-primary > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #337ab7;
}
.panel-primary > .panel-heading .badge {
color: #337ab7;
background-color: #fff;
}
.panel-primary > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #337ab7;
}
.panel-success {
border-color: #d6e9c6;
}
.panel-success > .panel-heading {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.panel-success > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #d6e9c6;
}
.panel-success > .panel-heading .badge {
color: #dff0d8;
background-color: #3c763d;
}
.panel-success > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #d6e9c6;
}
.panel-info {
border-color: #bce8f1;
}
.panel-info > .panel-heading {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.panel-info > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #bce8f1;
}
.panel-info > .panel-heading .badge {
color: #d9edf7;
background-color: #31708f;
}
.panel-info > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #bce8f1;
}
.panel-warning {
border-color: #faebcc;
}
.panel-warning > .panel-heading {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.panel-warning > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #faebcc;
}
.panel-warning > .panel-heading .badge {
color: #fcf8e3;
background-color: #8a6d3b;
}
.panel-warning > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #faebcc;
}
.panel-danger {
border-color: #ebccd1;
}
.panel-danger > .panel-heading {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.panel-danger > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ebccd1;
}
.panel-danger > .panel-heading .badge {
color: #f2dede;
background-color: #a94442;
}
.panel-danger > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ebccd1;
}
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object,
.embed-responsive video {
position: absolute;
top: 0;
left: 0;
bottom: 0;
height: 100%;
width: 100%;
border: 0;
}
.embed-responsive-16by9 {
padding-bottom: 56.25%;
}
.embed-responsive-4by3 {
padding-bottom: 75%;
}
.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5f5;
border: 1px solid #e3e3e3;
border-radius: 2px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
}
.well blockquote {
border-color: #ddd;
border-color: rgba(0, 0, 0, 0.15);
}
.well-lg {
padding: 24px;
border-radius: 3px;
}
.well-sm {
padding: 9px;
border-radius: 1px;
}
.close {
float: right;
font-size: 19.5px;
font-weight: bold;
line-height: 1;
color: #000;
text-shadow: 0 1px 0 #fff;
opacity: 0.2;
filter: alpha(opacity=20);
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
opacity: 0.5;
filter: alpha(opacity=50);
}
button.close {
padding: 0;
cursor: pointer;
background: transparent;
border: 0;
-webkit-appearance: none;
}
.modal-open {
overflow: hidden;
}
.modal {
display: none;
overflow: hidden;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1050;
-webkit-overflow-scrolling: touch;
outline: 0;
}
.modal.fade .modal-dialog {
-webkit-transform: translate(0, -25%);
-ms-transform: translate(0, -25%);
-o-transform: translate(0, -25%);
transform: translate(0, -25%);
-webkit-transition: -webkit-transform 0.3s ease-out;
-moz-transition: -moz-transform 0.3s ease-out;
-o-transition: -o-transform 0.3s ease-out;
transition: transform 0.3s ease-out;
}
.modal.in .modal-dialog {
-webkit-transform: translate(0, 0);
-ms-transform: translate(0, 0);
-o-transform: translate(0, 0);
transform: translate(0, 0);
}
.modal-open .modal {
overflow-x: hidden;
overflow-y: auto;
}
.modal-dialog {
position: relative;
width: auto;
margin: 10px;
}
.modal-content {
position: relative;
background-color: #fff;
border: 1px solid #999;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
-webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
background-clip: padding-box;
outline: 0;
}
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1040;
background-color: #000;
}
.modal-backdrop.fade {
opacity: 0;
filter: alpha(opacity=0);
}
.modal-backdrop.in {
opacity: 0.5;
filter: alpha(opacity=50);
}
.modal-header {
padding: 15px;
border-bottom: 1px solid #e5e5e5;
}
.modal-header .close {
margin-top: -2px;
}
.modal-title {
margin: 0;
line-height: 1.42857143;
}
.modal-body {
position: relative;
padding: 15px;
}
.modal-footer {
padding: 15px;
text-align: right;
border-top: 1px solid #e5e5e5;
}
.modal-footer .btn + .btn {
margin-left: 5px;
margin-bottom: 0;
}
.modal-footer .btn-group .btn + .btn {
margin-left: -1px;
}
.modal-footer .btn-block + .btn-block {
margin-left: 0;
}
.modal-scrollbar-measure {
position: absolute;
top: -9999px;
width: 50px;
height: 50px;
overflow: scroll;
}
@media (min-width: 768px) {
.modal-dialog {
width: 600px;
margin: 30px auto;
}
.modal-content {
-webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
}
.modal-sm {
width: 300px;
}
}
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
.tooltip {
position: absolute;
z-index: 1070;
display: block;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-style: normal;
font-weight: normal;
letter-spacing: normal;
line-break: auto;
line-height: 1.42857143;
text-align: left;
text-align: start;
text-decoration: none;
text-shadow: none;
text-transform: none;
white-space: normal;
word-break: normal;
word-spacing: normal;
word-wrap: normal;
font-size: 12px;
opacity: 0;
filter: alpha(opacity=0);
}
.tooltip.in {
opacity: 0.9;
filter: alpha(opacity=90);
}
.tooltip.top {
margin-top: -3px;
padding: 5px 0;
}
.tooltip.right {
margin-left: 3px;
padding: 0 5px;
}
.tooltip.bottom {
margin-top: 3px;
padding: 5px 0;
}
.tooltip.left {
margin-left: -3px;
padding: 0 5px;
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #fff;
text-align: center;
background-color: #000;
border-radius: 2px;
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.tooltip.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-left .tooltip-arrow {
bottom: 0;
right: 5px;
margin-bottom: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-right .tooltip-arrow {
bottom: 0;
left: 5px;
margin-bottom: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-width: 5px 5px 5px 0;
border-right-color: #000;
}
.tooltip.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-width: 5px 0 5px 5px;
border-left-color: #000;
}
.tooltip.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-left .tooltip-arrow {
top: 0;
right: 5px;
margin-top: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-right .tooltip-arrow {
top: 0;
left: 5px;
margin-top: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1060;
display: none;
max-width: 276px;
padding: 1px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-style: normal;
font-weight: normal;
letter-spacing: normal;
line-break: auto;
line-height: 1.42857143;
text-align: left;
text-align: start;
text-decoration: none;
text-shadow: none;
text-transform: none;
white-space: normal;
word-break: normal;
word-spacing: normal;
word-wrap: normal;
font-size: 13px;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}
.popover.top {
margin-top: -10px;
}
.popover.right {
margin-left: 10px;
}
.popover.bottom {
margin-top: 10px;
}
.popover.left {
margin-left: -10px;
}
.popover-title {
margin: 0;
padding: 8px 14px;
font-size: 13px;
background-color: #f7f7f7;
border-bottom: 1px solid #ebebeb;
border-radius: 2px 2px 0 0;
}
.popover-content {
padding: 9px 14px;
}
.popover > .arrow,
.popover > .arrow:after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.popover > .arrow {
border-width: 11px;
}
.popover > .arrow:after {
border-width: 10px;
content: "";
}
.popover.top > .arrow {
left: 50%;
margin-left: -11px;
border-bottom-width: 0;
border-top-color: #999999;
border-top-color: rgba(0, 0, 0, 0.25);
bottom: -11px;
}
.popover.top > .arrow:after {
content: " ";
bottom: 1px;
margin-left: -10px;
border-bottom-width: 0;
border-top-color: #fff;
}
.popover.right > .arrow {
top: 50%;
left: -11px;
margin-top: -11px;
border-left-width: 0;
border-right-color: #999999;
border-right-color: rgba(0, 0, 0, 0.25);
}
.popover.right > .arrow:after {
content: " ";
left: 1px;
bottom: -10px;
border-left-width: 0;
border-right-color: #fff;
}
.popover.bottom > .arrow {
left: 50%;
margin-left: -11px;
border-top-width: 0;
border-bottom-color: #999999;
border-bottom-color: rgba(0, 0, 0, 0.25);
top: -11px;
}
.popover.bottom > .arrow:after {
content: " ";
top: 1px;
margin-left: -10px;
border-top-width: 0;
border-bottom-color: #fff;
}
.popover.left > .arrow {
top: 50%;
right: -11px;
margin-top: -11px;
border-right-width: 0;
border-left-color: #999999;
border-left-color: rgba(0, 0, 0, 0.25);
}
.popover.left > .arrow:after {
content: " ";
right: 1px;
border-right-width: 0;
border-left-color: #fff;
bottom: -10px;
}
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
overflow: hidden;
width: 100%;
}
.carousel-inner > .item {
display: none;
position: relative;
-webkit-transition: 0.6s ease-in-out left;
-o-transition: 0.6s ease-in-out left;
transition: 0.6s ease-in-out left;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
}
@media all and (transform-3d), (-webkit-transform-3d) {
.carousel-inner > .item {
-webkit-transition: -webkit-transform 0.6s ease-in-out;
-moz-transition: -moz-transform 0.6s ease-in-out;
-o-transition: -o-transform 0.6s ease-in-out;
transition: transform 0.6s ease-in-out;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-perspective: 1000px;
-moz-perspective: 1000px;
perspective: 1000px;
}
.carousel-inner > .item.next,
.carousel-inner > .item.active.right {
-webkit-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
left: 0;
}
.carousel-inner > .item.prev,
.carousel-inner > .item.active.left {
-webkit-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0);
left: 0;
}
.carousel-inner > .item.next.left,
.carousel-inner > .item.prev.right,
.carousel-inner > .item.active {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
left: 0;
}
}
.carousel-inner > .active,
.carousel-inner > .next,
.carousel-inner > .prev {
display: block;
}
.carousel-inner > .active {
left: 0;
}
.carousel-inner > .next,
.carousel-inner > .prev {
position: absolute;
top: 0;
width: 100%;
}
.carousel-inner > .next {
left: 100%;
}
.carousel-inner > .prev {
left: -100%;
}
.carousel-inner > .next.left,
.carousel-inner > .prev.right {
left: 0;
}
.carousel-inner > .active.left {
left: -100%;
}
.carousel-inner > .active.right {
left: 100%;
}
.carousel-control {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 15%;
opacity: 0.5;
filter: alpha(opacity=50);
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
background-color: rgba(0, 0, 0, 0);
}
.carousel-control.left {
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);
background-image: linear-gradient(to right, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
}
.carousel-control.right {
left: auto;
right: 0;
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);
background-image: linear-gradient(to right, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
}
.carousel-control:hover,
.carousel-control:focus {
outline: 0;
color: #fff;
text-decoration: none;
opacity: 0.9;
filter: alpha(opacity=90);
}
.carousel-control .icon-prev,
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
position: absolute;
top: 50%;
margin-top: -10px;
z-index: 5;
display: inline-block;
}
.carousel-control .icon-prev,
.carousel-control .glyphicon-chevron-left {
left: 50%;
margin-left: -10px;
}
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-right {
right: 50%;
margin-right: -10px;
}
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 20px;
height: 20px;
line-height: 1;
font-family: serif;
}
.carousel-control .icon-prev:before {
content: '\2039';
}
.carousel-control .icon-next:before {
content: '\203a';
}
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
z-index: 15;
width: 60%;
margin-left: -30%;
padding-left: 0;
list-style: none;
text-align: center;
}
.carousel-indicators li {
display: inline-block;
width: 10px;
height: 10px;
margin: 1px;
text-indent: -999px;
border: 1px solid #fff;
border-radius: 10px;
cursor: pointer;
background-color: #000 \9;
background-color: rgba(0, 0, 0, 0);
}
.carousel-indicators .active {
margin: 0;
width: 12px;
height: 12px;
background-color: #fff;
}
.carousel-caption {
position: absolute;
left: 15%;
right: 15%;
bottom: 20px;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
}
.carousel-caption .btn {
text-shadow: none;
}
@media screen and (min-width: 768px) {
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 30px;
height: 30px;
margin-top: -10px;
font-size: 30px;
}
.carousel-control .glyphicon-chevron-left,
.carousel-control .icon-prev {
margin-left: -10px;
}
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-next {
margin-right: -10px;
}
.carousel-caption {
left: 20%;
right: 20%;
padding-bottom: 30px;
}
.carousel-indicators {
bottom: 20px;
}
}
.clearfix:before,
.clearfix:after,
.dl-horizontal dd:before,
.dl-horizontal dd:after,
.container:before,
.container:after,
.container-fluid:before,
.container-fluid:after,
.row:before,
.row:after,
.form-horizontal .form-group:before,
.form-horizontal .form-group:after,
.btn-toolbar:before,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:before,
.btn-group-vertical > .btn-group:after,
.nav:before,
.nav:after,
.navbar:before,
.navbar:after,
.navbar-header:before,
.navbar-header:after,
.navbar-collapse:before,
.navbar-collapse:after,
.pager:before,
.pager:after,
.panel-body:before,
.panel-body:after,
.modal-header:before,
.modal-header:after,
.modal-footer:before,
.modal-footer:after,
.item_buttons:before,
.item_buttons:after {
content: " ";
display: table;
}
.clearfix:after,
.dl-horizontal dd:after,
.container:after,
.container-fluid:after,
.row:after,
.form-horizontal .form-group:after,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:after,
.nav:after,
.navbar:after,
.navbar-header:after,
.navbar-collapse:after,
.pager:after,
.panel-body:after,
.modal-header:after,
.modal-footer:after,
.item_buttons:after {
clear: both;
}
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
.pull-right {
float: right !important;
}
.pull-left {
float: left !important;
}
.hide {
display: none !important;
}
.show {
display: block !important;
}
.invisible {
visibility: hidden;
}
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.hidden {
display: none !important;
}
.affix {
position: fixed;
}
@-ms-viewport {
width: device-width;
}
.visible-xs,
.visible-sm,
.visible-md,
.visible-lg {
display: none !important;
}
.visible-xs-block,
.visible-xs-inline,
.visible-xs-inline-block,
.visible-sm-block,
.visible-sm-inline,
.visible-sm-inline-block,
.visible-md-block,
.visible-md-inline,
.visible-md-inline-block,
.visible-lg-block,
.visible-lg-inline,
.visible-lg-inline-block {
display: none !important;
}
@media (max-width: 767px) {
.visible-xs {
display: block !important;
}
table.visible-xs {
display: table !important;
}
tr.visible-xs {
display: table-row !important;
}
th.visible-xs,
td.visible-xs {
display: table-cell !important;
}
}
@media (max-width: 767px) {
.visible-xs-block {
display: block !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline {
display: inline !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline-block {
display: inline-block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm {
display: block !important;
}
table.visible-sm {
display: table !important;
}
tr.visible-sm {
display: table-row !important;
}
th.visible-sm,
td.visible-sm {
display: table-cell !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-block {
display: block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline {
display: inline !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline-block {
display: inline-block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md {
display: block !important;
}
table.visible-md {
display: table !important;
}
tr.visible-md {
display: table-row !important;
}
th.visible-md,
td.visible-md {
display: table-cell !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-block {
display: block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline {
display: inline !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline-block {
display: inline-block !important;
}
}
@media (min-width: 1200px) {
.visible-lg {
display: block !important;
}
table.visible-lg {
display: table !important;
}
tr.visible-lg {
display: table-row !important;
}
th.visible-lg,
td.visible-lg {
display: table-cell !important;
}
}
@media (min-width: 1200px) {
.visible-lg-block {
display: block !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline {
display: inline !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline-block {
display: inline-block !important;
}
}
@media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.hidden-sm {
display: none !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.hidden-md {
display: none !important;
}
}
@media (min-width: 1200px) {
.hidden-lg {
display: none !important;
}
}
.visible-print {
display: none !important;
}
@media print {
.visible-print {
display: block !important;
}
table.visible-print {
display: table !important;
}
tr.visible-print {
display: table-row !important;
}
th.visible-print,
td.visible-print {
display: table-cell !important;
}
}
.visible-print-block {
display: none !important;
}
@media print {
.visible-print-block {
display: block !important;
}
}
.visible-print-inline {
display: none !important;
}
@media print {
.visible-print-inline {
display: inline !important;
}
}
.visible-print-inline-block {
display: none !important;
}
@media print {
.visible-print-inline-block {
display: inline-block !important;
}
}
@media print {
.hidden-print {
display: none !important;
}
}
/*!
*
* Font Awesome
*
*/
/*!
* Font Awesome 4.2.0 by @davegandy - http://fontawesome.io - @fontawesome
* License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
*/
/* FONT PATH
* -------------------------- */
@font-face {
font-family: 'FontAwesome';
src: url('../components/font-awesome/fonts/fontawesome-webfont.eot?v=4.2.0');
src: url('../components/font-awesome/fonts/fontawesome-webfont.eot?#iefix&v=4.2.0') format('embedded-opentype'), url('../components/font-awesome/fonts/fontawesome-webfont.woff?v=4.2.0') format('woff'), url('../components/font-awesome/fonts/fontawesome-webfont.ttf?v=4.2.0') format('truetype'), url('../components/font-awesome/fonts/fontawesome-webfont.svg?v=4.2.0#fontawesomeregular') format('svg');
font-weight: normal;
font-style: normal;
}
.fa {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* makes the font 33% larger relative to the icon container */
.fa-lg {
font-size: 1.33333333em;
line-height: 0.75em;
vertical-align: -15%;
}
.fa-2x {
font-size: 2em;
}
.fa-3x {
font-size: 3em;
}
.fa-4x {
font-size: 4em;
}
.fa-5x {
font-size: 5em;
}
.fa-fw {
width: 1.28571429em;
text-align: center;
}
.fa-ul {
padding-left: 0;
margin-left: 2.14285714em;
list-style-type: none;
}
.fa-ul > li {
position: relative;
}
.fa-li {
position: absolute;
left: -2.14285714em;
width: 2.14285714em;
top: 0.14285714em;
text-align: center;
}
.fa-li.fa-lg {
left: -1.85714286em;
}
.fa-border {
padding: .2em .25em .15em;
border: solid 0.08em #eee;
border-radius: .1em;
}
.pull-right {
float: right;
}
.pull-left {
float: left;
}
.fa.pull-left {
margin-right: .3em;
}
.fa.pull-right {
margin-left: .3em;
}
.fa-spin {
-webkit-animation: fa-spin 2s infinite linear;
animation: fa-spin 2s infinite linear;
}
@-webkit-keyframes fa-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@keyframes fa-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
.fa-rotate-90 {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
.fa-rotate-180 {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
-webkit-transform: rotate(180deg);
-ms-transform: rotate(180deg);
transform: rotate(180deg);
}
.fa-rotate-270 {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
-webkit-transform: rotate(270deg);
-ms-transform: rotate(270deg);
transform: rotate(270deg);
}
.fa-flip-horizontal {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1);
-webkit-transform: scale(-1, 1);
-ms-transform: scale(-1, 1);
transform: scale(-1, 1);
}
.fa-flip-vertical {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1);
-webkit-transform: scale(1, -1);
-ms-transform: scale(1, -1);
transform: scale(1, -1);
}
:root .fa-rotate-90,
:root .fa-rotate-180,
:root .fa-rotate-270,
:root .fa-flip-horizontal,
:root .fa-flip-vertical {
filter: none;
}
.fa-stack {
position: relative;
display: inline-block;
width: 2em;
height: 2em;
line-height: 2em;
vertical-align: middle;
}
.fa-stack-1x,
.fa-stack-2x {
position: absolute;
left: 0;
width: 100%;
text-align: center;
}
.fa-stack-1x {
line-height: inherit;
}
.fa-stack-2x {
font-size: 2em;
}
.fa-inverse {
color: #fff;
}
/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen
readers do not read off random characters that represent icons */
.fa-glass:before {
content: "\f000";
}
.fa-music:before {
content: "\f001";
}
.fa-search:before {
content: "\f002";
}
.fa-envelope-o:before {
content: "\f003";
}
.fa-heart:before {
content: "\f004";
}
.fa-star:before {
content: "\f005";
}
.fa-star-o:before {
content: "\f006";
}
.fa-user:before {
content: "\f007";
}
.fa-film:before {
content: "\f008";
}
.fa-th-large:before {
content: "\f009";
}
.fa-th:before {
content: "\f00a";
}
.fa-th-list:before {
content: "\f00b";
}
.fa-check:before {
content: "\f00c";
}
.fa-remove:before,
.fa-close:before,
.fa-times:before {
content: "\f00d";
}
.fa-search-plus:before {
content: "\f00e";
}
.fa-search-minus:before {
content: "\f010";
}
.fa-power-off:before {
content: "\f011";
}
.fa-signal:before {
content: "\f012";
}
.fa-gear:before,
.fa-cog:before {
content: "\f013";
}
.fa-trash-o:before {
content: "\f014";
}
.fa-home:before {
content: "\f015";
}
.fa-file-o:before {
content: "\f016";
}
.fa-clock-o:before {
content: "\f017";
}
.fa-road:before {
content: "\f018";
}
.fa-download:before {
content: "\f019";
}
.fa-arrow-circle-o-down:before {
content: "\f01a";
}
.fa-arrow-circle-o-up:before {
content: "\f01b";
}
.fa-inbox:before {
content: "\f01c";
}
.fa-play-circle-o:before {
content: "\f01d";
}
.fa-rotate-right:before,
.fa-repeat:before {
content: "\f01e";
}
.fa-refresh:before {
content: "\f021";
}
.fa-list-alt:before {
content: "\f022";
}
.fa-lock:before {
content: "\f023";
}
.fa-flag:before {
content: "\f024";
}
.fa-headphones:before {
content: "\f025";
}
.fa-volume-off:before {
content: "\f026";
}
.fa-volume-down:before {
content: "\f027";
}
.fa-volume-up:before {
content: "\f028";
}
.fa-qrcode:before {
content: "\f029";
}
.fa-barcode:before {
content: "\f02a";
}
.fa-tag:before {
content: "\f02b";
}
.fa-tags:before {
content: "\f02c";
}
.fa-book:before {
content: "\f02d";
}
.fa-bookmark:before {
content: "\f02e";
}
.fa-print:before {
content: "\f02f";
}
.fa-camera:before {
content: "\f030";
}
.fa-font:before {
content: "\f031";
}
.fa-bold:before {
content: "\f032";
}
.fa-italic:before {
content: "\f033";
}
.fa-text-height:before {
content: "\f034";
}
.fa-text-width:before {
content: "\f035";
}
.fa-align-left:before {
content: "\f036";
}
.fa-align-center:before {
content: "\f037";
}
.fa-align-right:before {
content: "\f038";
}
.fa-align-justify:before {
content: "\f039";
}
.fa-list:before {
content: "\f03a";
}
.fa-dedent:before,
.fa-outdent:before {
content: "\f03b";
}
.fa-indent:before {
content: "\f03c";
}
.fa-video-camera:before {
content: "\f03d";
}
.fa-photo:before,
.fa-image:before,
.fa-picture-o:before {
content: "\f03e";
}
.fa-pencil:before {
content: "\f040";
}
.fa-map-marker:before {
content: "\f041";
}
.fa-adjust:before {
content: "\f042";
}
.fa-tint:before {
content: "\f043";
}
.fa-edit:before,
.fa-pencil-square-o:before {
content: "\f044";
}
.fa-share-square-o:before {
content: "\f045";
}
.fa-check-square-o:before {
content: "\f046";
}
.fa-arrows:before {
content: "\f047";
}
.fa-step-backward:before {
content: "\f048";
}
.fa-fast-backward:before {
content: "\f049";
}
.fa-backward:before {
content: "\f04a";
}
.fa-play:before {
content: "\f04b";
}
.fa-pause:before {
content: "\f04c";
}
.fa-stop:before {
content: "\f04d";
}
.fa-forward:before {
content: "\f04e";
}
.fa-fast-forward:before {
content: "\f050";
}
.fa-step-forward:before {
content: "\f051";
}
.fa-eject:before {
content: "\f052";
}
.fa-chevron-left:before {
content: "\f053";
}
.fa-chevron-right:before {
content: "\f054";
}
.fa-plus-circle:before {
content: "\f055";
}
.fa-minus-circle:before {
content: "\f056";
}
.fa-times-circle:before {
content: "\f057";
}
.fa-check-circle:before {
content: "\f058";
}
.fa-question-circle:before {
content: "\f059";
}
.fa-info-circle:before {
content: "\f05a";
}
.fa-crosshairs:before {
content: "\f05b";
}
.fa-times-circle-o:before {
content: "\f05c";
}
.fa-check-circle-o:before {
content: "\f05d";
}
.fa-ban:before {
content: "\f05e";
}
.fa-arrow-left:before {
content: "\f060";
}
.fa-arrow-right:before {
content: "\f061";
}
.fa-arrow-up:before {
content: "\f062";
}
.fa-arrow-down:before {
content: "\f063";
}
.fa-mail-forward:before,
.fa-share:before {
content: "\f064";
}
.fa-expand:before {
content: "\f065";
}
.fa-compress:before {
content: "\f066";
}
.fa-plus:before {
content: "\f067";
}
.fa-minus:before {
content: "\f068";
}
.fa-asterisk:before {
content: "\f069";
}
.fa-exclamation-circle:before {
content: "\f06a";
}
.fa-gift:before {
content: "\f06b";
}
.fa-leaf:before {
content: "\f06c";
}
.fa-fire:before {
content: "\f06d";
}
.fa-eye:before {
content: "\f06e";
}
.fa-eye-slash:before {
content: "\f070";
}
.fa-warning:before,
.fa-exclamation-triangle:before {
content: "\f071";
}
.fa-plane:before {
content: "\f072";
}
.fa-calendar:before {
content: "\f073";
}
.fa-random:before {
content: "\f074";
}
.fa-comment:before {
content: "\f075";
}
.fa-magnet:before {
content: "\f076";
}
.fa-chevron-up:before {
content: "\f077";
}
.fa-chevron-down:before {
content: "\f078";
}
.fa-retweet:before {
content: "\f079";
}
.fa-shopping-cart:before {
content: "\f07a";
}
.fa-folder:before {
content: "\f07b";
}
.fa-folder-open:before {
content: "\f07c";
}
.fa-arrows-v:before {
content: "\f07d";
}
.fa-arrows-h:before {
content: "\f07e";
}
.fa-bar-chart-o:before,
.fa-bar-chart:before {
content: "\f080";
}
.fa-twitter-square:before {
content: "\f081";
}
.fa-facebook-square:before {
content: "\f082";
}
.fa-camera-retro:before {
content: "\f083";
}
.fa-key:before {
content: "\f084";
}
.fa-gears:before,
.fa-cogs:before {
content: "\f085";
}
.fa-comments:before {
content: "\f086";
}
.fa-thumbs-o-up:before {
content: "\f087";
}
.fa-thumbs-o-down:before {
content: "\f088";
}
.fa-star-half:before {
content: "\f089";
}
.fa-heart-o:before {
content: "\f08a";
}
.fa-sign-out:before {
content: "\f08b";
}
.fa-linkedin-square:before {
content: "\f08c";
}
.fa-thumb-tack:before {
content: "\f08d";
}
.fa-external-link:before {
content: "\f08e";
}
.fa-sign-in:before {
content: "\f090";
}
.fa-trophy:before {
content: "\f091";
}
.fa-github-square:before {
content: "\f092";
}
.fa-upload:before {
content: "\f093";
}
.fa-lemon-o:before {
content: "\f094";
}
.fa-phone:before {
content: "\f095";
}
.fa-square-o:before {
content: "\f096";
}
.fa-bookmark-o:before {
content: "\f097";
}
.fa-phone-square:before {
content: "\f098";
}
.fa-twitter:before {
content: "\f099";
}
.fa-facebook:before {
content: "\f09a";
}
.fa-github:before {
content: "\f09b";
}
.fa-unlock:before {
content: "\f09c";
}
.fa-credit-card:before {
content: "\f09d";
}
.fa-rss:before {
content: "\f09e";
}
.fa-hdd-o:before {
content: "\f0a0";
}
.fa-bullhorn:before {
content: "\f0a1";
}
.fa-bell:before {
content: "\f0f3";
}
.fa-certificate:before {
content: "\f0a3";
}
.fa-hand-o-right:before {
content: "\f0a4";
}
.fa-hand-o-left:before {
content: "\f0a5";
}
.fa-hand-o-up:before {
content: "\f0a6";
}
.fa-hand-o-down:before {
content: "\f0a7";
}
.fa-arrow-circle-left:before {
content: "\f0a8";
}
.fa-arrow-circle-right:before {
content: "\f0a9";
}
.fa-arrow-circle-up:before {
content: "\f0aa";
}
.fa-arrow-circle-down:before {
content: "\f0ab";
}
.fa-globe:before {
content: "\f0ac";
}
.fa-wrench:before {
content: "\f0ad";
}
.fa-tasks:before {
content: "\f0ae";
}
.fa-filter:before {
content: "\f0b0";
}
.fa-briefcase:before {
content: "\f0b1";
}
.fa-arrows-alt:before {
content: "\f0b2";
}
.fa-group:before,
.fa-users:before {
content: "\f0c0";
}
.fa-chain:before,
.fa-link:before {
content: "\f0c1";
}
.fa-cloud:before {
content: "\f0c2";
}
.fa-flask:before {
content: "\f0c3";
}
.fa-cut:before,
.fa-scissors:before {
content: "\f0c4";
}
.fa-copy:before,
.fa-files-o:before {
content: "\f0c5";
}
.fa-paperclip:before {
content: "\f0c6";
}
.fa-save:before,
.fa-floppy-o:before {
content: "\f0c7";
}
.fa-square:before {
content: "\f0c8";
}
.fa-navicon:before,
.fa-reorder:before,
.fa-bars:before {
content: "\f0c9";
}
.fa-list-ul:before {
content: "\f0ca";
}
.fa-list-ol:before {
content: "\f0cb";
}
.fa-strikethrough:before {
content: "\f0cc";
}
.fa-underline:before {
content: "\f0cd";
}
.fa-table:before {
content: "\f0ce";
}
.fa-magic:before {
content: "\f0d0";
}
.fa-truck:before {
content: "\f0d1";
}
.fa-pinterest:before {
content: "\f0d2";
}
.fa-pinterest-square:before {
content: "\f0d3";
}
.fa-google-plus-square:before {
content: "\f0d4";
}
.fa-google-plus:before {
content: "\f0d5";
}
.fa-money:before {
content: "\f0d6";
}
.fa-caret-down:before {
content: "\f0d7";
}
.fa-caret-up:before {
content: "\f0d8";
}
.fa-caret-left:before {
content: "\f0d9";
}
.fa-caret-right:before {
content: "\f0da";
}
.fa-columns:before {
content: "\f0db";
}
.fa-unsorted:before,
.fa-sort:before {
content: "\f0dc";
}
.fa-sort-down:before,
.fa-sort-desc:before {
content: "\f0dd";
}
.fa-sort-up:before,
.fa-sort-asc:before {
content: "\f0de";
}
.fa-envelope:before {
content: "\f0e0";
}
.fa-linkedin:before {
content: "\f0e1";
}
.fa-rotate-left:before,
.fa-undo:before {
content: "\f0e2";
}
.fa-legal:before,
.fa-gavel:before {
content: "\f0e3";
}
.fa-dashboard:before,
.fa-tachometer:before {
content: "\f0e4";
}
.fa-comment-o:before {
content: "\f0e5";
}
.fa-comments-o:before {
content: "\f0e6";
}
.fa-flash:before,
.fa-bolt:before {
content: "\f0e7";
}
.fa-sitemap:before {
content: "\f0e8";
}
.fa-umbrella:before {
content: "\f0e9";
}
.fa-paste:before,
.fa-clipboard:before {
content: "\f0ea";
}
.fa-lightbulb-o:before {
content: "\f0eb";
}
.fa-exchange:before {
content: "\f0ec";
}
.fa-cloud-download:before {
content: "\f0ed";
}
.fa-cloud-upload:before {
content: "\f0ee";
}
.fa-user-md:before {
content: "\f0f0";
}
.fa-stethoscope:before {
content: "\f0f1";
}
.fa-suitcase:before {
content: "\f0f2";
}
.fa-bell-o:before {
content: "\f0a2";
}
.fa-coffee:before {
content: "\f0f4";
}
.fa-cutlery:before {
content: "\f0f5";
}
.fa-file-text-o:before {
content: "\f0f6";
}
.fa-building-o:before {
content: "\f0f7";
}
.fa-hospital-o:before {
content: "\f0f8";
}
.fa-ambulance:before {
content: "\f0f9";
}
.fa-medkit:before {
content: "\f0fa";
}
.fa-fighter-jet:before {
content: "\f0fb";
}
.fa-beer:before {
content: "\f0fc";
}
.fa-h-square:before {
content: "\f0fd";
}
.fa-plus-square:before {
content: "\f0fe";
}
.fa-angle-double-left:before {
content: "\f100";
}
.fa-angle-double-right:before {
content: "\f101";
}
.fa-angle-double-up:before {
content: "\f102";
}
.fa-angle-double-down:before {
content: "\f103";
}
.fa-angle-left:before {
content: "\f104";
}
.fa-angle-right:before {
content: "\f105";
}
.fa-angle-up:before {
content: "\f106";
}
.fa-angle-down:before {
content: "\f107";
}
.fa-desktop:before {
content: "\f108";
}
.fa-laptop:before {
content: "\f109";
}
.fa-tablet:before {
content: "\f10a";
}
.fa-mobile-phone:before,
.fa-mobile:before {
content: "\f10b";
}
.fa-circle-o:before {
content: "\f10c";
}
.fa-quote-left:before {
content: "\f10d";
}
.fa-quote-right:before {
content: "\f10e";
}
.fa-spinner:before {
content: "\f110";
}
.fa-circle:before {
content: "\f111";
}
.fa-mail-reply:before,
.fa-reply:before {
content: "\f112";
}
.fa-github-alt:before {
content: "\f113";
}
.fa-folder-o:before {
content: "\f114";
}
.fa-folder-open-o:before {
content: "\f115";
}
.fa-smile-o:before {
content: "\f118";
}
.fa-frown-o:before {
content: "\f119";
}
.fa-meh-o:before {
content: "\f11a";
}
.fa-gamepad:before {
content: "\f11b";
}
.fa-keyboard-o:before {
content: "\f11c";
}
.fa-flag-o:before {
content: "\f11d";
}
.fa-flag-checkered:before {
content: "\f11e";
}
.fa-terminal:before {
content: "\f120";
}
.fa-code:before {
content: "\f121";
}
.fa-mail-reply-all:before,
.fa-reply-all:before {
content: "\f122";
}
.fa-star-half-empty:before,
.fa-star-half-full:before,
.fa-star-half-o:before {
content: "\f123";
}
.fa-location-arrow:before {
content: "\f124";
}
.fa-crop:before {
content: "\f125";
}
.fa-code-fork:before {
content: "\f126";
}
.fa-unlink:before,
.fa-chain-broken:before {
content: "\f127";
}
.fa-question:before {
content: "\f128";
}
.fa-info:before {
content: "\f129";
}
.fa-exclamation:before {
content: "\f12a";
}
.fa-superscript:before {
content: "\f12b";
}
.fa-subscript:before {
content: "\f12c";
}
.fa-eraser:before {
content: "\f12d";
}
.fa-puzzle-piece:before {
content: "\f12e";
}
.fa-microphone:before {
content: "\f130";
}
.fa-microphone-slash:before {
content: "\f131";
}
.fa-shield:before {
content: "\f132";
}
.fa-calendar-o:before {
content: "\f133";
}
.fa-fire-extinguisher:before {
content: "\f134";
}
.fa-rocket:before {
content: "\f135";
}
.fa-maxcdn:before {
content: "\f136";
}
.fa-chevron-circle-left:before {
content: "\f137";
}
.fa-chevron-circle-right:before {
content: "\f138";
}
.fa-chevron-circle-up:before {
content: "\f139";
}
.fa-chevron-circle-down:before {
content: "\f13a";
}
.fa-html5:before {
content: "\f13b";
}
.fa-css3:before {
content: "\f13c";
}
.fa-anchor:before {
content: "\f13d";
}
.fa-unlock-alt:before {
content: "\f13e";
}
.fa-bullseye:before {
content: "\f140";
}
.fa-ellipsis-h:before {
content: "\f141";
}
.fa-ellipsis-v:before {
content: "\f142";
}
.fa-rss-square:before {
content: "\f143";
}
.fa-play-circle:before {
content: "\f144";
}
.fa-ticket:before {
content: "\f145";
}
.fa-minus-square:before {
content: "\f146";
}
.fa-minus-square-o:before {
content: "\f147";
}
.fa-level-up:before {
content: "\f148";
}
.fa-level-down:before {
content: "\f149";
}
.fa-check-square:before {
content: "\f14a";
}
.fa-pencil-square:before {
content: "\f14b";
}
.fa-external-link-square:before {
content: "\f14c";
}
.fa-share-square:before {
content: "\f14d";
}
.fa-compass:before {
content: "\f14e";
}
.fa-toggle-down:before,
.fa-caret-square-o-down:before {
content: "\f150";
}
.fa-toggle-up:before,
.fa-caret-square-o-up:before {
content: "\f151";
}
.fa-toggle-right:before,
.fa-caret-square-o-right:before {
content: "\f152";
}
.fa-euro:before,
.fa-eur:before {
content: "\f153";
}
.fa-gbp:before {
content: "\f154";
}
.fa-dollar:before,
.fa-usd:before {
content: "\f155";
}
.fa-rupee:before,
.fa-inr:before {
content: "\f156";
}
.fa-cny:before,
.fa-rmb:before,
.fa-yen:before,
.fa-jpy:before {
content: "\f157";
}
.fa-ruble:before,
.fa-rouble:before,
.fa-rub:before {
content: "\f158";
}
.fa-won:before,
.fa-krw:before {
content: "\f159";
}
.fa-bitcoin:before,
.fa-btc:before {
content: "\f15a";
}
.fa-file:before {
content: "\f15b";
}
.fa-file-text:before {
content: "\f15c";
}
.fa-sort-alpha-asc:before {
content: "\f15d";
}
.fa-sort-alpha-desc:before {
content: "\f15e";
}
.fa-sort-amount-asc:before {
content: "\f160";
}
.fa-sort-amount-desc:before {
content: "\f161";
}
.fa-sort-numeric-asc:before {
content: "\f162";
}
.fa-sort-numeric-desc:before {
content: "\f163";
}
.fa-thumbs-up:before {
content: "\f164";
}
.fa-thumbs-down:before {
content: "\f165";
}
.fa-youtube-square:before {
content: "\f166";
}
.fa-youtube:before {
content: "\f167";
}
.fa-xing:before {
content: "\f168";
}
.fa-xing-square:before {
content: "\f169";
}
.fa-youtube-play:before {
content: "\f16a";
}
.fa-dropbox:before {
content: "\f16b";
}
.fa-stack-overflow:before {
content: "\f16c";
}
.fa-instagram:before {
content: "\f16d";
}
.fa-flickr:before {
content: "\f16e";
}
.fa-adn:before {
content: "\f170";
}
.fa-bitbucket:before {
content: "\f171";
}
.fa-bitbucket-square:before {
content: "\f172";
}
.fa-tumblr:before {
content: "\f173";
}
.fa-tumblr-square:before {
content: "\f174";
}
.fa-long-arrow-down:before {
content: "\f175";
}
.fa-long-arrow-up:before {
content: "\f176";
}
.fa-long-arrow-left:before {
content: "\f177";
}
.fa-long-arrow-right:before {
content: "\f178";
}
.fa-apple:before {
content: "\f179";
}
.fa-windows:before {
content: "\f17a";
}
.fa-android:before {
content: "\f17b";
}
.fa-linux:before {
content: "\f17c";
}
.fa-dribbble:before {
content: "\f17d";
}
.fa-skype:before {
content: "\f17e";
}
.fa-foursquare:before {
content: "\f180";
}
.fa-trello:before {
content: "\f181";
}
.fa-female:before {
content: "\f182";
}
.fa-male:before {
content: "\f183";
}
.fa-gittip:before {
content: "\f184";
}
.fa-sun-o:before {
content: "\f185";
}
.fa-moon-o:before {
content: "\f186";
}
.fa-archive:before {
content: "\f187";
}
.fa-bug:before {
content: "\f188";
}
.fa-vk:before {
content: "\f189";
}
.fa-weibo:before {
content: "\f18a";
}
.fa-renren:before {
content: "\f18b";
}
.fa-pagelines:before {
content: "\f18c";
}
.fa-stack-exchange:before {
content: "\f18d";
}
.fa-arrow-circle-o-right:before {
content: "\f18e";
}
.fa-arrow-circle-o-left:before {
content: "\f190";
}
.fa-toggle-left:before,
.fa-caret-square-o-left:before {
content: "\f191";
}
.fa-dot-circle-o:before {
content: "\f192";
}
.fa-wheelchair:before {
content: "\f193";
}
.fa-vimeo-square:before {
content: "\f194";
}
.fa-turkish-lira:before,
.fa-try:before {
content: "\f195";
}
.fa-plus-square-o:before {
content: "\f196";
}
.fa-space-shuttle:before {
content: "\f197";
}
.fa-slack:before {
content: "\f198";
}
.fa-envelope-square:before {
content: "\f199";
}
.fa-wordpress:before {
content: "\f19a";
}
.fa-openid:before {
content: "\f19b";
}
.fa-institution:before,
.fa-bank:before,
.fa-university:before {
content: "\f19c";
}
.fa-mortar-board:before,
.fa-graduation-cap:before {
content: "\f19d";
}
.fa-yahoo:before {
content: "\f19e";
}
.fa-google:before {
content: "\f1a0";
}
.fa-reddit:before {
content: "\f1a1";
}
.fa-reddit-square:before {
content: "\f1a2";
}
.fa-stumbleupon-circle:before {
content: "\f1a3";
}
.fa-stumbleupon:before {
content: "\f1a4";
}
.fa-delicious:before {
content: "\f1a5";
}
.fa-digg:before {
content: "\f1a6";
}
.fa-pied-piper:before {
content: "\f1a7";
}
.fa-pied-piper-alt:before {
content: "\f1a8";
}
.fa-drupal:before {
content: "\f1a9";
}
.fa-joomla:before {
content: "\f1aa";
}
.fa-language:before {
content: "\f1ab";
}
.fa-fax:before {
content: "\f1ac";
}
.fa-building:before {
content: "\f1ad";
}
.fa-child:before {
content: "\f1ae";
}
.fa-paw:before {
content: "\f1b0";
}
.fa-spoon:before {
content: "\f1b1";
}
.fa-cube:before {
content: "\f1b2";
}
.fa-cubes:before {
content: "\f1b3";
}
.fa-behance:before {
content: "\f1b4";
}
.fa-behance-square:before {
content: "\f1b5";
}
.fa-steam:before {
content: "\f1b6";
}
.fa-steam-square:before {
content: "\f1b7";
}
.fa-recycle:before {
content: "\f1b8";
}
.fa-automobile:before,
.fa-car:before {
content: "\f1b9";
}
.fa-cab:before,
.fa-taxi:before {
content: "\f1ba";
}
.fa-tree:before {
content: "\f1bb";
}
.fa-spotify:before {
content: "\f1bc";
}
.fa-deviantart:before {
content: "\f1bd";
}
.fa-soundcloud:before {
content: "\f1be";
}
.fa-database:before {
content: "\f1c0";
}
.fa-file-pdf-o:before {
content: "\f1c1";
}
.fa-file-word-o:before {
content: "\f1c2";
}
.fa-file-excel-o:before {
content: "\f1c3";
}
.fa-file-powerpoint-o:before {
content: "\f1c4";
}
.fa-file-photo-o:before,
.fa-file-picture-o:before,
.fa-file-image-o:before {
content: "\f1c5";
}
.fa-file-zip-o:before,
.fa-file-archive-o:before {
content: "\f1c6";
}
.fa-file-sound-o:before,
.fa-file-audio-o:before {
content: "\f1c7";
}
.fa-file-movie-o:before,
.fa-file-video-o:before {
content: "\f1c8";
}
.fa-file-code-o:before {
content: "\f1c9";
}
.fa-vine:before {
content: "\f1ca";
}
.fa-codepen:before {
content: "\f1cb";
}
.fa-jsfiddle:before {
content: "\f1cc";
}
.fa-life-bouy:before,
.fa-life-buoy:before,
.fa-life-saver:before,
.fa-support:before,
.fa-life-ring:before {
content: "\f1cd";
}
.fa-circle-o-notch:before {
content: "\f1ce";
}
.fa-ra:before,
.fa-rebel:before {
content: "\f1d0";
}
.fa-ge:before,
.fa-empire:before {
content: "\f1d1";
}
.fa-git-square:before {
content: "\f1d2";
}
.fa-git:before {
content: "\f1d3";
}
.fa-hacker-news:before {
content: "\f1d4";
}
.fa-tencent-weibo:before {
content: "\f1d5";
}
.fa-qq:before {
content: "\f1d6";
}
.fa-wechat:before,
.fa-weixin:before {
content: "\f1d7";
}
.fa-send:before,
.fa-paper-plane:before {
content: "\f1d8";
}
.fa-send-o:before,
.fa-paper-plane-o:before {
content: "\f1d9";
}
.fa-history:before {
content: "\f1da";
}
.fa-circle-thin:before {
content: "\f1db";
}
.fa-header:before {
content: "\f1dc";
}
.fa-paragraph:before {
content: "\f1dd";
}
.fa-sliders:before {
content: "\f1de";
}
.fa-share-alt:before {
content: "\f1e0";
}
.fa-share-alt-square:before {
content: "\f1e1";
}
.fa-bomb:before {
content: "\f1e2";
}
.fa-soccer-ball-o:before,
.fa-futbol-o:before {
content: "\f1e3";
}
.fa-tty:before {
content: "\f1e4";
}
.fa-binoculars:before {
content: "\f1e5";
}
.fa-plug:before {
content: "\f1e6";
}
.fa-slideshare:before {
content: "\f1e7";
}
.fa-twitch:before {
content: "\f1e8";
}
.fa-yelp:before {
content: "\f1e9";
}
.fa-newspaper-o:before {
content: "\f1ea";
}
.fa-wifi:before {
content: "\f1eb";
}
.fa-calculator:before {
content: "\f1ec";
}
.fa-paypal:before {
content: "\f1ed";
}
.fa-google-wallet:before {
content: "\f1ee";
}
.fa-cc-visa:before {
content: "\f1f0";
}
.fa-cc-mastercard:before {
content: "\f1f1";
}
.fa-cc-discover:before {
content: "\f1f2";
}
.fa-cc-amex:before {
content: "\f1f3";
}
.fa-cc-paypal:before {
content: "\f1f4";
}
.fa-cc-stripe:before {
content: "\f1f5";
}
.fa-bell-slash:before {
content: "\f1f6";
}
.fa-bell-slash-o:before {
content: "\f1f7";
}
.fa-trash:before {
content: "\f1f8";
}
.fa-copyright:before {
content: "\f1f9";
}
.fa-at:before {
content: "\f1fa";
}
.fa-eyedropper:before {
content: "\f1fb";
}
.fa-paint-brush:before {
content: "\f1fc";
}
.fa-birthday-cake:before {
content: "\f1fd";
}
.fa-area-chart:before {
content: "\f1fe";
}
.fa-pie-chart:before {
content: "\f200";
}
.fa-line-chart:before {
content: "\f201";
}
.fa-lastfm:before {
content: "\f202";
}
.fa-lastfm-square:before {
content: "\f203";
}
.fa-toggle-off:before {
content: "\f204";
}
.fa-toggle-on:before {
content: "\f205";
}
.fa-bicycle:before {
content: "\f206";
}
.fa-bus:before {
content: "\f207";
}
.fa-ioxhost:before {
content: "\f208";
}
.fa-angellist:before {
content: "\f209";
}
.fa-cc:before {
content: "\f20a";
}
.fa-shekel:before,
.fa-sheqel:before,
.fa-ils:before {
content: "\f20b";
}
.fa-meanpath:before {
content: "\f20c";
}
/*!
*
* IPython base
*
*/
.modal.fade .modal-dialog {
-webkit-transform: translate(0, 0);
-ms-transform: translate(0, 0);
-o-transform: translate(0, 0);
transform: translate(0, 0);
}
code {
color: #000;
}
pre {
font-size: inherit;
line-height: inherit;
}
label {
font-weight: normal;
}
/* Make the page background atleast 100% the height of the view port */
/* Make the page itself atleast 70% the height of the view port */
.border-box-sizing {
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
.corner-all {
border-radius: 2px;
}
.no-padding {
padding: 0px;
}
/* Flexible box model classes */
/* Taken from <NAME> http://infrequently.org/2009/08/css-3-progress/ */
/* This file is a compatability layer. It allows the usage of flexible box
model layouts accross multiple browsers, including older browsers. The newest,
universal implementation of the flexible box model is used when available (see
`Modern browsers` comments below). Browsers that are known to implement this
new spec completely include:
Firefox 28.0+
Chrome 29.0+
Internet Explorer 11+
Opera 17.0+
Browsers not listed, including Safari, are supported via the styling under the
`Old browsers` comments below.
*/
.hbox {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-align: stretch;
display: box;
box-orient: horizontal;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: row;
align-items: stretch;
}
.hbox > * {
/* Old browsers */
-webkit-box-flex: 0;
-moz-box-flex: 0;
box-flex: 0;
/* Modern browsers */
flex: none;
}
.vbox {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
}
.vbox > * {
/* Old browsers */
-webkit-box-flex: 0;
-moz-box-flex: 0;
box-flex: 0;
/* Modern browsers */
flex: none;
}
.hbox.reverse,
.vbox.reverse,
.reverse {
/* Old browsers */
-webkit-box-direction: reverse;
-moz-box-direction: reverse;
box-direction: reverse;
/* Modern browsers */
flex-direction: row-reverse;
}
.hbox.box-flex0,
.vbox.box-flex0,
.box-flex0 {
/* Old browsers */
-webkit-box-flex: 0;
-moz-box-flex: 0;
box-flex: 0;
/* Modern browsers */
flex: none;
width: auto;
}
.hbox.box-flex1,
.vbox.box-flex1,
.box-flex1 {
/* Old browsers */
-webkit-box-flex: 1;
-moz-box-flex: 1;
box-flex: 1;
/* Modern browsers */
flex: 1;
}
.hbox.box-flex,
.vbox.box-flex,
.box-flex {
/* Old browsers */
/* Old browsers */
-webkit-box-flex: 1;
-moz-box-flex: 1;
box-flex: 1;
/* Modern browsers */
flex: 1;
}
.hbox.box-flex2,
.vbox.box-flex2,
.box-flex2 {
/* Old browsers */
-webkit-box-flex: 2;
-moz-box-flex: 2;
box-flex: 2;
/* Modern browsers */
flex: 2;
}
.box-group1 {
/* Deprecated */
-webkit-box-flex-group: 1;
-moz-box-flex-group: 1;
box-flex-group: 1;
}
.box-group2 {
/* Deprecated */
-webkit-box-flex-group: 2;
-moz-box-flex-group: 2;
box-flex-group: 2;
}
.hbox.start,
.vbox.start,
.start {
/* Old browsers */
-webkit-box-pack: start;
-moz-box-pack: start;
box-pack: start;
/* Modern browsers */
justify-content: flex-start;
}
.hbox.end,
.vbox.end,
.end {
/* Old browsers */
-webkit-box-pack: end;
-moz-box-pack: end;
box-pack: end;
/* Modern browsers */
justify-content: flex-end;
}
.hbox.center,
.vbox.center,
.center {
/* Old browsers */
-webkit-box-pack: center;
-moz-box-pack: center;
box-pack: center;
/* Modern browsers */
justify-content: center;
}
.hbox.baseline,
.vbox.baseline,
.baseline {
/* Old browsers */
-webkit-box-pack: baseline;
-moz-box-pack: baseline;
box-pack: baseline;
/* Modern browsers */
justify-content: baseline;
}
.hbox.stretch,
.vbox.stretch,
.stretch {
/* Old browsers */
-webkit-box-pack: stretch;
-moz-box-pack: stretch;
box-pack: stretch;
/* Modern browsers */
justify-content: stretch;
}
.hbox.align-start,
.vbox.align-start,
.align-start {
/* Old browsers */
-webkit-box-align: start;
-moz-box-align: start;
box-align: start;
/* Modern browsers */
align-items: flex-start;
}
.hbox.align-end,
.vbox.align-end,
.align-end {
/* Old browsers */
-webkit-box-align: end;
-moz-box-align: end;
box-align: end;
/* Modern browsers */
align-items: flex-end;
}
.hbox.align-center,
.vbox.align-center,
.align-center {
/* Old browsers */
-webkit-box-align: center;
-moz-box-align: center;
box-align: center;
/* Modern browsers */
align-items: center;
}
.hbox.align-baseline,
.vbox.align-baseline,
.align-baseline {
/* Old browsers */
-webkit-box-align: baseline;
-moz-box-align: baseline;
box-align: baseline;
/* Modern browsers */
align-items: baseline;
}
.hbox.align-stretch,
.vbox.align-stretch,
.align-stretch {
/* Old browsers */
-webkit-box-align: stretch;
-moz-box-align: stretch;
box-align: stretch;
/* Modern browsers */
align-items: stretch;
}
div.error {
margin: 2em;
text-align: center;
}
div.error > h1 {
font-size: 500%;
line-height: normal;
}
div.error > p {
font-size: 200%;
line-height: normal;
}
div.traceback-wrapper {
text-align: left;
max-width: 800px;
margin: auto;
}
/**
* Primary styles
*
* Author: Jupyter Development Team
*/
body {
background-color: #fff;
/* This makes sure that the body covers the entire window and needs to
be in a different element than the display: box in wrapper below */
position: absolute;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
overflow: visible;
}
body > #header {
/* Initially hidden to prevent FLOUC */
display: none;
background-color: #fff;
/* Display over codemirror */
position: relative;
z-index: 100;
}
body > #header #header-container {
padding-bottom: 5px;
padding-top: 5px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
body > #header .header-bar {
width: 100%;
height: 1px;
background: #e7e7e7;
margin-bottom: -1px;
}
@media print {
body > #header {
display: none !important;
}
}
#header-spacer {
width: 100%;
visibility: hidden;
}
@media print {
#header-spacer {
display: none;
}
}
#ipython_notebook {
padding-left: 0px;
padding-top: 1px;
padding-bottom: 1px;
}
@media (max-width: 991px) {
#ipython_notebook {
margin-left: 10px;
}
}
[dir="rtl"] #ipython_notebook {
float: right !important;
}
#noscript {
width: auto;
padding-top: 16px;
padding-bottom: 16px;
text-align: center;
font-size: 22px;
color: red;
font-weight: bold;
}
#ipython_notebook img {
height: 28px;
}
#site {
width: 100%;
display: none;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
overflow: auto;
}
@media print {
#site {
height: auto !important;
}
}
/* Smaller buttons */
.ui-button .ui-button-text {
padding: 0.2em 0.8em;
font-size: 77%;
}
input.ui-button {
padding: 0.3em 0.9em;
}
span#login_widget {
float: right;
}
span#login_widget > .button,
#logout {
color: #333;
background-color: #fff;
border-color: #ccc;
}
span#login_widget > .button:focus,
#logout:focus,
span#login_widget > .button.focus,
#logout.focus {
color: #333;
background-color: #e6e6e6;
border-color: #8c8c8c;
}
span#login_widget > .button:hover,
#logout:hover {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
span#login_widget > .button:active,
#logout:active,
span#login_widget > .button.active,
#logout.active,
.open > .dropdown-togglespan#login_widget > .button,
.open > .dropdown-toggle#logout {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
span#login_widget > .button:active:hover,
#logout:active:hover,
span#login_widget > .button.active:hover,
#logout.active:hover,
.open > .dropdown-togglespan#login_widget > .button:hover,
.open > .dropdown-toggle#logout:hover,
span#login_widget > .button:active:focus,
#logout:active:focus,
span#login_widget > .button.active:focus,
#logout.active:focus,
.open > .dropdown-togglespan#login_widget > .button:focus,
.open > .dropdown-toggle#logout:focus,
span#login_widget > .button:active.focus,
#logout:active.focus,
span#login_widget > .button.active.focus,
#logout.active.focus,
.open > .dropdown-togglespan#login_widget > .button.focus,
.open > .dropdown-toggle#logout.focus {
color: #333;
background-color: #d4d4d4;
border-color: #8c8c8c;
}
span#login_widget > .button:active,
#logout:active,
span#login_widget > .button.active,
#logout.active,
.open > .dropdown-togglespan#login_widget > .button,
.open > .dropdown-toggle#logout {
background-image: none;
}
span#login_widget > .button.disabled:hover,
#logout.disabled:hover,
span#login_widget > .button[disabled]:hover,
#logout[disabled]:hover,
fieldset[disabled] span#login_widget > .button:hover,
fieldset[disabled] #logout:hover,
span#login_widget > .button.disabled:focus,
#logout.disabled:focus,
span#login_widget > .button[disabled]:focus,
#logout[disabled]:focus,
fieldset[disabled] span#login_widget > .button:focus,
fieldset[disabled] #logout:focus,
span#login_widget > .button.disabled.focus,
#logout.disabled.focus,
span#login_widget > .button[disabled].focus,
#logout[disabled].focus,
fieldset[disabled] span#login_widget > .button.focus,
fieldset[disabled] #logout.focus {
background-color: #fff;
border-color: #ccc;
}
span#login_widget > .button .badge,
#logout .badge {
color: #fff;
background-color: #333;
}
.nav-header {
text-transform: none;
}
#header > span {
margin-top: 10px;
}
.modal_stretch .modal-dialog {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
min-height: 80vh;
}
.modal_stretch .modal-dialog .modal-body {
max-height: calc(100vh - 200px);
overflow: auto;
flex: 1;
}
@media (min-width: 768px) {
.modal .modal-dialog {
width: 700px;
}
}
@media (min-width: 768px) {
select.form-control {
margin-left: 12px;
margin-right: 12px;
}
}
/*!
*
* IPython auth
*
*/
.center-nav {
display: inline-block;
margin-bottom: -4px;
}
/*!
*
* IPython tree view
*
*/
/* We need an invisible input field on top of the sentense*/
/* "Drag file onto the list ..." */
.alternate_upload {
background-color: none;
display: inline;
}
.alternate_upload.form {
padding: 0;
margin: 0;
}
.alternate_upload input.fileinput {
text-align: center;
vertical-align: middle;
display: inline;
opacity: 0;
z-index: 2;
width: 12ex;
margin-right: -12ex;
}
.alternate_upload .btn-upload {
height: 22px;
}
/**
* Primary styles
*
* Author: Jupyter Development Team
*/
[dir="rtl"] #tabs li {
float: right;
}
ul#tabs {
margin-bottom: 4px;
}
[dir="rtl"] ul#tabs {
margin-right: 0px;
}
ul#tabs a {
padding-top: 6px;
padding-bottom: 4px;
}
ul.breadcrumb a:focus,
ul.breadcrumb a:hover {
text-decoration: none;
}
ul.breadcrumb i.icon-home {
font-size: 16px;
margin-right: 4px;
}
ul.breadcrumb span {
color: #5e5e5e;
}
.list_toolbar {
padding: 4px 0 4px 0;
vertical-align: middle;
}
.list_toolbar .tree-buttons {
padding-top: 1px;
}
[dir="rtl"] .list_toolbar .tree-buttons {
float: left !important;
}
[dir="rtl"] .list_toolbar .pull-right {
padding-top: 1px;
float: left !important;
}
[dir="rtl"] .list_toolbar .pull-left {
float: right !important;
}
.dynamic-buttons {
padding-top: 3px;
display: inline-block;
}
.list_toolbar [class*="span"] {
min-height: 24px;
}
.list_header {
font-weight: bold;
background-color: #EEE;
}
.list_placeholder {
font-weight: bold;
padding-top: 4px;
padding-bottom: 4px;
padding-left: 7px;
padding-right: 7px;
}
.list_container {
margin-top: 4px;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 2px;
}
.list_container > div {
border-bottom: 1px solid #ddd;
}
.list_container > div:hover .list-item {
background-color: red;
}
.list_container > div:last-child {
border: none;
}
.list_item:hover .list_item {
background-color: #ddd;
}
.list_item a {
text-decoration: none;
}
.list_item:hover {
background-color: #fafafa;
}
.list_header > div,
.list_item > div {
padding-top: 4px;
padding-bottom: 4px;
padding-left: 7px;
padding-right: 7px;
line-height: 22px;
}
.list_header > div input,
.list_item > div input {
margin-right: 7px;
margin-left: 14px;
vertical-align: baseline;
line-height: 22px;
position: relative;
top: -1px;
}
.list_header > div .item_link,
.list_item > div .item_link {
margin-left: -1px;
vertical-align: baseline;
line-height: 22px;
}
.new-file input[type=checkbox] {
visibility: hidden;
}
.item_name {
line-height: 22px;
height: 24px;
}
.item_icon {
font-size: 14px;
color: #5e5e5e;
margin-right: 7px;
margin-left: 7px;
line-height: 22px;
vertical-align: baseline;
}
.item_buttons {
line-height: 1em;
margin-left: -5px;
}
.item_buttons .btn,
.item_buttons .btn-group,
.item_buttons .input-group {
float: left;
}
.item_buttons > .btn,
.item_buttons > .btn-group,
.item_buttons > .input-group {
margin-left: 5px;
}
.item_buttons .btn {
min-width: 13ex;
}
.item_buttons .running-indicator {
padding-top: 4px;
color: #5cb85c;
}
.item_buttons .kernel-name {
padding-top: 4px;
color: #5bc0de;
margin-right: 7px;
float: left;
}
.toolbar_info {
height: 24px;
line-height: 24px;
}
.list_item input:not([type=checkbox]) {
padding-top: 3px;
padding-bottom: 3px;
height: 22px;
line-height: 14px;
margin: 0px;
}
.highlight_text {
color: blue;
}
#project_name {
display: inline-block;
padding-left: 7px;
margin-left: -2px;
}
#project_name > .breadcrumb {
padding: 0px;
margin-bottom: 0px;
background-color: transparent;
font-weight: bold;
}
#tree-selector {
padding-right: 0px;
}
[dir="rtl"] #tree-selector a {
float: right;
}
#button-select-all {
min-width: 50px;
}
#select-all {
margin-left: 7px;
margin-right: 2px;
}
.menu_icon {
margin-right: 2px;
}
.tab-content .row {
margin-left: 0px;
margin-right: 0px;
}
.folder_icon:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\f114";
}
.folder_icon:before.pull-left {
margin-right: .3em;
}
.folder_icon:before.pull-right {
margin-left: .3em;
}
.notebook_icon:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\f02d";
position: relative;
top: -1px;
}
.notebook_icon:before.pull-left {
margin-right: .3em;
}
.notebook_icon:before.pull-right {
margin-left: .3em;
}
.running_notebook_icon:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\f02d";
position: relative;
top: -1px;
color: #5cb85c;
}
.running_notebook_icon:before.pull-left {
margin-right: .3em;
}
.running_notebook_icon:before.pull-right {
margin-left: .3em;
}
.file_icon:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\f016";
position: relative;
top: -2px;
}
.file_icon:before.pull-left {
margin-right: .3em;
}
.file_icon:before.pull-right {
margin-left: .3em;
}
#notebook_toolbar .pull-right {
padding-top: 0px;
margin-right: -1px;
}
ul#new-menu {
left: auto;
right: 0;
}
[dir="rtl"] #new-menu {
text-align: right;
}
.kernel-menu-icon {
padding-right: 12px;
width: 24px;
content: "\f096";
}
.kernel-menu-icon:before {
content: "\f096";
}
.kernel-menu-icon-current:before {
content: "\f00c";
}
#tab_content {
padding-top: 20px;
}
#running .panel-group .panel {
margin-top: 3px;
margin-bottom: 1em;
}
#running .panel-group .panel .panel-heading {
background-color: #EEE;
padding-top: 4px;
padding-bottom: 4px;
padding-left: 7px;
padding-right: 7px;
line-height: 22px;
}
#running .panel-group .panel .panel-heading a:focus,
#running .panel-group .panel .panel-heading a:hover {
text-decoration: none;
}
#running .panel-group .panel .panel-body {
padding: 0px;
}
#running .panel-group .panel .panel-body .list_container {
margin-top: 0px;
margin-bottom: 0px;
border: 0px;
border-radius: 0px;
}
#running .panel-group .panel .panel-body .list_container .list_item {
border-bottom: 1px solid #ddd;
}
#running .panel-group .panel .panel-body .list_container .list_item:last-child {
border-bottom: 0px;
}
[dir="rtl"] #running .col-sm-8 {
float: right !important;
}
.delete-button {
display: none;
}
.duplicate-button {
display: none;
}
.rename-button {
display: none;
}
.shutdown-button {
display: none;
}
.dynamic-instructions {
display: inline-block;
padding-top: 4px;
}
/*!
*
* IPython text editor webapp
*
*/
.selected-keymap i.fa {
padding: 0px 5px;
}
.selected-keymap i.fa:before {
content: "\f00c";
}
#mode-menu {
overflow: auto;
max-height: 20em;
}
.edit_app #header {
-webkit-box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
}
.edit_app #menubar .navbar {
/* Use a negative 1 bottom margin, so the border overlaps the border of the
header */
margin-bottom: -1px;
}
.dirty-indicator {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
width: 20px;
}
.dirty-indicator.pull-left {
margin-right: .3em;
}
.dirty-indicator.pull-right {
margin-left: .3em;
}
.dirty-indicator-dirty {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
width: 20px;
}
.dirty-indicator-dirty.pull-left {
margin-right: .3em;
}
.dirty-indicator-dirty.pull-right {
margin-left: .3em;
}
.dirty-indicator-clean {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
width: 20px;
}
.dirty-indicator-clean.pull-left {
margin-right: .3em;
}
.dirty-indicator-clean.pull-right {
margin-left: .3em;
}
.dirty-indicator-clean:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\f00c";
}
.dirty-indicator-clean:before.pull-left {
margin-right: .3em;
}
.dirty-indicator-clean:before.pull-right {
margin-left: .3em;
}
#filename {
font-size: 16pt;
display: table;
padding: 0px 5px;
}
#current-mode {
padding-left: 5px;
padding-right: 5px;
}
#texteditor-backdrop {
padding-top: 20px;
padding-bottom: 20px;
}
@media not print {
#texteditor-backdrop {
background-color: #EEE;
}
}
@media print {
#texteditor-backdrop #texteditor-container .CodeMirror-gutter,
#texteditor-backdrop #texteditor-container .CodeMirror-gutters {
background-color: #fff;
}
}
@media not print {
#texteditor-backdrop #texteditor-container .CodeMirror-gutter,
#texteditor-backdrop #texteditor-container .CodeMirror-gutters {
background-color: #fff;
}
}
@media not print {
#texteditor-backdrop #texteditor-container {
padding: 0px;
background-color: #fff;
-webkit-box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
}
}
/*!
*
* IPython notebook
*
*/
/* CSS font colors for translated ANSI colors. */
.ansibold {
font-weight: bold;
}
/* use dark versions for foreground, to improve visibility */
.ansiblack {
color: black;
}
.ansired {
color: darkred;
}
.ansigreen {
color: darkgreen;
}
.ansiyellow {
color: #c4a000;
}
.ansiblue {
color: darkblue;
}
.ansipurple {
color: darkviolet;
}
.ansicyan {
color: steelblue;
}
.ansigray {
color: gray;
}
/* and light for background, for the same reason */
.ansibgblack {
background-color: black;
}
.ansibgred {
background-color: red;
}
.ansibggreen {
background-color: green;
}
.ansibgyellow {
background-color: yellow;
}
.ansibgblue {
background-color: blue;
}
.ansibgpurple {
background-color: magenta;
}
.ansibgcyan {
background-color: cyan;
}
.ansibggray {
background-color: gray;
}
div.cell {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
border-radius: 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
border-width: 1px;
border-style: solid;
border-color: transparent;
width: 100%;
padding: 5px;
/* This acts as a spacer between cells, that is outside the border */
margin: 0px;
outline: none;
border-left-width: 1px;
padding-left: 5px;
background: linear-gradient(to right, transparent -40px, transparent 1px, transparent 1px, transparent 100%);
}
div.cell.jupyter-soft-selected {
border-left-color: #90CAF9;
border-left-color: #E3F2FD;
border-left-width: 1px;
padding-left: 5px;
border-right-color: #E3F2FD;
border-right-width: 1px;
background: #E3F2FD;
}
@media print {
div.cell.jupyter-soft-selected {
border-color: transparent;
}
}
div.cell.selected {
border-color: #ababab;
border-left-width: 0px;
padding-left: 6px;
background: linear-gradient(to right, #42A5F5 -40px, #42A5F5 5px, transparent 5px, transparent 100%);
}
@media print {
div.cell.selected {
border-color: transparent;
}
}
div.cell.selected.jupyter-soft-selected {
border-left-width: 0;
padding-left: 6px;
background: linear-gradient(to right, #42A5F5 -40px, #42A5F5 7px, #E3F2FD 7px, #E3F2FD 100%);
}
.edit_mode div.cell.selected {
border-color: #66BB6A;
border-left-width: 0px;
padding-left: 6px;
background: linear-gradient(to right, #66BB6A -40px, #66BB6A 5px, transparent 5px, transparent 100%);
}
@media print {
.edit_mode div.cell.selected {
border-color: transparent;
}
}
.prompt {
/* This needs to be wide enough for 3 digit prompt numbers: In[100]: */
min-width: 14ex;
/* This padding is tuned to match the padding on the CodeMirror editor. */
padding: 0.4em;
margin: 0px;
font-family: monospace;
text-align: right;
/* This has to match that of the the CodeMirror class line-height below */
line-height: 1.21429em;
/* Don't highlight prompt number selection */
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
/* Use default cursor */
cursor: default;
}
@media (max-width: 540px) {
.prompt {
text-align: left;
}
}
div.inner_cell {
min-width: 0;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
/* Old browsers */
-webkit-box-flex: 1;
-moz-box-flex: 1;
box-flex: 1;
/* Modern browsers */
flex: 1;
}
/* input_area and input_prompt must match in top border and margin for alignment */
div.input_area {
border: 1px solid #cfcfcf;
border-radius: 2px;
background: #f7f7f7;
line-height: 1.21429em;
}
/* This is needed so that empty prompt areas can collapse to zero height when there
is no content in the output_subarea and the prompt. The main purpose of this is
to make sure that empty JavaScript output_subareas have no height. */
div.prompt:empty {
padding-top: 0;
padding-bottom: 0;
}
div.unrecognized_cell {
padding: 5px 5px 5px 0px;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-align: stretch;
display: box;
box-orient: horizontal;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: row;
align-items: stretch;
}
div.unrecognized_cell .inner_cell {
border-radius: 2px;
padding: 5px;
font-weight: bold;
color: red;
border: 1px solid #cfcfcf;
background: #eaeaea;
}
div.unrecognized_cell .inner_cell a {
color: inherit;
text-decoration: none;
}
div.unrecognized_cell .inner_cell a:hover {
color: inherit;
text-decoration: none;
}
@media (max-width: 540px) {
div.unrecognized_cell > div.prompt {
display: none;
}
}
div.code_cell {
/* avoid page breaking on code cells when printing */
}
@media print {
div.code_cell {
page-break-inside: avoid;
}
}
/* any special styling for code cells that are currently running goes here */
div.input {
page-break-inside: avoid;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-align: stretch;
display: box;
box-orient: horizontal;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: row;
align-items: stretch;
}
@media (max-width: 540px) {
div.input {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
}
}
/* input_area and input_prompt must match in top border and margin for alignment */
div.input_prompt {
color: #303F9F;
border-top: 1px solid transparent;
}
div.input_area > div.highlight {
margin: 0.4em;
border: none;
padding: 0px;
background-color: transparent;
}
div.input_area > div.highlight > pre {
margin: 0px;
border: none;
padding: 0px;
background-color: transparent;
}
/* The following gets added to the <head> if it is detected that the user has a
* monospace font with inconsistent normal/bold/italic height. See
* notebookmain.js. Such fonts will have keywords vertically offset with
* respect to the rest of the text. The user should select a better font.
* See: https://github.com/ipython/ipython/issues/1503
*
* .CodeMirror span {
* vertical-align: bottom;
* }
*/
.CodeMirror {
line-height: 1.21429em;
/* Changed from 1em to our global default */
font-size: 14px;
height: auto;
/* Changed to auto to autogrow */
background: none;
/* Changed from white to allow our bg to show through */
}
.CodeMirror-scroll {
/* The CodeMirror docs are a bit fuzzy on if overflow-y should be hidden or visible.*/
/* We have found that if it is visible, vertical scrollbars appear with font size changes.*/
overflow-y: hidden;
overflow-x: auto;
}
.CodeMirror-lines {
/* In CM2, this used to be 0.4em, but in CM3 it went to 4px. We need the em value because */
/* we have set a different line-height and want this to scale with that. */
padding: 0.4em;
}
.CodeMirror-linenumber {
padding: 0 8px 0 4px;
}
.CodeMirror-gutters {
border-bottom-left-radius: 2px;
border-top-left-radius: 2px;
}
.CodeMirror pre {
/* In CM3 this went to 4px from 0 in CM2. We need the 0 value because of how we size */
/* .CodeMirror-lines */
padding: 0;
border: 0;
border-radius: 0;
}
/*
Original style from softwaremaniacs.org (c) <NAME> <<EMAIL>>
Adapted from GitHub theme
*/
.highlight-base {
color: #000;
}
.highlight-variable {
color: #000;
}
.highlight-variable-2 {
color: #1a1a1a;
}
.highlight-variable-3 {
color: #333333;
}
.highlight-string {
color: #BA2121;
}
.highlight-comment {
color: #408080;
font-style: italic;
}
.highlight-number {
color: #080;
}
.highlight-atom {
color: #88F;
}
.highlight-keyword {
color: #008000;
font-weight: bold;
}
.highlight-builtin {
color: #008000;
}
.highlight-error {
color: #f00;
}
.highlight-operator {
color: #AA22FF;
font-weight: bold;
}
.highlight-meta {
color: #AA22FF;
}
/* previously not defined, copying from default codemirror */
.highlight-def {
color: #00f;
}
.highlight-string-2 {
color: #f50;
}
.highlight-qualifier {
color: #555;
}
.highlight-bracket {
color: #997;
}
.highlight-tag {
color: #170;
}
.highlight-attribute {
color: #00c;
}
.highlight-header {
color: blue;
}
.highlight-quote {
color: #090;
}
.highlight-link {
color: #00c;
}
/* apply the same style to codemirror */
.cm-s-ipython span.cm-keyword {
color: #008000;
font-weight: bold;
}
.cm-s-ipython span.cm-atom {
color: #88F;
}
.cm-s-ipython span.cm-number {
color: #080;
}
.cm-s-ipython span.cm-def {
color: #00f;
}
.cm-s-ipython span.cm-variable {
color: #000;
}
.cm-s-ipython span.cm-operator {
color: #AA22FF;
font-weight: bold;
}
.cm-s-ipython span.cm-variable-2 {
color: #1a1a1a;
}
.cm-s-ipython span.cm-variable-3 {
color: #333333;
}
.cm-s-ipython span.cm-comment {
color: #408080;
font-style: italic;
}
.cm-s-ipython span.cm-string {
color: #BA2121;
}
.cm-s-ipython span.cm-string-2 {
color: #f50;
}
.cm-s-ipython span.cm-meta {
color: #AA22FF;
}
.cm-s-ipython span.cm-qualifier {
color: #555;
}
.cm-s-ipython span.cm-builtin {
color: #008000;
}
.cm-s-ipython span.cm-bracket {
color: #997;
}
.cm-s-ipython span.cm-tag {
color: #170;
}
.cm-s-ipython span.cm-attribute {
color: #00c;
}
.cm-s-ipython span.cm-header {
color: blue;
}
.cm-s-ipython span.cm-quote {
color: #090;
}
.cm-s-ipython span.cm-link {
color: #00c;
}
.cm-s-ipython span.cm-error {
color: #f00;
}
.cm-s-ipython span.cm-tab {
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=);
background-position: right;
background-repeat: no-repeat;
}
div.output_wrapper {
/* this position must be relative to enable descendents to be absolute within it */
position: relative;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
z-index: 1;
}
/* class for the output area when it should be height-limited */
div.output_scroll {
/* ideally, this would be max-height, but FF barfs all over that */
height: 24em;
/* FF needs this *and the wrapper* to specify full width, or it will shrinkwrap */
width: 100%;
overflow: auto;
border-radius: 2px;
-webkit-box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.8);
box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.8);
display: block;
}
/* output div while it is collapsed */
div.output_collapsed {
margin: 0px;
padding: 0px;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
}
div.out_prompt_overlay {
height: 100%;
padding: 0px 0.4em;
position: absolute;
border-radius: 2px;
}
div.out_prompt_overlay:hover {
/* use inner shadow to get border that is computed the same on WebKit/FF */
-webkit-box-shadow: inset 0 0 1px #000;
box-shadow: inset 0 0 1px #000;
background: rgba(240, 240, 240, 0.5);
}
div.output_prompt {
color: #D84315;
}
/* This class is the outer container of all output sections. */
div.output_area {
padding: 0px;
page-break-inside: avoid;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-align: stretch;
display: box;
box-orient: horizontal;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: row;
align-items: stretch;
}
div.output_area .MathJax_Display {
text-align: left !important;
}
div.output_area .rendered_html table {
margin-left: 0;
margin-right: 0;
}
div.output_area .rendered_html img {
margin-left: 0;
margin-right: 0;
}
div.output_area img,
div.output_area svg {
max-width: 100%;
height: auto;
}
div.output_area img.unconfined,
div.output_area svg.unconfined {
max-width: none;
}
/* This is needed to protect the pre formating from global settings such
as that of bootstrap */
.output {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
}
@media (max-width: 540px) {
div.output_area {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
}
}
div.output_area pre {
margin: 0;
padding: 0;
border: 0;
vertical-align: baseline;
color: black;
background-color: transparent;
border-radius: 0;
}
/* This class is for the output subarea inside the output_area and after
the prompt div. */
div.output_subarea {
overflow-x: auto;
padding: 0.4em;
/* Old browsers */
-webkit-box-flex: 1;
-moz-box-flex: 1;
box-flex: 1;
/* Modern browsers */
flex: 1;
max-width: calc(100% - 14ex);
}
div.output_scroll div.output_subarea {
overflow-x: visible;
}
/* The rest of the output_* classes are for special styling of the different
output types */
/* all text output has this class: */
div.output_text {
text-align: left;
color: #000;
/* This has to match that of the the CodeMirror class line-height below */
line-height: 1.21429em;
}
/* stdout/stderr are 'text' as well as 'stream', but execute_result/error are *not* streams */
div.output_stderr {
background: #fdd;
/* very light red background for stderr */
}
div.output_latex {
text-align: left;
}
/* Empty output_javascript divs should have no height */
div.output_javascript:empty {
padding: 0;
}
.js-error {
color: darkred;
}
/* raw_input styles */
div.raw_input_container {
line-height: 1.21429em;
padding-top: 5px;
}
pre.raw_input_prompt {
/* nothing needed here. */
}
input.raw_input {
font-family: monospace;
font-size: inherit;
color: inherit;
width: auto;
/* make sure input baseline aligns with prompt */
vertical-align: baseline;
/* padding + margin = 0.5em between prompt and cursor */
padding: 0em 0.25em;
margin: 0em 0.25em;
}
input.raw_input:focus {
box-shadow: none;
}
p.p-space {
margin-bottom: 10px;
}
div.output_unrecognized {
padding: 5px;
font-weight: bold;
color: red;
}
div.output_unrecognized a {
color: inherit;
text-decoration: none;
}
div.output_unrecognized a:hover {
color: inherit;
text-decoration: none;
}
.rendered_html {
color: #000;
/* any extras will just be numbers: */
}
.rendered_html em {
font-style: italic;
}
.rendered_html strong {
font-weight: bold;
}
.rendered_html u {
text-decoration: underline;
}
.rendered_html :link {
text-decoration: underline;
}
.rendered_html :visited {
text-decoration: underline;
}
.rendered_html h1 {
font-size: 185.7%;
margin: 1.08em 0 0 0;
font-weight: bold;
line-height: 1.0;
}
.rendered_html h2 {
font-size: 157.1%;
margin: 1.27em 0 0 0;
font-weight: bold;
line-height: 1.0;
}
.rendered_html h3 {
font-size: 128.6%;
margin: 1.55em 0 0 0;
font-weight: bold;
line-height: 1.0;
}
.rendered_html h4 {
font-size: 100%;
margin: 2em 0 0 0;
font-weight: bold;
line-height: 1.0;
}
.rendered_html h5 {
font-size: 100%;
margin: 2em 0 0 0;
font-weight: bold;
line-height: 1.0;
font-style: italic;
}
.rendered_html h6 {
font-size: 100%;
margin: 2em 0 0 0;
font-weight: bold;
line-height: 1.0;
font-style: italic;
}
.rendered_html h1:first-child {
margin-top: 0.538em;
}
.rendered_html h2:first-child {
margin-top: 0.636em;
}
.rendered_html h3:first-child {
margin-top: 0.777em;
}
.rendered_html h4:first-child {
margin-top: 1em;
}
.rendered_html h5:first-child {
margin-top: 1em;
}
.rendered_html h6:first-child {
margin-top: 1em;
}
.rendered_html ul {
list-style: disc;
margin: 0em 2em;
padding-left: 0px;
}
.rendered_html ul ul {
list-style: square;
margin: 0em 2em;
}
.rendered_html ul ul ul {
list-style: circle;
margin: 0em 2em;
}
.rendered_html ol {
list-style: decimal;
margin: 0em 2em;
padding-left: 0px;
}
.rendered_html ol ol {
list-style: upper-alpha;
margin: 0em 2em;
}
.rendered_html ol ol ol {
list-style: lower-alpha;
margin: 0em 2em;
}
.rendered_html ol ol ol ol {
list-style: lower-roman;
margin: 0em 2em;
}
.rendered_html ol ol ol ol ol {
list-style: decimal;
margin: 0em 2em;
}
.rendered_html * + ul {
margin-top: 1em;
}
.rendered_html * + ol {
margin-top: 1em;
}
.rendered_html hr {
color: black;
background-color: black;
}
.rendered_html pre {
margin: 1em 2em;
}
.rendered_html pre,
.rendered_html code {
border: 0;
background-color: #fff;
color: #000;
font-size: 100%;
padding: 0px;
}
.rendered_html blockquote {
margin: 1em 2em;
}
.rendered_html table {
margin-left: auto;
margin-right: auto;
border: 1px solid black;
border-collapse: collapse;
}
.rendered_html tr,
.rendered_html th,
.rendered_html td {
border: 1px solid black;
border-collapse: collapse;
margin: 1em 2em;
}
.rendered_html td,
.rendered_html th {
text-align: left;
vertical-align: middle;
padding: 4px;
}
.rendered_html th {
font-weight: bold;
}
.rendered_html * + table {
margin-top: 1em;
}
.rendered_html p {
text-align: left;
}
.rendered_html * + p {
margin-top: 1em;
}
.rendered_html img {
display: block;
margin-left: auto;
margin-right: auto;
}
.rendered_html * + img {
margin-top: 1em;
}
.rendered_html img,
.rendered_html svg {
max-width: 100%;
height: auto;
}
.rendered_html img.unconfined,
.rendered_html svg.unconfined {
max-width: none;
}
div.text_cell {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-align: stretch;
display: box;
box-orient: horizontal;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: row;
align-items: stretch;
}
@media (max-width: 540px) {
div.text_cell > div.prompt {
display: none;
}
}
div.text_cell_render {
/*font-family: "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;*/
outline: none;
resize: none;
width: inherit;
border-style: none;
padding: 0.5em 0.5em 0.5em 0.4em;
color: #000;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
a.anchor-link:link {
text-decoration: none;
padding: 0px 20px;
visibility: hidden;
}
h1:hover .anchor-link,
h2:hover .anchor-link,
h3:hover .anchor-link,
h4:hover .anchor-link,
h5:hover .anchor-link,
h6:hover .anchor-link {
visibility: visible;
}
.text_cell.rendered .input_area {
display: none;
}
.text_cell.rendered .rendered_html {
overflow-x: auto;
overflow-y: hidden;
}
.text_cell.unrendered .text_cell_render {
display: none;
}
.cm-header-1,
.cm-header-2,
.cm-header-3,
.cm-header-4,
.cm-header-5,
.cm-header-6 {
font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.cm-header-1 {
font-size: 185.7%;
}
.cm-header-2 {
font-size: 157.1%;
}
.cm-header-3 {
font-size: 128.6%;
}
.cm-header-4 {
font-size: 110%;
}
.cm-header-5 {
font-size: 100%;
font-style: italic;
}
.cm-header-6 {
font-size: 100%;
font-style: italic;
}
/*!
*
* IPython notebook webapp
*
*/
@media (max-width: 767px) {
.notebook_app {
padding-left: 0px;
padding-right: 0px;
}
}
#ipython-main-app {
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
height: 100%;
}
div#notebook_panel {
margin: 0px;
padding: 0px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
height: 100%;
}
div#notebook {
font-size: 14px;
line-height: 20px;
overflow-y: hidden;
overflow-x: auto;
width: 100%;
/* This spaces the page away from the edge of the notebook area */
padding-top: 20px;
margin: 0px;
outline: none;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
min-height: 100%;
}
@media not print {
#notebook-container {
padding: 15px;
background-color: #fff;
min-height: 0;
-webkit-box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
}
}
@media print {
#notebook-container {
width: 100%;
}
}
div.ui-widget-content {
border: 1px solid #ababab;
outline: none;
}
pre.dialog {
background-color: #f7f7f7;
border: 1px solid #ddd;
border-radius: 2px;
padding: 0.4em;
padding-left: 2em;
}
p.dialog {
padding: 0.2em;
}
/* Word-wrap output correctly. This is the CSS3 spelling, though Firefox seems
to not honor it correctly. Webkit browsers (Chrome, rekonq, Safari) do.
*/
pre,
code,
kbd,
samp {
white-space: pre-wrap;
}
#fonttest {
font-family: monospace;
}
p {
margin-bottom: 0;
}
.end_space {
min-height: 100px;
transition: height .2s ease;
}
.notebook_app > #header {
-webkit-box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
}
@media not print {
.notebook_app {
background-color: #EEE;
}
}
kbd {
border-style: solid;
border-width: 1px;
box-shadow: none;
margin: 2px;
padding-left: 2px;
padding-right: 2px;
padding-top: 1px;
padding-bottom: 1px;
}
/* CSS for the cell toolbar */
.celltoolbar {
border: thin solid #CFCFCF;
border-bottom: none;
background: #EEE;
border-radius: 2px 2px 0px 0px;
width: 100%;
height: 29px;
padding-right: 4px;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-align: stretch;
display: box;
box-orient: horizontal;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: row;
align-items: stretch;
/* Old browsers */
-webkit-box-pack: end;
-moz-box-pack: end;
box-pack: end;
/* Modern browsers */
justify-content: flex-end;
display: -webkit-flex;
}
@media print {
.celltoolbar {
display: none;
}
}
.ctb_hideshow {
display: none;
vertical-align: bottom;
}
/* ctb_show is added to the ctb_hideshow div to show the cell toolbar.
Cell toolbars are only shown when the ctb_global_show class is also set.
*/
.ctb_global_show .ctb_show.ctb_hideshow {
display: block;
}
.ctb_global_show .ctb_show + .input_area,
.ctb_global_show .ctb_show + div.text_cell_input,
.ctb_global_show .ctb_show ~ div.text_cell_render {
border-top-right-radius: 0px;
border-top-left-radius: 0px;
}
.ctb_global_show .ctb_show ~ div.text_cell_render {
border: 1px solid #cfcfcf;
}
.celltoolbar {
font-size: 87%;
padding-top: 3px;
}
.celltoolbar select {
display: block;
width: 100%;
height: 32px;
padding: 6px 12px;
font-size: 13px;
line-height: 1.42857143;
color: #555555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 2px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 1px;
width: inherit;
font-size: inherit;
height: 22px;
padding: 0px;
display: inline-block;
}
.celltoolbar select:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
.celltoolbar select::-moz-placeholder {
color: #999;
opacity: 1;
}
.celltoolbar select:-ms-input-placeholder {
color: #999;
}
.celltoolbar select::-webkit-input-placeholder {
color: #999;
}
.celltoolbar select::-ms-expand {
border: 0;
background-color: transparent;
}
.celltoolbar select[disabled],
.celltoolbar select[readonly],
fieldset[disabled] .celltoolbar select {
background-color: #eeeeee;
opacity: 1;
}
.celltoolbar select[disabled],
fieldset[disabled] .celltoolbar select {
cursor: not-allowed;
}
textarea.celltoolbar select {
height: auto;
}
select.celltoolbar select {
height: 30px;
line-height: 30px;
}
textarea.celltoolbar select,
select[multiple].celltoolbar select {
height: auto;
}
.celltoolbar label {
margin-left: 5px;
margin-right: 5px;
}
.completions {
position: absolute;
z-index: 110;
overflow: hidden;
border: 1px solid #ababab;
border-radius: 2px;
-webkit-box-shadow: 0px 6px 10px -1px #adadad;
box-shadow: 0px 6px 10px -1px #adadad;
line-height: 1;
}
.completions select {
background: white;
outline: none;
border: none;
padding: 0px;
margin: 0px;
overflow: auto;
font-family: monospace;
font-size: 110%;
color: #000;
width: auto;
}
.completions select option.context {
color: #286090;
}
#kernel_logo_widget {
float: right !important;
float: right;
}
#kernel_logo_widget .current_kernel_logo {
display: none;
margin-top: -1px;
margin-bottom: -1px;
width: 32px;
height: 32px;
}
#menubar {
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
margin-top: 1px;
}
#menubar .navbar {
border-top: 1px;
border-radius: 0px 0px 2px 2px;
margin-bottom: 0px;
}
#menubar .navbar-toggle {
float: left;
padding-top: 7px;
padding-bottom: 7px;
border: none;
}
#menubar .navbar-collapse {
clear: left;
}
.nav-wrapper {
border-bottom: 1px solid #e7e7e7;
}
i.menu-icon {
padding-top: 4px;
}
ul#help_menu li a {
overflow: hidden;
padding-right: 2.2em;
}
ul#help_menu li a i {
margin-right: -1.2em;
}
.dropdown-submenu {
position: relative;
}
.dropdown-submenu > .dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
}
.dropdown-submenu:hover > .dropdown-menu {
display: block;
}
.dropdown-submenu > a:after {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
display: block;
content: "\f0da";
float: right;
color: #333333;
margin-top: 2px;
margin-right: -10px;
}
.dropdown-submenu > a:after.pull-left {
margin-right: .3em;
}
.dropdown-submenu > a:after.pull-right {
margin-left: .3em;
}
.dropdown-submenu:hover > a:after {
color: #262626;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left > .dropdown-menu {
left: -100%;
margin-left: 10px;
}
#notification_area {
float: right !important;
float: right;
z-index: 10;
}
.indicator_area {
float: right !important;
float: right;
color: #777;
margin-left: 5px;
margin-right: 5px;
width: 11px;
z-index: 10;
text-align: center;
width: auto;
}
#kernel_indicator {
float: right !important;
float: right;
color: #777;
margin-left: 5px;
margin-right: 5px;
width: 11px;
z-index: 10;
text-align: center;
width: auto;
border-left: 1px solid;
}
#kernel_indicator .kernel_indicator_name {
padding-left: 5px;
padding-right: 5px;
}
#modal_indicator {
float: right !important;
float: right;
color: #777;
margin-left: 5px;
margin-right: 5px;
width: 11px;
z-index: 10;
text-align: center;
width: auto;
}
#readonly-indicator {
float: right !important;
float: right;
color: #777;
margin-left: 5px;
margin-right: 5px;
width: 11px;
z-index: 10;
text-align: center;
width: auto;
margin-top: 2px;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
display: none;
}
.modal_indicator:before {
width: 1.28571429em;
text-align: center;
}
.edit_mode .modal_indicator:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\f040";
}
.edit_mode .modal_indicator:before.pull-left {
margin-right: .3em;
}
.edit_mode .modal_indicator:before.pull-right {
margin-left: .3em;
}
.command_mode .modal_indicator:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: ' ';
}
.command_mode .modal_indicator:before.pull-left {
margin-right: .3em;
}
.command_mode .modal_indicator:before.pull-right {
margin-left: .3em;
}
.kernel_idle_icon:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\f10c";
}
.kernel_idle_icon:before.pull-left {
margin-right: .3em;
}
.kernel_idle_icon:before.pull-right {
margin-left: .3em;
}
.kernel_busy_icon:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\f111";
}
.kernel_busy_icon:before.pull-left {
margin-right: .3em;
}
.kernel_busy_icon:before.pull-right {
margin-left: .3em;
}
.kernel_dead_icon:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\f1e2";
}
.kernel_dead_icon:before.pull-left {
margin-right: .3em;
}
.kernel_dead_icon:before.pull-right {
margin-left: .3em;
}
.kernel_disconnected_icon:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\f127";
}
.kernel_disconnected_icon:before.pull-left {
margin-right: .3em;
}
.kernel_disconnected_icon:before.pull-right {
margin-left: .3em;
}
.notification_widget {
color: #777;
z-index: 10;
background: rgba(240, 240, 240, 0.5);
margin-right: 4px;
color: #333;
background-color: #fff;
border-color: #ccc;
}
.notification_widget:focus,
.notification_widget.focus {
color: #333;
background-color: #e6e6e6;
border-color: #8c8c8c;
}
.notification_widget:hover {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
.notification_widget:active,
.notification_widget.active,
.open > .dropdown-toggle.notification_widget {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
.notification_widget:active:hover,
.notification_widget.active:hover,
.open > .dropdown-toggle.notification_widget:hover,
.notification_widget:active:focus,
.notification_widget.active:focus,
.open > .dropdown-toggle.notification_widget:focus,
.notification_widget:active.focus,
.notification_widget.active.focus,
.open > .dropdown-toggle.notification_widget.focus {
color: #333;
background-color: #d4d4d4;
border-color: #8c8c8c;
}
.notification_widget:active,
.notification_widget.active,
.open > .dropdown-toggle.notification_widget {
background-image: none;
}
.notification_widget.disabled:hover,
.notification_widget[disabled]:hover,
fieldset[disabled] .notification_widget:hover,
.notification_widget.disabled:focus,
.notification_widget[disabled]:focus,
fieldset[disabled] .notification_widget:focus,
.notification_widget.disabled.focus,
.notification_widget[disabled].focus,
fieldset[disabled] .notification_widget.focus {
background-color: #fff;
border-color: #ccc;
}
.notification_widget .badge {
color: #fff;
background-color: #333;
}
.notification_widget.warning {
color: #fff;
background-color: #f0ad4e;
border-color: #eea236;
}
.notification_widget.warning:focus,
.notification_widget.warning.focus {
color: #fff;
background-color: #ec971f;
border-color: #985f0d;
}
.notification_widget.warning:hover {
color: #fff;
background-color: #ec971f;
border-color: #d58512;
}
.notification_widget.warning:active,
.notification_widget.warning.active,
.open > .dropdown-toggle.notification_widget.warning {
color: #fff;
background-color: #ec971f;
border-color: #d58512;
}
.notification_widget.warning:active:hover,
.notification_widget.warning.active:hover,
.open > .dropdown-toggle.notification_widget.warning:hover,
.notification_widget.warning:active:focus,
.notification_widget.warning.active:focus,
.open > .dropdown-toggle.notification_widget.warning:focus,
.notification_widget.warning:active.focus,
.notification_widget.warning.active.focus,
.open > .dropdown-toggle.notification_widget.warning.focus {
color: #fff;
background-color: #d58512;
border-color: #985f0d;
}
.notification_widget.warning:active,
.notification_widget.warning.active,
.open > .dropdown-toggle.notification_widget.warning {
background-image: none;
}
.notification_widget.warning.disabled:hover,
.notification_widget.warning[disabled]:hover,
fieldset[disabled] .notification_widget.warning:hover,
.notification_widget.warning.disabled:focus,
.notification_widget.warning[disabled]:focus,
fieldset[disabled] .notification_widget.warning:focus,
.notification_widget.warning.disabled.focus,
.notification_widget.warning[disabled].focus,
fieldset[disabled] .notification_widget.warning.focus {
background-color: #f0ad4e;
border-color: #eea236;
}
.notification_widget.warning .badge {
color: #f0ad4e;
background-color: #fff;
}
.notification_widget.success {
color: #fff;
background-color: #5cb85c;
border-color: #4cae4c;
}
.notification_widget.success:focus,
.notification_widget.success.focus {
color: #fff;
background-color: #449d44;
border-color: #255625;
}
.notification_widget.success:hover {
color: #fff;
background-color: #449d44;
border-color: #398439;
}
.notification_widget.success:active,
.notification_widget.success.active,
.open > .dropdown-toggle.notification_widget.success {
color: #fff;
background-color: #449d44;
border-color: #398439;
}
.notification_widget.success:active:hover,
.notification_widget.success.active:hover,
.open > .dropdown-toggle.notification_widget.success:hover,
.notification_widget.success:active:focus,
.notification_widget.success.active:focus,
.open > .dropdown-toggle.notification_widget.success:focus,
.notification_widget.success:active.focus,
.notification_widget.success.active.focus,
.open > .dropdown-toggle.notification_widget.success.focus {
color: #fff;
background-color: #398439;
border-color: #255625;
}
.notification_widget.success:active,
.notification_widget.success.active,
.open > .dropdown-toggle.notification_widget.success {
background-image: none;
}
.notification_widget.success.disabled:hover,
.notification_widget.success[disabled]:hover,
fieldset[disabled] .notification_widget.success:hover,
.notification_widget.success.disabled:focus,
.notification_widget.success[disabled]:focus,
fieldset[disabled] .notification_widget.success:focus,
.notification_widget.success.disabled.focus,
.notification_widget.success[disabled].focus,
fieldset[disabled] .notification_widget.success.focus {
background-color: #5cb85c;
border-color: #4cae4c;
}
.notification_widget.success .badge {
color: #5cb85c;
background-color: #fff;
}
.notification_widget.info {
color: #fff;
background-color: #5bc0de;
border-color: #46b8da;
}
.notification_widget.info:focus,
.notification_widget.info.focus {
color: #fff;
background-color: #31b0d5;
border-color: #1b6d85;
}
.notification_widget.info:hover {
color: #fff;
background-color: #31b0d5;
border-color: #269abc;
}
.notification_widget.info:active,
.notification_widget.info.active,
.open > .dropdown-toggle.notification_widget.info {
color: #fff;
background-color: #31b0d5;
border-color: #269abc;
}
.notification_widget.info:active:hover,
.notification_widget.info.active:hover,
.open > .dropdown-toggle.notification_widget.info:hover,
.notification_widget.info:active:focus,
.notification_widget.info.active:focus,
.open > .dropdown-toggle.notification_widget.info:focus,
.notification_widget.info:active.focus,
.notification_widget.info.active.focus,
.open > .dropdown-toggle.notification_widget.info.focus {
color: #fff;
background-color: #269abc;
border-color: #1b6d85;
}
.notification_widget.info:active,
.notification_widget.info.active,
.open > .dropdown-toggle.notification_widget.info {
background-image: none;
}
.notification_widget.info.disabled:hover,
.notification_widget.info[disabled]:hover,
fieldset[disabled] .notification_widget.info:hover,
.notification_widget.info.disabled:focus,
.notification_widget.info[disabled]:focus,
fieldset[disabled] .notification_widget.info:focus,
.notification_widget.info.disabled.focus,
.notification_widget.info[disabled].focus,
fieldset[disabled] .notification_widget.info.focus {
background-color: #5bc0de;
border-color: #46b8da;
}
.notification_widget.info .badge {
color: #5bc0de;
background-color: #fff;
}
.notification_widget.danger {
color: #fff;
background-color: #d9534f;
border-color: #d43f3a;
}
.notification_widget.danger:focus,
.notification_widget.danger.focus {
color: #fff;
background-color: #c9302c;
border-color: #761c19;
}
.notification_widget.danger:hover {
color: #fff;
background-color: #c9302c;
border-color: #ac2925;
}
.notification_widget.danger:active,
.notification_widget.danger.active,
.open > .dropdown-toggle.notification_widget.danger {
color: #fff;
background-color: #c9302c;
border-color: #ac2925;
}
.notification_widget.danger:active:hover,
.notification_widget.danger.active:hover,
.open > .dropdown-toggle.notification_widget.danger:hover,
.notification_widget.danger:active:focus,
.notification_widget.danger.active:focus,
.open > .dropdown-toggle.notification_widget.danger:focus,
.notification_widget.danger:active.focus,
.notification_widget.danger.active.focus,
.open > .dropdown-toggle.notification_widget.danger.focus {
color: #fff;
background-color: #ac2925;
border-color: #761c19;
}
.notification_widget.danger:active,
.notification_widget.danger.active,
.open > .dropdown-toggle.notification_widget.danger {
background-image: none;
}
.notification_widget.danger.disabled:hover,
.notification_widget.danger[disabled]:hover,
fieldset[disabled] .notification_widget.danger:hover,
.notification_widget.danger.disabled:focus,
.notification_widget.danger[disabled]:focus,
fieldset[disabled] .notification_widget.danger:focus,
.notification_widget.danger.disabled.focus,
.notification_widget.danger[disabled].focus,
fieldset[disabled] .notification_widget.danger.focus {
background-color: #d9534f;
border-color: #d43f3a;
}
.notification_widget.danger .badge {
color: #d9534f;
background-color: #fff;
}
div#pager {
background-color: #fff;
font-size: 14px;
line-height: 20px;
overflow: hidden;
display: none;
position: fixed;
bottom: 0px;
width: 100%;
max-height: 50%;
padding-top: 8px;
-webkit-box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
/* Display over codemirror */
z-index: 100;
/* Hack which prevents jquery ui resizable from changing top. */
top: auto !important;
}
div#pager pre {
line-height: 1.21429em;
color: #000;
background-color: #f7f7f7;
padding: 0.4em;
}
div#pager #pager-button-area {
position: absolute;
top: 8px;
right: 20px;
}
div#pager #pager-contents {
position: relative;
overflow: auto;
width: 100%;
height: 100%;
}
div#pager #pager-contents #pager-container {
position: relative;
padding: 15px 0px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
div#pager .ui-resizable-handle {
top: 0px;
height: 8px;
background: #f7f7f7;
border-top: 1px solid #cfcfcf;
border-bottom: 1px solid #cfcfcf;
/* This injects handle bars (a short, wide = symbol) for
the resize handle. */
}
div#pager .ui-resizable-handle::after {
content: '';
top: 2px;
left: 50%;
height: 3px;
width: 30px;
margin-left: -15px;
position: absolute;
border-top: 1px solid #cfcfcf;
}
.quickhelp {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-align: stretch;
display: box;
box-orient: horizontal;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: row;
align-items: stretch;
line-height: 1.8em;
}
.shortcut_key {
display: inline-block;
width: 21ex;
text-align: right;
font-family: monospace;
}
.shortcut_descr {
display: inline-block;
/* Old browsers */
-webkit-box-flex: 1;
-moz-box-flex: 1;
box-flex: 1;
/* Modern browsers */
flex: 1;
}
span.save_widget {
margin-top: 6px;
}
span.save_widget span.filename {
height: 1em;
line-height: 1em;
padding: 3px;
margin-left: 16px;
border: none;
font-size: 146.5%;
border-radius: 2px;
}
span.save_widget span.filename:hover {
background-color: #e6e6e6;
}
span.checkpoint_status,
span.autosave_status {
font-size: small;
}
@media (max-width: 767px) {
span.save_widget {
font-size: small;
}
span.checkpoint_status,
span.autosave_status {
display: none;
}
}
@media (min-width: 768px) and (max-width: 991px) {
span.checkpoint_status {
display: none;
}
span.autosave_status {
font-size: x-small;
}
}
.toolbar {
padding: 0px;
margin-left: -5px;
margin-top: 2px;
margin-bottom: 5px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
.toolbar select,
.toolbar label {
width: auto;
vertical-align: middle;
margin-right: 2px;
margin-bottom: 0px;
display: inline;
font-size: 92%;
margin-left: 0.3em;
margin-right: 0.3em;
padding: 0px;
padding-top: 3px;
}
.toolbar .btn {
padding: 2px 8px;
}
.toolbar .btn-group {
margin-top: 0px;
margin-left: 5px;
}
#maintoolbar {
margin-bottom: -3px;
margin-top: -8px;
border: 0px;
min-height: 27px;
margin-left: 0px;
padding-top: 11px;
padding-bottom: 3px;
}
#maintoolbar .navbar-text {
float: none;
vertical-align: middle;
text-align: right;
margin-left: 5px;
margin-right: 0px;
margin-top: 0px;
}
.select-xs {
height: 24px;
}
.pulse,
.dropdown-menu > li > a.pulse,
li.pulse > a.dropdown-toggle,
li.pulse.open > a.dropdown-toggle {
background-color: #F37626;
color: white;
}
/**
* Primary styles
*
* Author: Jupyter Development Team
*/
/** WARNING IF YOU ARE EDITTING THIS FILE, if this is a .css file, It has a lot
* of chance of beeing generated from the ../less/[samename].less file, you can
* try to get back the less file by reverting somme commit in history
**/
/*
* We'll try to get something pretty, so we
* have some strange css to have the scroll bar on
* the left with fix button on the top right of the tooltip
*/
@-moz-keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
@-webkit-keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
@-moz-keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@-webkit-keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/*properties of tooltip after "expand"*/
.bigtooltip {
overflow: auto;
height: 200px;
-webkit-transition-property: height;
-webkit-transition-duration: 500ms;
-moz-transition-property: height;
-moz-transition-duration: 500ms;
transition-property: height;
transition-duration: 500ms;
}
/*properties of tooltip before "expand"*/
.smalltooltip {
-webkit-transition-property: height;
-webkit-transition-duration: 500ms;
-moz-transition-property: height;
-moz-transition-duration: 500ms;
transition-property: height;
transition-duration: 500ms;
text-overflow: ellipsis;
overflow: hidden;
height: 80px;
}
.tooltipbuttons {
position: absolute;
padding-right: 15px;
top: 0px;
right: 0px;
}
.tooltiptext {
/*avoid the button to overlap on some docstring*/
padding-right: 30px;
}
.ipython_tooltip {
max-width: 700px;
/*fade-in animation when inserted*/
-webkit-animation: fadeOut 400ms;
-moz-animation: fadeOut 400ms;
animation: fadeOut 400ms;
-webkit-animation: fadeIn 400ms;
-moz-animation: fadeIn 400ms;
animation: fadeIn 400ms;
vertical-align: middle;
background-color: #f7f7f7;
overflow: visible;
border: #ababab 1px solid;
outline: none;
padding: 3px;
margin: 0px;
padding-left: 7px;
font-family: monospace;
min-height: 50px;
-moz-box-shadow: 0px 6px 10px -1px #adadad;
-webkit-box-shadow: 0px 6px 10px -1px #adadad;
box-shadow: 0px 6px 10px -1px #adadad;
border-radius: 2px;
position: absolute;
z-index: 1000;
}
.ipython_tooltip a {
float: right;
}
.ipython_tooltip .tooltiptext pre {
border: 0;
border-radius: 0;
font-size: 100%;
background-color: #f7f7f7;
}
.pretooltiparrow {
left: 0px;
margin: 0px;
top: -16px;
width: 40px;
height: 16px;
overflow: hidden;
position: absolute;
}
.pretooltiparrow:before {
background-color: #f7f7f7;
border: 1px #ababab solid;
z-index: 11;
content: "";
position: absolute;
left: 15px;
top: 10px;
width: 25px;
height: 25px;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
}
ul.typeahead-list i {
margin-left: -10px;
width: 18px;
}
ul.typeahead-list {
max-height: 80vh;
overflow: auto;
}
ul.typeahead-list > li > a {
/** Firefox bug **/
/* see https://github.com/jupyter/notebook/issues/559 */
white-space: normal;
}
.cmd-palette .modal-body {
padding: 7px;
}
.cmd-palette form {
background: white;
}
.cmd-palette input {
outline: none;
}
.no-shortcut {
display: none;
}
.command-shortcut:before {
content: "(command)";
padding-right: 3px;
color: #777777;
}
.edit-shortcut:before {
content: "(edit)";
padding-right: 3px;
color: #777777;
}
#find-and-replace #replace-preview .match,
#find-and-replace #replace-preview .insert {
background-color: #BBDEFB;
border-color: #90CAF9;
border-style: solid;
border-width: 1px;
border-radius: 0px;
}
#find-and-replace #replace-preview .replace .match {
background-color: #FFCDD2;
border-color: #EF9A9A;
border-radius: 0px;
}
#find-and-replace #replace-preview .replace .insert {
background-color: #C8E6C9;
border-color: #A5D6A7;
border-radius: 0px;
}
#find-and-replace #replace-preview {
max-height: 60vh;
overflow: auto;
}
#find-and-replace #replace-preview pre {
padding: 5px 10px;
}
.terminal-app {
background: #EEE;
}
.terminal-app #header {
background: #fff;
-webkit-box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.2);
}
.terminal-app .terminal {
width: 100%;
float: left;
font-family: monospace;
color: white;
background: black;
padding: 0.4em;
border-radius: 2px;
-webkit-box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.4);
box-shadow: 0px 0px 12px 1px rgba(87, 87, 87, 0.4);
}
.terminal-app .terminal,
.terminal-app .terminal dummy-screen {
line-height: 1em;
font-size: 14px;
}
.terminal-app .terminal .xterm-rows {
padding: 10px;
}
.terminal-app .terminal-cursor {
color: black;
background: white;
}
.terminal-app #terminado-container {
margin-top: 20px;
}
/*# sourceMappingURL=style.min.css.map */
</style>
<style type="text/css">
.highlight .hll { background-color: #ffffcc }
.highlight { background: #f8f8f8; }
.highlight .c { color: #408080; font-style: italic } /* Comment */
.highlight .err { border: 1px solid #FF0000 } /* Error */
.highlight .k { color: #008000; font-weight: bold } /* Keyword */
.highlight .o { color: #666666 } /* Operator */
.highlight .ch { color: #408080; font-style: italic } /* Comment.Hashbang */
.highlight .cm { color: #408080; font-style: italic } /* Comment.Multiline */
.highlight .cp { color: #BC7A00 } /* Comment.Preproc */
.highlight .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */
.highlight .c1 { color: #408080; font-style: italic } /* Comment.Single */
.highlight .cs { color: #408080; font-style: italic } /* Comment.Special */
.highlight .gd { color: #A00000 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #FF0000 } /* Generic.Error */
.highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.highlight .gi { color: #00A000 } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.highlight .gt { color: #0044DD } /* Generic.Traceback */
.highlight .kc { color: #008000; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008000 } /* Keyword.Pseudo */
.highlight .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #B00040 } /* Keyword.Type */
.highlight .m { color: #666666 } /* Literal.Number */
.highlight .s { color: #BA2121 } /* Literal.String */
.highlight .na { color: #7D9029 } /* Name.Attribute */
.highlight .nb { color: #008000 } /* Name.Builtin */
.highlight .nc { color: #0000FF; font-weight: bold } /* Name.Class */
.highlight .no { color: #880000 } /* Name.Constant */
.highlight .nd { color: #AA22FF } /* Name.Decorator */
.highlight .ni { color: #999999; font-weight: bold } /* Name.Entity */
.highlight .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0000FF } /* Name.Function */
.highlight .nl { color: #A0A000 } /* Name.Label */
.highlight .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
.highlight .nt { color: #008000; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #19177C } /* Name.Variable */
.highlight .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #666666 } /* Literal.Number.Bin */
.highlight .mf { color: #666666 } /* Literal.Number.Float */
.highlight .mh { color: #666666 } /* Literal.Number.Hex */
.highlight .mi { color: #666666 } /* Literal.Number.Integer */
.highlight .mo { color: #666666 } /* Literal.Number.Oct */
.highlight .sa { color: #BA2121 } /* Literal.String.Affix */
.highlight .sb { color: #BA2121 } /* Literal.String.Backtick */
.highlight .sc { color: #BA2121 } /* Literal.String.Char */
.highlight .dl { color: #BA2121 } /* Literal.String.Delimiter */
.highlight .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */
.highlight .s2 { color: #BA2121 } /* Literal.String.Double */
.highlight .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
.highlight .sh { color: #BA2121 } /* Literal.String.Heredoc */
.highlight .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
.highlight .sx { color: #008000 } /* Literal.String.Other */
.highlight .sr { color: #BB6688 } /* Literal.String.Regex */
.highlight .s1 { color: #BA2121 } /* Literal.String.Single */
.highlight .ss { color: #19177C } /* Literal.String.Symbol */
.highlight .bp { color: #008000 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0000FF } /* Name.Function.Magic */
.highlight .vc { color: #19177C } /* Name.Variable.Class */
.highlight .vg { color: #19177C } /* Name.Variable.Global */
.highlight .vi { color: #19177C } /* Name.Variable.Instance */
.highlight .vm { color: #19177C } /* Name.Variable.Magic */
.highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
</style>
<style type="text/css">
/* Temporary definitions which will become obsolete with Notebook release 5.0 */
.ansi-black-fg { color: #3E424D; }
.ansi-black-bg { background-color: #3E424D; }
.ansi-black-intense-fg { color: #282C36; }
.ansi-black-intense-bg { background-color: #282C36; }
.ansi-red-fg { color: #E75C58; }
.ansi-red-bg { background-color: #E75C58; }
.ansi-red-intense-fg { color: #B22B31; }
.ansi-red-intense-bg { background-color: #B22B31; }
.ansi-green-fg { color: #00A250; }
.ansi-green-bg { background-color: #00A250; }
.ansi-green-intense-fg { color: #007427; }
.ansi-green-intense-bg { background-color: #007427; }
.ansi-yellow-fg { color: #DDB62B; }
.ansi-yellow-bg { background-color: #DDB62B; }
.ansi-yellow-intense-fg { color: #B27D12; }
.ansi-yellow-intense-bg { background-color: #B27D12; }
.ansi-blue-fg { color: #208FFB; }
.ansi-blue-bg { background-color: #208FFB; }
.ansi-blue-intense-fg { color: #0065CA; }
.ansi-blue-intense-bg { background-color: #0065CA; }
.ansi-magenta-fg { color: #D160C4; }
.ansi-magenta-bg { background-color: #D160C4; }
.ansi-magenta-intense-fg { color: #A03196; }
.ansi-magenta-intense-bg { background-color: #A03196; }
.ansi-cyan-fg { color: #60C6C8; }
.ansi-cyan-bg { background-color: #60C6C8; }
.ansi-cyan-intense-fg { color: #258F8F; }
.ansi-cyan-intense-bg { background-color: #258F8F; }
.ansi-white-fg { color: #C5C1B4; }
.ansi-white-bg { background-color: #C5C1B4; }
.ansi-white-intense-fg { color: #A1A6B2; }
.ansi-white-intense-bg { background-color: #A1A6B2; }
.ansi-bold { font-weight: bold; }
</style>
<style type="text/css">
/* Overrides of notebook CSS for static HTML export */
body {
overflow: visible;
padding: 8px;
}
div#notebook {
overflow: visible;
border-top: none;
}
@media print {
div.cell {
display: block;
page-break-inside: avoid;
}
div.output_wrapper {
display: block;
page-break-inside: avoid;
}
div.output {
display: block;
page-break-inside: avoid;
}
}
</style>
<!-- Custom stylesheet, it must be in the same directory as the html file -->
<link rel="stylesheet" href="custom.css">
<!-- Loading mathjax macro -->
<!-- Load mathjax -->
<script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML"></script>
<!-- MathJax configuration -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true,
processEnvironments: true
},
// Center justify equations in code and markdown cells. Elsewhere
// we use CSS to left justify single line equations in code cells.
displayAlign: 'center',
"HTML-CSS": {
styles: {'.MathJax_Display': {"margin": 0}},
linebreaks: { automatic: true }
}
});
</script>
<!-- End of mathjax configuration --></head>
<body>
<div tabindex="-1" id="notebook" class="border-box-sizing">
<div class="container" id="notebook-container">
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="Artificial-Intelligence-Engineer-Nanodegree---Probabilistic-Models">Artificial Intelligence Engineer Nanodegree - Probabilistic Models<a class="anchor-link" href="#Artificial-Intelligence-Engineer-Nanodegree---Probabilistic-Models">¶</a></h1><h2 id="Project:-Sign-Language-Recognition-System">Project: Sign Language Recognition System<a class="anchor-link" href="#Project:-Sign-Language-Recognition-System">¶</a></h2><ul>
<li><a href="#intro">Introduction</a></li>
<li><a href="#part1_tutorial">Part 1 Feature Selection</a><ul>
<li><a href="#part1_tutorial">Tutorial</a></li>
<li><a href="#part1_submission">Features Submission</a></li>
<li><a href="#part1_test">Features Unittest</a></li>
</ul>
</li>
<li><a href="#part2_tutorial">Part 2 Train the models</a><ul>
<li><a href="#part2_tutorial">Tutorial</a></li>
<li><a href="#part2_submission">Model Selection Score Submission</a></li>
<li><a href="#part2_test">Model Score Unittest</a></li>
</ul>
</li>
<li><a href="#part3_tutorial">Part 3 Build a Recognizer</a><ul>
<li><a href="#part3_tutorial">Tutorial</a></li>
<li><a href="#part3_submission">Recognizer Submission</a></li>
<li><a href="#part3_test">Recognizer Unittest</a></li>
</ul>
</li>
<li><a href="#part4_info">Part 4 (OPTIONAL) Improve the WER with Language Models</a></li>
</ul>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><a id='intro'></a></p>
<h2 id="Introduction">Introduction<a class="anchor-link" href="#Introduction">¶</a></h2><p>The overall goal of this project is to build a word recognizer for American Sign Language video sequences, demonstrating the power of probabalistic models. In particular, this project employs <a href="https://en.wikipedia.org/wiki/Hidden_Markov_model">hidden Markov models (HMM's)</a> to analyze a series of measurements taken from videos of American Sign Language (ASL) collected for research (see the <a href="http://www-i6.informatik.rwth-aachen.de/~dreuw/database-rwth-boston-104.php">RWTH-BOSTON-104 Database</a>). In this video, the right-hand x and y locations are plotted as the speaker signs the sentence.
<a href="https://drive.google.com/open?id=0B_5qGuFe-wbhUXRuVnNZVnMtam8"><img src="http://www-i6.informatik.rwth-aachen.de/~dreuw/images/demosample.png" alt="ASLR demo"></a></p>
<p>The raw data, train, and test sets are pre-defined. You will derive a variety of feature sets (explored in Part 1), as well as implement three different model selection criterion to determine the optimal number of hidden states for each word model (explored in Part 2). Finally, in Part 3 you will implement the recognizer and compare the effects the different combinations of feature sets and model selection criteria.</p>
<p>At the end of each Part, complete the submission cells with implementations, answer all questions, and pass the unit tests. Then submit the completed notebook for review!</p>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><a id='part1_tutorial'></a></p>
<h2 id="PART-1:-Data">PART 1: Data<a class="anchor-link" href="#PART-1:-Data">¶</a></h2><h3 id="Features-Tutorial">Features Tutorial<a class="anchor-link" href="#Features-Tutorial">¶</a></h3><h5 id="Load-the-initial-database">Load the initial database<a class="anchor-link" href="#Load-the-initial-database">¶</a></h5><p>A data handler designed for this database is provided in the student codebase as the <code>AslDb</code> class in the <code>asl_data</code> module. This handler creates the initial <a href="http://pandas.pydata.org/pandas-docs/stable/">pandas</a> dataframe from the corpus of data included in the <code>data</code> directory as well as dictionaries suitable for extracting data in a format friendly to the <a href="https://hmmlearn.readthedocs.io/en/latest/">hmmlearn</a> library. We'll use those to create models in Part 2.</p>
<p>To start, let's set up the initial database and select an example set of features for the training set. At the end of Part 1, you will create additional feature sets for experimentation.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [1]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="kn">from</span> <span class="nn">asl_data</span> <span class="k">import</span> <span class="n">AslDb</span>
<span class="n">asl</span> <span class="o">=</span> <span class="n">AslDb</span><span class="p">()</span> <span class="c1"># initializes the database</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">head</span><span class="p">()</span> <span class="c1"># displays the first five rows of the asl database, indexed by video and frame</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt output_prompt">Out[1]:</div>
<div class="output_html rendered_html output_subarea output_execute_result">
<div>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th></th>
<th>left-x</th>
<th>left-y</th>
<th>right-x</th>
<th>right-y</th>
<th>nose-x</th>
<th>nose-y</th>
<th>speaker</th>
</tr>
<tr>
<th>video</th>
<th>frame</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th rowspan="5" valign="top">98</th>
<th>0</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
</tr>
<tr>
<th>1</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
</tr>
<tr>
<th>2</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
</tr>
<tr>
<th>3</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
</tr>
<tr>
<th>4</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [2]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">ix</span><span class="p">[</span><span class="mi">98</span><span class="p">,</span><span class="mi">1</span><span class="p">]</span> <span class="c1"># look at the data available for an individual frame</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt output_prompt">Out[2]:</div>
<div class="output_text output_subarea output_execute_result">
<pre>left-x 149
left-y 181
right-x 170
right-y 175
nose-x 161
nose-y 62
speaker woman-1
Name: (98, 1), dtype: object</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>The frame represented by video 98, frame 1 is shown here:
<img src="http://www-i6.informatik.rwth-aachen.de/~dreuw/database/rwth-boston-104/overview/images/orig/098-start.jpg" alt="Video 98"></p>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Feature-selection-for-training-the-model">Feature selection for training the model<a class="anchor-link" href="#Feature-selection-for-training-the-model">¶</a></h5><p>The objective of feature selection when training a model is to choose the most relevant variables while keeping the model as simple as possible, thus reducing training time. We can use the raw features already provided or derive our own and add columns to the pandas dataframe <code>asl.df</code> for selection. As an example, in the next cell a feature named <code>'grnd-ry'</code> is added. This feature is the difference between the right-hand y value and the nose y value, which serves as the "ground" right y value.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [3]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'grnd-ry'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'right-y'</span><span class="p">]</span> <span class="o">-</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'nose-y'</span><span class="p">]</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">head</span><span class="p">()</span> <span class="c1"># the new feature 'grnd-ry' is now in the frames dictionary</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt output_prompt">Out[3]:</div>
<div class="output_html rendered_html output_subarea output_execute_result">
<div>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th></th>
<th>left-x</th>
<th>left-y</th>
<th>right-x</th>
<th>right-y</th>
<th>nose-x</th>
<th>nose-y</th>
<th>speaker</th>
<th>grnd-ry</th>
</tr>
<tr>
<th>video</th>
<th>frame</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th rowspan="5" valign="top">98</th>
<th>0</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
</tr>
<tr>
<th>1</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
</tr>
<tr>
<th>2</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
</tr>
<tr>
<th>3</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
</tr>
<tr>
<th>4</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Try-it!">Try it!<a class="anchor-link" href="#Try-it!">¶</a></h5>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [4]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">asl_utils</span> <span class="k">import</span> <span class="n">test_features_tryit</span>
<span class="c1"># DONE add df columns for 'grnd-rx', 'grnd-ly', 'grnd-lx' representing differences between hand and nose locations</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'grnd-rx'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'right-x'</span><span class="p">]</span> <span class="o">-</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'nose-x'</span><span class="p">]</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'grnd-ly'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'left-y'</span><span class="p">]</span> <span class="o">-</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'nose-y'</span><span class="p">]</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'grnd-lx'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'left-x'</span><span class="p">]</span> <span class="o">-</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'nose-x'</span><span class="p">]</span>
<span class="c1"># test the code</span>
<span class="n">test_features_tryit</span><span class="p">(</span><span class="n">asl</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>asl.df sample
</pre>
</div>
</div>
<div class="output_area">
<div class="prompt"></div>
<div class="output_html rendered_html output_subarea ">
<div>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th></th>
<th>left-x</th>
<th>left-y</th>
<th>right-x</th>
<th>right-y</th>
<th>nose-x</th>
<th>nose-y</th>
<th>speaker</th>
<th>grnd-ry</th>
<th>grnd-rx</th>
<th>grnd-ly</th>
<th>grnd-lx</th>
</tr>
<tr>
<th>video</th>
<th>frame</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th rowspan="5" valign="top">98</th>
<th>0</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
<td>9</td>
<td>119</td>
<td>-12</td>
</tr>
<tr>
<th>1</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
<td>9</td>
<td>119</td>
<td>-12</td>
</tr>
<tr>
<th>2</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
<td>9</td>
<td>119</td>
<td>-12</td>
</tr>
<tr>
<th>3</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
<td>9</td>
<td>119</td>
<td>-12</td>
</tr>
<tr>
<th>4</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
<td>9</td>
<td>119</td>
<td>-12</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="output_area">
<div class="prompt output_prompt">Out[4]:</div>
<div class="output_html rendered_html output_subarea output_execute_result">
<font color=green>Correct!</font><br/>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [5]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># collect the features into a list</span>
<span class="n">features_ground</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'grnd-rx'</span><span class="p">,</span><span class="s1">'grnd-ry'</span><span class="p">,</span><span class="s1">'grnd-lx'</span><span class="p">,</span><span class="s1">'grnd-ly'</span><span class="p">]</span>
<span class="c1">#show a single set of features for a given (video, frame) tuple</span>
<span class="p">[</span><span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">ix</span><span class="p">[</span><span class="mi">98</span><span class="p">,</span><span class="mi">1</span><span class="p">][</span><span class="n">v</span><span class="p">]</span> <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">features_ground</span><span class="p">]</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt output_prompt">Out[5]:</div>
<div class="output_text output_subarea output_execute_result">
<pre>[9, 113, -12, 119]</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Build-the-training-set">Build the training set<a class="anchor-link" href="#Build-the-training-set">¶</a></h5><p>Now that we have a feature list defined, we can pass that list to the <code>build_training</code> method to collect the features for all the words in the training set. Each word in the training set has multiple examples from various videos. Below we can see the unique words that have been loaded into the training set:</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [6]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">training</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">build_training</span><span class="p">(</span><span class="n">features_ground</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Training words: </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">training</span><span class="o">.</span><span class="n">words</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Training words: ['JOHN', 'WRITE', 'HOMEWORK', 'IX-1P', 'SEE', 'YESTERDAY', 'IX', 'LOVE', 'MARY', 'CAN', 'GO', 'GO1', 'FUTURE', 'GO2', 'PARTY', 'FUTURE1', 'HIT', 'BLAME', 'FRED', 'FISH', 'WONT', 'EAT', 'BUT', 'CHICKEN', 'VEGETABLE', 'CHINA', 'PEOPLE', 'PREFER', 'BROCCOLI', 'LIKE', 'LEAVE', 'SAY', 'BUY', 'HOUSE', 'KNOW', 'CORN', 'CORN1', 'THINK', 'NOT', 'PAST', 'LIVE', 'CHICAGO', 'CAR', 'SHOULD', 'DECIDE', 'VISIT', 'MOVIE', 'WANT', 'SELL', 'TOMORROW', 'NEXT-WEEK', 'NEW-YORK', 'LAST-WEEK', 'WILL', 'FINISH', 'ANN', 'READ', 'BOOK', 'CHOCOLATE', 'FIND', 'SOMETHING-ONE', 'POSS', 'BROTHER', 'ARRIVE', 'HERE', 'GIVE', 'MAN', 'NEW', 'COAT', 'WOMAN', 'GIVE1', 'HAVE', 'FRANK', 'BREAK-DOWN', 'SEARCH-FOR', 'WHO', 'WHAT', 'LEG', 'FRIEND', 'CANDY', 'BLUE', 'SUE', 'BUY1', 'STOLEN', 'OLD', 'STUDENT', 'VIDEOTAPE', 'BORROW', 'MOTHER', 'POTATO', 'TELL', 'BILL', 'THROW', 'APPLE', 'NAME', 'SHOOT', 'SAY-1P', 'SELF', 'GROUP', 'JANA', 'TOY1', 'MANY', 'TOY', 'ALL', 'BOY', 'TEACHER', 'GIRL', 'BOX', 'GIVE2', 'GIVE3', 'GET', 'PUTASIDE']
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>The training data in <code>training</code> is an object of class <code>WordsData</code> defined in the <code>asl_data</code> module. in addition to the <code>words</code> list, data can be accessed with the <code>get_all_sequences</code>, <code>get_all_Xlengths</code>, <code>get_word_sequences</code>, and <code>get_word_Xlengths</code> methods. We need the <code>get_word_Xlengths</code> method to train multiple sequences with the <code>hmmlearn</code> library. In the following example, notice that there are two lists; the first is a concatenation of all the sequences(the X portion) and the second is a list of the sequence lengths(the Lengths portion).</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [7]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">training</span><span class="o">.</span><span class="n">get_word_Xlengths</span><span class="p">(</span><span class="s1">'CHOCOLATE'</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt output_prompt">Out[7]:</div>
<div class="output_text output_subarea output_execute_result">
<pre>(array([[-11, 48, 7, 120],
[-11, 48, 8, 109],
[ -8, 49, 11, 98],
[ -7, 50, 7, 87],
[ -4, 54, 7, 77],
[ -4, 54, 6, 69],
[ -4, 54, 6, 69],
[-13, 52, 6, 69],
[-13, 52, 6, 69],
[ -8, 51, 6, 69],
[ -8, 51, 6, 69],
[ -8, 51, 6, 69],
[ -8, 51, 6, 69],
[ -8, 51, 6, 69],
[-10, 59, 7, 71],
[-15, 64, 9, 77],
[-17, 75, 13, 81],
[ -4, 48, -4, 113],
[ -2, 53, -4, 113],
[ -4, 55, 2, 98],
[ -4, 58, 2, 98],
[ -1, 59, 2, 89],
[ -1, 59, -1, 84],
[ -1, 59, -1, 84],
[ -7, 63, -1, 84],
[ -7, 63, -1, 84],
[ -7, 63, 3, 83],
[ -7, 63, 3, 83],
[ -7, 63, 3, 83],
[ -7, 63, 3, 83],
[ -7, 63, 3, 83],
[ -7, 63, 3, 83],
[ -7, 63, 3, 83],
[ -4, 70, 3, 83],
[ -4, 70, 3, 83],
[ -2, 73, 5, 90],
[ -3, 79, -4, 96],
[-15, 98, 13, 135],
[ -6, 93, 12, 128],
[ -2, 89, 14, 118],
[ 5, 90, 10, 108],
[ 4, 86, 7, 105],
[ 4, 86, 7, 105],
[ 4, 86, 13, 100],
[ -3, 82, 14, 96],
[ -3, 82, 14, 96],
[ 6, 89, 16, 100],
[ 6, 89, 16, 100],
[ 7, 85, 17, 111]]), [17, 20, 12])</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h6 id="More-feature-sets">More feature sets<a class="anchor-link" href="#More-feature-sets">¶</a></h6><p>So far we have a simple feature set that is enough to get started modeling. However, we might get better results if we manipulate the raw values a bit more, so we will go ahead and set up some other options now for experimentation later. For example, we could normalize each speaker's range of motion with grouped statistics using <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#api-dataframe-stats">Pandas stats</a> functions and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html">pandas groupby</a>. Below is an example for finding the means of all speaker subgroups.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [8]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">df_means</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="s1">'speaker'</span><span class="p">)</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
<span class="n">df_means</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt output_prompt">Out[8]:</div>
<div class="output_html rendered_html output_subarea output_execute_result">
<div>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>left-x</th>
<th>left-y</th>
<th>right-x</th>
<th>right-y</th>
<th>nose-x</th>
<th>nose-y</th>
<th>grnd-ry</th>
<th>grnd-rx</th>
<th>grnd-ly</th>
<th>grnd-lx</th>
</tr>
<tr>
<th>speaker</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th>man-1</th>
<td>206.248203</td>
<td>218.679449</td>
<td>155.464350</td>
<td>150.371031</td>
<td>175.031756</td>
<td>61.642600</td>
<td>88.728430</td>
<td>-19.567406</td>
<td>157.036848</td>
<td>31.216447</td>
</tr>
<tr>
<th>woman-1</th>
<td>164.661438</td>
<td>161.271242</td>
<td>151.017865</td>
<td>117.332462</td>
<td>162.655120</td>
<td>57.245098</td>
<td>60.087364</td>
<td>-11.637255</td>
<td>104.026144</td>
<td>2.006318</td>
</tr>
<tr>
<th>woman-2</th>
<td>183.214509</td>
<td>176.527232</td>
<td>156.866295</td>
<td>119.835714</td>
<td>170.318973</td>
<td>58.022098</td>
<td>61.813616</td>
<td>-13.452679</td>
<td>118.505134</td>
<td>12.895536</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>To select a mean that matches by speaker, use the pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html">map</a> method:</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [9]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'left-x-mean'</span><span class="p">]</span><span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'speaker'</span><span class="p">]</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">df_means</span><span class="p">[</span><span class="s1">'left-x'</span><span class="p">])</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">head</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt output_prompt">Out[9]:</div>
<div class="output_html rendered_html output_subarea output_execute_result">
<div>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th></th>
<th>left-x</th>
<th>left-y</th>
<th>right-x</th>
<th>right-y</th>
<th>nose-x</th>
<th>nose-y</th>
<th>speaker</th>
<th>grnd-ry</th>
<th>grnd-rx</th>
<th>grnd-ly</th>
<th>grnd-lx</th>
<th>left-x-mean</th>
</tr>
<tr>
<th>video</th>
<th>frame</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th rowspan="5" valign="top">98</th>
<th>0</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
<td>9</td>
<td>119</td>
<td>-12</td>
<td>164.661438</td>
</tr>
<tr>
<th>1</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
<td>9</td>
<td>119</td>
<td>-12</td>
<td>164.661438</td>
</tr>
<tr>
<th>2</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
<td>9</td>
<td>119</td>
<td>-12</td>
<td>164.661438</td>
</tr>
<tr>
<th>3</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
<td>9</td>
<td>119</td>
<td>-12</td>
<td>164.661438</td>
</tr>
<tr>
<th>4</th>
<td>149</td>
<td>181</td>
<td>170</td>
<td>175</td>
<td>161</td>
<td>62</td>
<td>woman-1</td>
<td>113</td>
<td>9</td>
<td>119</td>
<td>-12</td>
<td>164.661438</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Try-it!">Try it!<a class="anchor-link" href="#Try-it!">¶</a></h5>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [10]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">asl_utils</span> <span class="k">import</span> <span class="n">test_std_tryit</span>
<span class="c1"># DONE Create a dataframe named `df_std` with standard deviations grouped by speaker</span>
<span class="n">df_std</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="s1">'speaker'</span><span class="p">)</span><span class="o">.</span><span class="n">std</span><span class="p">()</span>
<span class="c1"># test the code</span>
<span class="n">test_std_tryit</span><span class="p">(</span><span class="n">df_std</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>df_std
</pre>
</div>
</div>
<div class="output_area">
<div class="prompt"></div>
<div class="output_html rendered_html output_subarea ">
<div>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>left-x</th>
<th>left-y</th>
<th>right-x</th>
<th>right-y</th>
<th>nose-x</th>
<th>nose-y</th>
<th>grnd-ry</th>
<th>grnd-rx</th>
<th>grnd-ly</th>
<th>grnd-lx</th>
<th>left-x-mean</th>
</tr>
<tr>
<th>speaker</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th>man-1</th>
<td>15.154425</td>
<td>36.328485</td>
<td>18.901917</td>
<td>54.902340</td>
<td>6.654573</td>
<td>5.520045</td>
<td>53.487999</td>
<td>20.269032</td>
<td>36.572749</td>
<td>15.080360</td>
<td>0.0</td>
</tr>
<tr>
<th>woman-1</th>
<td>17.573442</td>
<td>26.594521</td>
<td>16.459943</td>
<td>34.667787</td>
<td>3.549392</td>
<td>3.538330</td>
<td>33.972660</td>
<td>16.764706</td>
<td>27.117393</td>
<td>17.328941</td>
<td>0.0</td>
</tr>
<tr>
<th>woman-2</th>
<td>15.388711</td>
<td>28.825025</td>
<td>14.890288</td>
<td>39.649111</td>
<td>4.099760</td>
<td>3.416167</td>
<td>39.128572</td>
<td>16.191324</td>
<td>29.320655</td>
<td>15.050938</td>
<td>0.0</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="output_area">
<div class="prompt output_prompt">Out[10]:</div>
<div class="output_html rendered_html output_subarea output_execute_result">
<font color=green>Correct!</font><br/>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><a id='part1_submission'></a></p>
<h3 id="Features-Implementation-Submission">Features Implementation Submission<a class="anchor-link" href="#Features-Implementation-Submission">¶</a></h3><p>Implement four feature sets and answer the question that follows.</p>
<ul>
<li><p>normalized Cartesian coordinates</p>
<ul>
<li>use <em>mean</em> and <em>standard deviation</em> statistics and the <a href="https://en.wikipedia.org/wiki/Standard_score">standard score</a> equation to account for speakers with different heights and arm length</li>
</ul>
</li>
<li><p>polar coordinates</p>
<ul>
<li>calculate polar coordinates with <a href="https://en.wikipedia.org/wiki/Polar_coordinate_system#Converting_between_polar_and_Cartesian_coordinates">Cartesian to polar equations</a></li>
<li>use the <a href="https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.arctan2.html">np.arctan2</a> function and <em>swap the x and y axes</em> to move the $0$ to $2\pi$ discontinuity to 12 o'clock instead of 3 o'clock; in other words, the normal break in radians value from $0$ to $2\pi$ occurs directly to the left of the speaker's nose, which may be in the signing area and interfere with results. By swapping the x and y axes, that discontinuity move to directly above the speaker's head, an area not generally used in signing.</li>
</ul>
</li>
<li><p>delta difference</p>
<ul>
<li>as described in Thad's lecture, use the difference in values between one frame and the next frames as features</li>
<li>pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.diff.html">diff method</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html">fillna method</a> will be helpful for this one</li>
</ul>
</li>
<li><p>custom features</p>
<ul>
<li>These are your own design; combine techniques used above or come up with something else entirely. We look forward to seeing what you come up with!
Some ideas to get you started:<ul>
<li>normalize using a <a href="https://en.wikipedia.org/wiki/Feature_scaling">feature scaling equation</a></li>
<li>normalize the polar coordinates</li>
<li>adding additional deltas</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [11]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># DONE add features for normalized by speaker values of left, right, x, y</span>
<span class="c1"># Name these 'norm-rx', 'norm-ry', 'norm-lx', and 'norm-ly'</span>
<span class="c1"># using Z-score scaling (X-Xmean)/Xstd</span>
<span class="n">features_norm</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'norm-rx'</span><span class="p">,</span> <span class="s1">'norm-ry'</span><span class="p">,</span> <span class="s1">'norm-lx'</span><span class="p">,</span><span class="s1">'norm-ly'</span><span class="p">]</span>
<span class="n">features_raw</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'right-x'</span><span class="p">,</span> <span class="s1">'right-y'</span><span class="p">,</span> <span class="s1">'left-x'</span><span class="p">,</span> <span class="s1">'left-y'</span><span class="p">]</span>
<span class="k">for</span> <span class="n">norm</span><span class="p">,</span> <span class="n">raw</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">features_norm</span><span class="p">,</span> <span class="n">features_raw</span><span class="p">):</span>
<span class="c1"># (X-Xmean)/Xstd</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="n">norm</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="n">raw</span><span class="p">]</span> <span class="o">-</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'speaker'</span><span class="p">]</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">df_means</span><span class="p">[</span><span class="n">raw</span><span class="p">]))</span> <span class="o">/</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'speaker'</span><span class="p">]</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">df_std</span><span class="p">[</span><span class="n">raw</span><span class="p">])</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [12]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># DONE add features for polar coordinate values where the nose is the origin</span>
<span class="c1"># Name these 'polar-rr', 'polar-rtheta', 'polar-lr', and 'polar-ltheta'</span>
<span class="c1"># Note that 'polar-rr' and 'polar-rtheta' refer to the radius and angle</span>
<span class="n">features_polar</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'polar-rr'</span><span class="p">,</span> <span class="s1">'polar-rtheta'</span><span class="p">,</span> <span class="s1">'polar-lr'</span><span class="p">,</span> <span class="s1">'polar-ltheta'</span><span class="p">]</span>
<span class="n">rx</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'grnd-rx'</span><span class="p">]</span>
<span class="n">ry</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'grnd-ry'</span><span class="p">]</span>
<span class="n">lx</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'grnd-lx'</span><span class="p">]</span>
<span class="n">ly</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'grnd-ly'</span><span class="p">]</span>
<span class="c1"># polar radius = sqrt(x^2 + y^2) => hypotenuse (numpy)</span>
<span class="c1"># https://docs.scipy.org/doc/numpy/reference/generated/numpy.hypot.html</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'polar-rr'</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">hypot</span><span class="p">(</span><span class="n">rx</span><span class="p">,</span> <span class="n">ry</span><span class="p">)</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'polar-lr'</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">hypot</span><span class="p">(</span><span class="n">lx</span><span class="p">,</span> <span class="n">ly</span><span class="p">)</span>
<span class="c1"># polar theta = arctan2 given x and y coordinates</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'polar-rtheta'</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arctan2</span><span class="p">(</span><span class="n">rx</span><span class="p">,</span> <span class="n">ry</span><span class="p">)</span> <span class="c1"># x/y swapped</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'polar-ltheta'</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arctan2</span><span class="p">(</span><span class="n">lx</span><span class="p">,</span> <span class="n">ly</span><span class="p">)</span> <span class="c1"># x/y swapped</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [13]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># DONE add features for left, right, x, y differences by one time step, i.e. the "delta" values discussed in the lecture</span>
<span class="c1"># Name these 'delta-rx', 'delta-ry', 'delta-lx', and 'delta-ly'</span>
<span class="n">features_delta</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'delta-rx'</span><span class="p">,</span> <span class="s1">'delta-ry'</span><span class="p">,</span> <span class="s1">'delta-lx'</span><span class="p">,</span> <span class="s1">'delta-ly'</span><span class="p">]</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'delta-rx'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'right-x'</span><span class="p">]</span><span class="o">.</span><span class="n">diff</span><span class="p">()</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'delta-ry'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'right-y'</span><span class="p">]</span><span class="o">.</span><span class="n">diff</span><span class="p">()</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'delta-lx'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'left-x'</span><span class="p">]</span><span class="o">.</span><span class="n">diff</span><span class="p">()</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'delta-ly'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'left-y'</span><span class="p">]</span><span class="o">.</span><span class="n">diff</span><span class="p">()</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [14]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># DONE add features of your own design, which may be a combination of the above or something else</span>
<span class="c1"># Name these whatever you would like</span>
<span class="c1"># get new stats for normalization of polar coords</span>
<span class="n">df_means2</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="s1">'speaker'</span><span class="p">)</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
<span class="n">df_std2</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="s1">'speaker'</span><span class="p">)</span><span class="o">.</span><span class="n">std</span><span class="p">()</span>
<span class="n">features_polar_norm</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'norm-polar-rr'</span><span class="p">,</span> <span class="s1">'norm-polar-rtheta'</span><span class="p">,</span> <span class="s1">'norm-polar-lr'</span><span class="p">,</span> <span class="s1">'norm-polar-ltheta'</span><span class="p">]</span>
<span class="n">features_delta_polar_norm</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'delta-norm-polar-rr'</span><span class="p">,</span> <span class="s1">'delta-norm-polar-rtheta'</span><span class="p">,</span> <span class="s1">'delta-norm-polar-lr'</span><span class="p">,</span> <span class="s1">'delta-norm-polar-ltheta'</span><span class="p">]</span>
<span class="c1"># generate new polar norm features</span>
<span class="k">for</span> <span class="n">norm</span><span class="p">,</span> <span class="n">raw</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">features_polar_norm</span><span class="p">,</span> <span class="n">features_polar</span><span class="p">):</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="n">norm</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="n">raw</span><span class="p">]</span> <span class="o">-</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'speaker'</span><span class="p">]</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">df_means2</span><span class="p">[</span><span class="n">raw</span><span class="p">]))</span> <span class="o">/</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'speaker'</span><span class="p">]</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">df_std2</span><span class="p">[</span><span class="n">raw</span><span class="p">])</span>
<span class="c1"># generate new delta polar norm features</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'delta-norm-polar-rr'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'norm-polar-rr'</span><span class="p">]</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">diff</span><span class="p">()</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'delta-norm-polar-rtheta'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'norm-polar-rtheta'</span><span class="p">]</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">diff</span><span class="p">()</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'delta-norm-polar-lr'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'norm-polar-lr'</span><span class="p">]</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">diff</span><span class="p">()</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'delta-norm-polar-ltheta'</span><span class="p">]</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="s1">'norm-polar-ltheta'</span><span class="p">]</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">diff</span><span class="p">()</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="c1"># DONE define a list named 'features_custom' for building the training set</span>
<span class="n">features_custom</span> <span class="o">=</span> <span class="n">features_polar_norm</span> <span class="o">+</span> <span class="n">features_delta_polar_norm</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><strong>Question 1:</strong> What custom features did you choose for the features_custom set and why?</p>
<p><strong>Answer 1:</strong></p>
<blockquote><ul>
<li>Normalized Polar Coordinates: Arm length differences among the speakers can impact the distance measured between their hands and nose. This would ultimately have an impact on the polar coordinates, giving distorting differences among same signed words. To diminish this noise, we can normalize the polar coordinates.</li>
<li>Delta for Normalized Polar Coordinates: Per Thad's lecture, frame deltas can be a powerful feature. Hence, this should have a strong positive impact on the model's accuracy.</li>
</ul>
</blockquote>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><a id='part1_test'></a></p>
<h3 id="Features-Unit-Testing">Features Unit Testing<a class="anchor-link" href="#Features-Unit-Testing">¶</a></h3><p>Run the following unit tests as a sanity check on the defined "ground", "norm", "polar", and 'delta"
feature sets. The test simply looks for some valid values but is not exhaustive. However, the project should not be submitted if these tests don't pass.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [15]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>
<span class="c1"># import numpy as np</span>
<span class="k">class</span> <span class="nc">TestFeatures</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">test_features_ground</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">sample</span> <span class="o">=</span> <span class="p">(</span><span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">ix</span><span class="p">[</span><span class="mi">98</span><span class="p">,</span> <span class="mi">1</span><span class="p">][</span><span class="n">features_ground</span><span class="p">])</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">sample</span><span class="p">,</span> <span class="p">[</span><span class="mi">9</span><span class="p">,</span> <span class="mi">113</span><span class="p">,</span> <span class="o">-</span><span class="mi">12</span><span class="p">,</span> <span class="mi">119</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">test_features_norm</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">sample</span> <span class="o">=</span> <span class="p">(</span><span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">ix</span><span class="p">[</span><span class="mi">98</span><span class="p">,</span> <span class="mi">1</span><span class="p">][</span><span class="n">features_norm</span><span class="p">])</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="n">np</span><span class="o">.</span><span class="n">testing</span><span class="o">.</span><span class="n">assert_almost_equal</span><span class="p">(</span><span class="n">sample</span><span class="p">,</span> <span class="p">[</span> <span class="mf">1.153</span><span class="p">,</span> <span class="mf">1.663</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.891</span><span class="p">,</span> <span class="mf">0.742</span><span class="p">],</span> <span class="mi">3</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_features_polar</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">sample</span> <span class="o">=</span> <span class="p">(</span><span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">ix</span><span class="p">[</span><span class="mi">98</span><span class="p">,</span><span class="mi">1</span><span class="p">][</span><span class="n">features_polar</span><span class="p">])</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="n">np</span><span class="o">.</span><span class="n">testing</span><span class="o">.</span><span class="n">assert_almost_equal</span><span class="p">(</span><span class="n">sample</span><span class="p">,</span> <span class="p">[</span><span class="mf">113.3578</span><span class="p">,</span> <span class="mf">0.0794</span><span class="p">,</span> <span class="mf">119.603</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.1005</span><span class="p">],</span> <span class="mi">3</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test_features_delta</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">sample</span> <span class="o">=</span> <span class="p">(</span><span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">ix</span><span class="p">[</span><span class="mi">98</span><span class="p">,</span> <span class="mi">0</span><span class="p">][</span><span class="n">features_delta</span><span class="p">])</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">sample</span><span class="p">,</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">])</span>
<span class="n">sample</span> <span class="o">=</span> <span class="p">(</span><span class="n">asl</span><span class="o">.</span><span class="n">df</span><span class="o">.</span><span class="n">ix</span><span class="p">[</span><span class="mi">98</span><span class="p">,</span> <span class="mi">18</span><span class="p">][</span><span class="n">features_delta</span><span class="p">])</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertTrue</span><span class="p">(</span><span class="n">sample</span> <span class="ow">in</span> <span class="p">[[</span><span class="o">-</span><span class="mi">16</span><span class="p">,</span> <span class="o">-</span><span class="mi">5</span><span class="p">,</span> <span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">],</span> <span class="p">[</span><span class="o">-</span><span class="mi">14</span><span class="p">,</span> <span class="o">-</span><span class="mi">9</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">]],</span> <span class="s2">"Sample value found was </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">sample</span><span class="p">))</span>
<span class="n">suite</span> <span class="o">=</span> <span class="n">unittest</span><span class="o">.</span><span class="n">TestLoader</span><span class="p">()</span><span class="o">.</span><span class="n">loadTestsFromModule</span><span class="p">(</span><span class="n">TestFeatures</span><span class="p">())</span>
<span class="n">unittest</span><span class="o">.</span><span class="n">TextTestRunner</span><span class="p">()</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">suite</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stderr output_text">
<pre>....
----------------------------------------------------------------------
Ran 4 tests in 0.009s
OK
</pre>
</div>
</div>
<div class="output_area">
<div class="prompt output_prompt">Out[15]:</div>
<div class="output_text output_subarea output_execute_result">
<pre><unittest.runner.TextTestResult run=4 errors=0 failures=0></pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><a id='part2_tutorial'></a></p>
<h2 id="PART-2:-Model-Selection">PART 2: Model Selection<a class="anchor-link" href="#PART-2:-Model-Selection">¶</a></h2><h3 id="Model-Selection-Tutorial">Model Selection Tutorial<a class="anchor-link" href="#Model-Selection-Tutorial">¶</a></h3><p>The objective of Model Selection is to tune the number of states for each word HMM prior to testing on unseen data. In this section you will explore three methods:</p>
<ul>
<li>Log likelihood using cross-validation folds (CV)</li>
<li>Bayesian Information Criterion (BIC)</li>
<li>Discriminative Information Criterion (DIC) </li>
</ul>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Train-a-single-word">Train a single word<a class="anchor-link" href="#Train-a-single-word">¶</a></h5><p>Now that we have built a training set with sequence data, we can "train" models for each word. As a simple starting example, we train a single word using Gaussian hidden Markov models (HMM). By using the <code>fit</code> method during training, the <a href="https://en.wikipedia.org/wiki/Baum%E2%80%93Welch_algorithm">Baum-Welch Expectation-Maximization</a> (EM) algorithm is invoked iteratively to find the best estimate for the model <em>for the number of hidden states specified</em> from a group of sample seequences. For this example, we <em>assume</em> the correct number of hidden states is 3, but that is just a guess. How do we know what the "best" number of states for training is? We will need to find some model selection technique to choose the best parameter.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [16]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">warnings</span>
<span class="kn">from</span> <span class="nn">hmmlearn.hmm</span> <span class="k">import</span> <span class="n">GaussianHMM</span>
<span class="k">def</span> <span class="nf">train_a_word</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="n">num_hidden_states</span><span class="p">,</span> <span class="n">features</span><span class="p">):</span>
<span class="n">warnings</span><span class="o">.</span><span class="n">filterwarnings</span><span class="p">(</span><span class="s2">"ignore"</span><span class="p">,</span> <span class="n">category</span><span class="o">=</span><span class="ne">DeprecationWarning</span><span class="p">)</span>
<span class="n">training</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">build_training</span><span class="p">(</span><span class="n">features</span><span class="p">)</span>
<span class="n">X</span><span class="p">,</span> <span class="n">lengths</span> <span class="o">=</span> <span class="n">training</span><span class="o">.</span><span class="n">get_word_Xlengths</span><span class="p">(</span><span class="n">word</span><span class="p">)</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">GaussianHMM</span><span class="p">(</span><span class="n">n_components</span><span class="o">=</span><span class="n">num_hidden_states</span><span class="p">,</span> <span class="n">n_iter</span><span class="o">=</span><span class="mi">1000</span><span class="p">)</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X</span><span class="p">,</span> <span class="n">lengths</span><span class="p">)</span>
<span class="n">logL</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">X</span><span class="p">,</span> <span class="n">lengths</span><span class="p">)</span>
<span class="k">return</span> <span class="n">model</span><span class="p">,</span> <span class="n">logL</span>
<span class="n">demoword</span> <span class="o">=</span> <span class="s1">'BOOK'</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">demoword</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">features_ground</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Number of states trained in model for </span><span class="si">{}</span><span class="s2"> is </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">demoword</span><span class="p">,</span> <span class="n">model</span><span class="o">.</span><span class="n">n_components</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for BOOK is 3
logL = -2331.1138127433205
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>The HMM model has been trained and information can be pulled from the model, including means and variances for each feature and hidden state. The <a href="http://math.stackexchange.com/questions/892832/why-we-consider-log-likelihood-instead-of-likelihood-in-gaussian-distribution">log likelihood</a> for any individual sample or group of samples can also be calculated with the <code>score</code> method.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [17]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="k">def</span> <span class="nf">show_model_stats</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="n">model</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Number of states trained in model for </span><span class="si">{}</span><span class="s2"> is </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="n">model</span><span class="o">.</span><span class="n">n_components</span><span class="p">))</span>
<span class="n">variance</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="n">np</span><span class="o">.</span><span class="n">diag</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">covars_</span><span class="p">[</span><span class="n">i</span><span class="p">])</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">n_components</span><span class="p">)])</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">n_components</span><span class="p">):</span> <span class="c1"># for each hidden state</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"hidden state #</span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">i</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"mean = "</span><span class="p">,</span> <span class="n">model</span><span class="o">.</span><span class="n">means_</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"variance = "</span><span class="p">,</span> <span class="n">variance</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="nb">print</span><span class="p">()</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">demoword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for BOOK is 3
hidden state #0
mean = [ -11.45300909 94.109178 19.03512475 102.2030162 ]
variance = [ 77.403668 203.35441965 26.68898447 156.12444034]
hidden state #1
mean = [ -3.46504869 50.66686933 14.02391587 52.04731066]
variance = [ 49.12346305 43.04799144 39.35109609 47.24195772]
hidden state #2
mean = [ -1.12415027 69.44164191 17.02866283 77.7231196 ]
variance = [ 19.70434594 16.83041492 30.51552305 11.03678246]
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Try-it!">Try it!<a class="anchor-link" href="#Try-it!">¶</a></h5><p>Experiment by changing the feature set, word, and/or num_hidden_states values in the next cell to see changes in values.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="Experimenting-with-different-params">Experimenting with different params<a class="anchor-link" href="#Experimenting-with-different-params">¶</a></h3>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [17]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">my_testword</span> <span class="o">=</span> <span class="s1">'CHOCOLATE'</span>
<span class="c1"># Experiment here with different parameters</span>
<span class="c1"># Hidden states = 3</span>
<span class="c1"># Features = features_ground</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">features_ground</span><span class="p">)</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for CHOCOLATE is 3
hidden state #0
mean = [ 0.58333333 87.91666667 12.75 108.5 ]
variance = [ 39.41055556 18.74388889 9.855 144.4175 ]
hidden state #1
mean = [ -9.30211403 55.32333876 6.92259936 71.24057775]
variance = [ 16.16920957 46.50917372 3.81388185 15.79446427]
hidden state #2
mean = [ -5.40587658 60.1652424 2.32479599 91.3095432 ]
variance = [ 7.95073876 64.13103127 13.68077479 129.5912395 ]
logL = -601.3291470028619
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [18]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Hidden states = 5</span>
<span class="c1"># Features = features_ground</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="n">features_ground</span><span class="p">)</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for CHOCOLATE is 5
hidden state #0
mean = [ -4.93673736 64.73126904 1.62601029 84.91542811]
variance = [ 6.16147276 28.36727822 5.4706657 13.12675543]
hidden state #1
mean = [ -7.70665738 93.36393433 12.99292645 127.06351815]
variance = [ 29.53966949 13.52107768 0.66764483 48.4385572 ]
hidden state #2
mean = [ 3.32089022 86.11784619 12.66977977 102.36987409]
variance = [ 12.48273231 7.43528515 12.86407411 24.73804616]
hidden state #3
mean = [ -6.37753172 51.09767101 3.64019095 104.46455217]
variance = [ 10.28279876 12.43850367 27.33782827 106.89825397]
hidden state #4
mean = [ -9.23826304 55.30740641 6.92298855 71.30558162]
variance = [ 16.30897315 45.96991798 3.76848558 15.98402053]
logL = -544.2490114712293
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [19]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Hidden states = 5</span>
<span class="c1"># Features = features_custom</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="n">features_custom</span><span class="p">)</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for CHOCOLATE is 5
hidden state #0
mean = [-0.14925569 0.82325349 -1.51836159 -0.56284318 -0.0336368 0.06155974
-0.09162892 0.01971325]
variance = [ 0.00940745 0.03196555 0.12150031 0.04219313 0.00622097 0.0173876
0.03799468 0.02153849]
hidden state #1
mean = [-0.44625101 0.261368 -0.73096552 -0.25967622 0.03781022 0.04738094
-0.44216309 0.06351477]
variance = [ 0.0068445 0.03372716 0.2987258 0.01092846 0.00296635 0.00769682
0.00782123 0.02306752]
hidden state #2
mean = [-0.00400922 0.51523053 -0.88045723 -0.16424537 0.06642172 -0.00156156
0.01665437 0.00281624]
variance = [ 0.03215712 0.03275756 0.07757933 0.01890142 0.00943858 0.00655269
0.02043576 0.01854633]
hidden state #3
mean = [-0.39240872 0.21197653 -1.8790557 -0.24720567 0.01569517 -0.01989206
-0.02178569 0.0041389 ]
variance = [ 0.00557964 0.01415824 0.00152366 0.00136303 0.00635711 0.01739035
0.00978684 0.00143182]
hidden state #4
mean = [ -4.73786402e-01 6.07747068e-01 2.82580403e-01 -4.38044211e-01
7.94567451e-02 5.70878600e-02 -1.79681513e-20 -1.91625527e-21]
variance = [ 0.01131337 0.00825902 0.005 0.005 0.01131337 0.00825902
0.005 0.005 ]
logL = 285.1016234325817
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [20]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Hidden states = 5</span>
<span class="c1"># Features = features_delta</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="n">features_delta</span><span class="p">)</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for CHOCOLATE is 5
hidden state #0
mean = [ 0. 0. 0. 0.]
variance = [ 0.00052632 0.00052632 0.00052632 0.00052632]
hidden state #1
mean = [ 0.86285472 0.95873664 0.74031447 -9.43679815]
variance = [ 2.42024112 1.38275633 10.85095231 11.84719275]
hidden state #2
mean = [ 0.26423101 4.75590611 0.69728368 5.20905851]
variance = [ 15.78452098 19.65733494 15.38289096 9.66814788]
hidden state #3
mean = [ 4.99999998 -3.39999997 -1.99999999 -8.80000001]
variance = [ 11.60200002 5.04200011 5.20200001 13.36199995]
hidden state #4
mean = [-1.85716798 2.28566982 0. 0. ]
variance = [ 2.78380677e+01 9.63401728e+00 1.42857733e-03 1.42857733e-03]
logL = -59.18801202860831
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [21]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Hidden states = 5</span>
<span class="c1"># Features = features_delta_polar_norm</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="n">features_delta_polar_norm</span><span class="p">)</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for CHOCOLATE is 5
hidden state #0
mean = [-0.00314991 -0.07953286 -0.22050097 0.23622811]
variance = [ 0.00560103 0.01084632 0.05346053 0.01434641]
hidden state #1
mean = [ 1.34731584e-03 -6.20008254e-03 -1.59597231e-12 1.36953813e-12]
variance = [ 0.00104624 0.00753053 0.00045655 0.00045655]
hidden state #2
mean = [ 0.15143428 0.02568643 0.12933596 0.06112101]
variance = [ 0.01185609 0.02154619 0.01505076 0.00744944]
hidden state #3
mean = [-0.01540876 0.08834336 -0.32417316 -0.02547907]
variance = [ 0.00487484 0.00692047 0.01158948 0.01541168]
hidden state #4
mean = [ 0.19669649 -0.02655891 0.2365145 -0.4433212 ]
variance = [ 0.00999999 0.01 0.00999998 0.01000053]
logL = 257.16149734266344
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [22]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Hidden states = 3</span>
<span class="c1"># Features = features_delta_polar_norm</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">features_delta_polar_norm</span><span class="p">)</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for CHOCOLATE is 3
hidden state #0
mean = [ -3.30017104e-03 -7.36061325e-03 -7.05049916e-12 6.04805115e-12]
variance = [ 0.00062308 0.00798317 0.00047833 0.00047833]
hidden state #1
mean = [-0.00232987 0.07113751 -0.32068122 -0.00507313]
variance = [ 0.00537749 0.00824713 0.02208024 0.01820034]
hidden state #2
mean = [ 0.11513179 -0.00034274 0.08839649 0.06034013]
variance = [ 0.01465258 0.01919955 0.02121595 0.03455639]
logL = 243.823375473056
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [23]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Hidden states = 1</span>
<span class="c1"># Features = features_delta_polar_norm</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">features_delta_polar_norm</span><span class="p">)</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for CHOCOLATE is 1
hidden state #0
mean = [ 0.02861422 0.018563 -0.07465093 0.01455437]
variance = [ 0.00814318 0.01187925 0.04024481 0.01536548]
logL = 130.85519033449012
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [24]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Hidden states = 7</span>
<span class="c1"># Features = features_delta_polar_norm</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="n">features_delta_polar_norm</span><span class="p">)</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for CHOCOLATE is 7
hidden state #0
mean = [ 0.07308074 -0.0149723 0.00178149 0.02596297]
variance = [ 0.01387967 0.0543756 0.00540081 0.00313285]
hidden state #1
mean = [-0.01669721 0.0711175 -0.27059137 -0.09129257]
variance = [ 0.00595829 0.00862358 0.02347137 0.00597358]
hidden state #2
mean = [ -3.50120181e-16 7.20640383e-16 -1.46174378e-16 -2.46293454e-16]
variance = [ 0.00052689 0.00052689 0.00052689 0.00052689]
hidden state #3
mean = [ 0.0201976 0.07172625 -0.39921043 0.12893594]
variance = [ 0.0053465 0.00921889 0.01149137 0.00943241]
hidden state #4
mean = [ 0.19669656 -0.0265588 0.23651451 -0.4433219 ]
variance = [ 0.01 0.01000001 0.01 0.01000018]
hidden state #5
mean = [ 0.14518477 -0.0058136 0.21452247 0.08933145]
variance = [ 0.01985784 0.00704195 0.00952282 0.00986405]
hidden state #6
mean = [ -7.40503940e-06 3.89280897e-05 -8.31331858e-02 3.03066597e-01]
variance = [ 0.00501488 0.0050212 0.00705418 0.0120447 ]
logL = 297.93888063909657
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [25]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Hidden states = 9</span>
<span class="c1"># Features = features_delta_polar_norm</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="n">features_delta_polar_norm</span><span class="p">)</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for CHOCOLATE is 9
hidden state #0
mean = [-0.03123049 0.07832673 -0.30179813 -0.10413859]
variance = [ 0.00494798 0.00924873 0.01666204 0.00537068]
hidden state #1
mean = [ -3.94774778e-16 8.05091721e-16 -1.67130041e-16 -2.81611634e-16]
variance = [ 0.00052647 0.00052647 0.00052647 0.00052647]
hidden state #2
mean = [ 0.02045416 0.07206602 -0.39892901 0.12730019]
variance = [ 0.00523072 0.0090806 0.0112285 0.00939895]
hidden state #3
mean = [ 0.19669658 -0.02655874 0.23651451 -0.44332222]
variance = [ 0.01 0.01 0.01 0.01]
hidden state #4
mean = [ 0.2368152 -0.04746886 0.15637418 0.13313286]
variance = [ 0.00701465 0.00718207 0.007147 0.00884294]
hidden state #5
mean = [ 0.01500555 -0.27127114 -0.03724529 0.03199608]
variance = [ 0.01223289 0.00751883 0.00610574 0.00538241]
hidden state #6
mean = [ 0.11314619 0.14402222 0.02493173 0.01716982]
variance = [ 0.01067874 0.00946733 0.00448464 0.00318322]
hidden state #7
mean = [ -1.03321693e-05 4.27593700e-05 -8.30334571e-02 3.02880178e-01]
variance = [ 0.00500362 0.00501111 0.00704309 0.01203431]
hidden state #8
mean = [ 0.00768342 0.05668119 0.30179187 0.02359831]
variance = [ 0.01263054 0.00532223 0.00539679 0.00919909]
logL = 312.5916438167874
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [26]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Hidden states = 15</span>
<span class="c1"># Features = features_delta_polar_norm</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="n">features_delta_polar_norm</span><span class="p">)</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for CHOCOLATE is 15
hidden state #0
mean = [ -6.37669523e-06 2.82537701e-05 -8.30407914e-02 3.02901367e-01]
variance = [ 0.00500393 0.00500894 0.00704338 0.01203047]
hidden state #1
mean = [ 4.88167268e-03 4.70470971e-04 6.84026945e-20 5.95293275e-20]
variance = [ 0.00095279 0.00050426 0.00050006 0.00050006]
hidden state #2
mean = [-0.06241948 0.11744381 -0.3002239 0.0319183 ]
variance = [1000. 1000. 1000. 1000.]
hidden state #3
mean = [ 0.27241785 -0.00527029 0.12110212 0.14982645]
variance = [ 0.00671898 0.00543085 0.00698792 0.01242833]
hidden state #4
mean = [ 0.19669658 -0.02655874 0.23651451 -0.44332222]
variance = [ 0.01 0.01 0.01 0.01]
hidden state #5
mean = [-0.03676285 0.12181973 -0.33808422 0.18211529]
variance = [ 0.00731655 0.00515397 0.00791461 0.00592145]
hidden state #6
mean = [ 0.01508759 -0.27124297 -0.03722053 0.03197474]
variance = [ 0.01223528 0.00751606 0.00610261 0.0053795 ]
hidden state #7
mean = [ 0.11698883 0.17707856 0.03103251 0.02137633]
variance = [ 0.01320826 0.00619449 0.00539306 0.00387319]
hidden state #8
mean = [ 0.16561611 -0.13186754 0.22691846 0.09974913]
variance = [ 0.01 0.01 0.01 0.01]
hidden state #9
mean = [ 0.00768482 0.05668148 0.30179155 0.02359935]
variance = [ 0.01263062 0.00532231 0.00539687 0.00919917]
hidden state #10
mean = [ 0.0687524 -0.08767796 -0.59880921 0.25460297]
variance = [ 0.01 0.01 0.01 0.01]
hidden state #11
mean = [-0.02744924 -0.00784049 -0.19656018 -0.11244123]
variance = [ 0.00484025 0.00345628 0.01011196 0.00745694]
hidden state #12
mean = [-0.01366772 0.10802446 -0.40458588 -0.12309509]
variance = [ 0.00638914 0.00654798 0.00664642 0.00480186]
hidden state #13
mean = [-0.12064687 0.22726322 -0.20682436 -0.01521957]
variance = [ 0.01002291 0.01015113 0.01010243 0.01000576]
hidden state #14
mean = [ 0.04377026 0.08958253 -0.37475667 0.04973574]
variance = [ 0.00522396 0.0073448 0.00368578 0.00426046]
logL = 335.9134076181284
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [27]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Hidden states = 25</span>
<span class="c1"># Features = features_delta_polar_norm</span>
<span class="n">model</span><span class="p">,</span> <span class="n">logL</span> <span class="o">=</span> <span class="n">train_a_word</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="mi">25</span><span class="p">,</span> <span class="n">features_delta_polar_norm</span><span class="p">)</span>
<span class="n">show_model_stats</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"logL = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">logL</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for CHOCOLATE is 25
hidden state #0
mean = [ -2.32037225e-16 7.89907792e-16 -9.73463946e-21 5.63522155e-20]
variance = [ 0.00052655 0.00052655 0.00052655 0.00052655]
hidden state #1
mean = [-0.12106391 0.22804878 -0.20615445 -0.01555813]
variance = [ 0.01 0.01 0.01 0.01]
hidden state #2
mean = [ 0.0687524 -0.08767796 -0.59880921 0.25460297]
variance = [ 0.01 0.01 0.01 0.01]
hidden state #3
mean = [ 0.04375868 0.08944678 -0.37482616 0.04978911]
variance = [ 0.00521498 0.00734278 0.00367647 0.00425681]
hidden state #4
mean = [ 0.00770102 0.05668481 0.30178786 0.02361137]
variance = [ 0.01263155 0.00532323 0.0053978 0.0092001 ]
hidden state #5
mean = [ 6.36751327e-02 -2.98716237e-01 -3.25578187e-06 1.88862829e-05]
variance = [ 0.01126331 0.00900729 0.00500298 0.00500699]
hidden state #6
mean = [ 0.19669658 -0.02655874 0.23651451 -0.44332222]
variance = [ 0.01 0.01 0.01 0.01]
hidden state #7
mean = [ -3.30577292e-10 7.72820051e-10 -1.28176032e-01 3.86600757e-01]
variance = [ 0.00999974 0.00999974 0.00999995 0.01000047]
hidden state #8
mean = [ 0.10579649 0.1109365 0.0003525 0.00024879]
variance = [ 0.01277185 0.00688944 0.00258344 0.00256157]
hidden state #9
mean = [-0.02744924 -0.00784049 -0.19656018 -0.11244123]
variance = [ 0.00484025 0.00345628 0.01011196 0.00745694]
hidden state #10
mean = [ 0.1656162 -0.13186739 0.22691825 0.09974908]
variance = [ 0.01000001 0.01000002 0.01000003 0.01 ]
hidden state #11
mean = [ 0.02213815 0.05019149 -0.44859745 -0.11251116]
variance = [ 0.00500207 0.0050043 0.00605111 0.00874689]
hidden state #12
mean = [-0.08489336 0.1094113 -0.28409709 0.15175983]
variance = [ 0.01 0.01 0.01 0.01]
hidden state #13
mean = [ 0.3138777 0.01548645 0.16568805 0.23601405]
variance = [ 0.01000002 0.01000002 0.00999999 0.01000001]
hidden state #14
mean = [-0.00799959 0.0084428 -0.02752297 -0.00713534]
variance = [1000. 1000. 1000. 1000.]
hidden state #15
mean = [-0.00044881 0.00047367 -0.00154414 -0.00040032]
variance = [1000. 1000. 1000. 1000.]
hidden state #16
mean = [ 0.04159721 0.04944981 0.05859401 0.06651426]
variance = [1000. 1000. 1000. 1000.]
hidden state #17
mean = [ 0.02272124 0.20330536 -0.30254238 -0.15883416]
variance = [ 0.01 0.01 0.01 0.01]
hidden state #18
mean = [ 0.23092729 -0.02602087 0.07654007 0.06362845]
variance = [ 0.01000858 0.00999943 0.01000493 0.0100001 ]
hidden state #19
mean = [-0.08218897 -0.2165478 -0.11166676 0.09579049]
variance = [ 0.00999992 0.01000095 0.01000006 0.00999998]
hidden state #20
mean = [ -4.86387053e-05 2.28474525e-03 -3.71440963e-02 2.16092121e-01]
variance = [ 0.01000453 0.01043148 0.00992858 0.01053228]
hidden state #21
mean = [ -4.07670539e-08 2.50662811e-08 -4.00627850e-01 8.27278516e-02]
variance = [1000. 1000. 1000. 1000.]
hidden state #22
mean = [ 0.14112592 0.26314376 0.11582885 0.07990183]
variance = [ 0.01096344 0.01035749 0.01044129 0.00992418]
hidden state #23
mean = [-0.12166844 0.1284095 -0.41860622 -0.10852387]
variance = [ 0.01 0.01 0.01 0.01]
hidden state #24
mean = [ 0.01136766 0.13422816 -0.39207135 0.21247076]
variance = [ 0.01 0.01 0.01 0.01]
logL = 348.08435070788096
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Visualize-the-hidden-states">Visualize the hidden states<a class="anchor-link" href="#Visualize-the-hidden-states">¶</a></h5><p>We can plot the means and variances for each state and feature. Try varying the number of states trained for the HMM model and examine the variances. Are there some models that are "better" than others? How can you tell? We would like to hear what you think in the classroom online.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [28]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="o">%</span><span class="k">matplotlib</span> inline
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [30]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">math</span>
<span class="kn">from</span> <span class="nn">matplotlib</span> <span class="k">import</span> <span class="p">(</span><span class="n">cm</span><span class="p">,</span> <span class="n">pyplot</span> <span class="k">as</span> <span class="n">plt</span><span class="p">,</span> <span class="n">mlab</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">visualize</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="n">model</span><span class="p">):</span>
<span class="sd">""" visualize the input model for a particular word """</span>
<span class="n">variance</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="n">np</span><span class="o">.</span><span class="n">diag</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">covars_</span><span class="p">[</span><span class="n">i</span><span class="p">])</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">n_components</span><span class="p">)])</span>
<span class="n">figures</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">parm_idx</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">means_</span><span class="p">[</span><span class="mi">0</span><span class="p">])):</span>
<span class="n">xmin</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="nb">min</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">means_</span><span class="p">[:,</span><span class="n">parm_idx</span><span class="p">])</span> <span class="o">-</span> <span class="nb">max</span><span class="p">(</span><span class="n">variance</span><span class="p">[:,</span><span class="n">parm_idx</span><span class="p">]))</span>
<span class="n">xmax</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="nb">max</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">means_</span><span class="p">[:,</span><span class="n">parm_idx</span><span class="p">])</span> <span class="o">+</span> <span class="nb">max</span><span class="p">(</span><span class="n">variance</span><span class="p">[:,</span><span class="n">parm_idx</span><span class="p">]))</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">axs</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">n_components</span><span class="p">,</span> <span class="n">sharex</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">sharey</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="n">colours</span> <span class="o">=</span> <span class="n">cm</span><span class="o">.</span><span class="n">rainbow</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">linspace</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">model</span><span class="o">.</span><span class="n">n_components</span><span class="p">))</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="p">(</span><span class="n">ax</span><span class="p">,</span> <span class="n">colour</span><span class="p">)</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">axs</span><span class="p">,</span> <span class="n">colours</span><span class="p">)):</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linspace</span><span class="p">(</span><span class="n">xmin</span><span class="p">,</span> <span class="n">xmax</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span>
<span class="n">mu</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">means_</span><span class="p">[</span><span class="n">i</span><span class="p">,</span><span class="n">parm_idx</span><span class="p">]</span>
<span class="n">sigma</span> <span class="o">=</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">diag</span><span class="p">(</span><span class="n">model</span><span class="o">.</span><span class="n">covars_</span><span class="p">[</span><span class="n">i</span><span class="p">])[</span><span class="n">parm_idx</span><span class="p">])</span>
<span class="n">ax</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">mlab</span><span class="o">.</span><span class="n">normpdf</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">mu</span><span class="p">,</span> <span class="n">sigma</span><span class="p">),</span> <span class="n">c</span><span class="o">=</span><span class="n">colour</span><span class="p">)</span>
<span class="n">ax</span><span class="o">.</span><span class="n">set_title</span><span class="p">(</span><span class="s2">"</span><span class="si">{}</span><span class="s2"> feature </span><span class="si">{}</span><span class="s2"> hidden state #</span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="n">parm_idx</span><span class="p">,</span> <span class="n">i</span><span class="p">))</span>
<span class="n">ax</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="n">figures</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">plt</span><span class="p">)</span>
<span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">figures</span><span class="p">:</span>
<span class="n">p</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
<span class="n">visualize</span><span class="p">(</span><span class="n">my_testword</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_png output_subarea ">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYYAAAEICAYAAABbOlNNAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz
AAALEgAACxIB0t1+/AAAIABJREFUeJzsnXd4VNXWxn8nhYQU<KEY>GKSBEsINjoCgJGv<KEY>
s/fZa633bE1E8MADDzzwwINSeN1sATzwwAMPPLi14FkYPPDAAw88sINnYfDAAw888MAOno<KEY>
<KEY>
<KEY>
<KEY>
0<KEY>
"
>
</div>
</div>
<div class="output_area">
<div class="prompt"></div>
<div class="output_png output_subarea ">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYYAAAEICAYAAABbOlNNAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz
AAALEgAACxIB0t1+/AAAIABJREFUeJzsnXd4VMX6xz8nhYQUUiGB<KEY>PxKapr2uadrK
<KEY>
<KEY>
<KEY>
<KEY>
s<KEY>
<KEY>
<KEY>
"
>
</div>
</div>
<div class="output_area">
<div class="prompt"></div>
<div class="output_png output_subarea ">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYYAAAEICAYAAABbOlNNAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz
AAALEgAACxIB0t1+/AAAIABJREFUeJzsnXd<KEY>
<KEY>
<KEY>
<KEY>
/<KEY>
<KEY>
"
>
</div>
</div>
<div class="output_area">
<div class="prompt"></div>
<div class="output_png output_subarea ">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYYAAAEICAY<KEY>ABHNCSVQ<KEY>
qUo29z6w6<KEY>
Q1<KEY>
<KEY>
"
>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="ModelSelector-class">ModelSelector class<a class="anchor-link" href="#ModelSelector-class">¶</a></h5><p>Review the <code>ModelSelector</code> class from the codebase found in the <code>my_model_selectors.py</code> module. It is designed to be a strategy pattern for choosing different model selectors. For the project submission in this section, subclass <code>SelectorModel</code> to implement the following model selectors. In other words, you will write your own classes/functions in the <code>my_model_selectors.py</code> module and run them from this notebook:</p>
<ul>
<li><code>SelectorCV</code>: Log likelihood with CV</li>
<li><code>SelectorBIC</code>: BIC </li>
<li><code>SelectorDIC</code>: DIC</li>
</ul>
<p>You will train each word in the training set with a range of values for the number of hidden states, and then score these alternatives with the model selector, choosing the "best" according to each strategy. The simple case of training with a constant value for <code>n_components</code> can be called using the provided <code>SelectorConstant</code> subclass as follow:</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [31]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">my_model_selectors</span> <span class="k">import</span> <span class="n">SelectorConstant</span>
<span class="n">training</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">build_training</span><span class="p">(</span><span class="n">features_ground</span><span class="p">)</span> <span class="c1"># Experiment here with different feature sets defined in part 1</span>
<span class="n">word</span> <span class="o">=</span> <span class="s1">'VEGETABLE'</span> <span class="c1"># Experiment here with different words</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">SelectorConstant</span><span class="p">(</span><span class="n">training</span><span class="o">.</span><span class="n">get_all_sequences</span><span class="p">(),</span> <span class="n">training</span><span class="o">.</span><span class="n">get_all_Xlengths</span><span class="p">(),</span> <span class="n">word</span><span class="p">,</span> <span class="n">n_constant</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span><span class="o">.</span><span class="n">select</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Number of states trained in model for </span><span class="si">{}</span><span class="s2"> is </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="n">model</span><span class="o">.</span><span class="n">n_components</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of states trained in model for VEGETABLE is 3
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [32]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">visualize</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_png output_subarea ">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAX4AAAEICAYAAABYoZ8gAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz
AAALEgAACxIB0t1+/AAAIABJREFUeJzsnXl8VcX5/99PNgIJYZUAAdlXRVZBVASrVVzBpRZXcC11
6/fXWl/<KEY>
"
>
</div>
</div>
<div class="output_area">
<div class="prompt"></div>
<div class="output_png output_subarea ">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAX4AAAEIC<KEY>gAAAABHNCSV<KEY>
EZHcyuSl<KEY>4HcdxGgwP/I7jOA2GB37HcZwG42eV
f1M5K02q3QAAAABJRU5ErkJggg==
"
>
</div>
</div>
<div class="output_area">
<div class="prompt"></div>
<div class="output_png output_subarea ">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAX4AAAEICAYAAABYoZ8gAAAABHNCSVQ<KEY>z
<KEY>
i<KEY>
"
>
</div>
</div>
<div class="output_area">
<div class="prompt"></div>
<div class="output_png output_subarea ">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUh<KEY>AEIC<KEY>HNCSV<KEY>
"
>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Cross-validation-folds">Cross-validation folds<a class="anchor-link" href="#Cross-validation-folds">¶</a></h5><p>If we simply score the model with the Log Likelihood calculated from the feature sequences it has been trained on, we should expect that more complex models will have higher likelihoods. However, that doesn't tell us which would have a better likelihood score on unseen data. The model will likely be overfit as complexity is added. To estimate which topology model is better using only the training data, we can compare scores using cross-validation. One technique for cross-validation is to break the training set into "folds" and rotate which fold is left out of training. The "left out" fold scored. This gives us a proxy method of finding the best model to use on "unseen data". In the following example, a set of word sequences is broken into three folds using the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html">scikit-learn Kfold</a> class object. When you implement <code>SelectorCV</code>, you will use this technique.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [33]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="k">import</span> <span class="n">KFold</span>
<span class="n">training</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">build_training</span><span class="p">(</span><span class="n">features_ground</span><span class="p">)</span> <span class="c1"># Experiment here with different feature sets</span>
<span class="n">word</span> <span class="o">=</span> <span class="s1">'VEGETABLE'</span> <span class="c1"># Experiment here with different words</span>
<span class="n">word_sequences</span> <span class="o">=</span> <span class="n">training</span><span class="o">.</span><span class="n">get_word_sequences</span><span class="p">(</span><span class="n">word</span><span class="p">)</span>
<span class="n">split_method</span> <span class="o">=</span> <span class="n">KFold</span><span class="p">()</span>
<span class="k">for</span> <span class="n">cv_train_idx</span><span class="p">,</span> <span class="n">cv_test_idx</span> <span class="ow">in</span> <span class="n">split_method</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">word_sequences</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Train fold indices:</span><span class="si">{}</span><span class="s2"> Test fold indices:</span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">cv_train_idx</span><span class="p">,</span> <span class="n">cv_test_idx</span><span class="p">))</span> <span class="c1"># view indices of the folds</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Train fold indices:[2 3 4 5] Test fold indices:[0 1]
Train fold indices:[0 1 4 5] Test fold indices:[2 3]
Train fold indices:[0 1 2 3] Test fold indices:[4 5]
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><strong>Tip:</strong> In order to run <code>hmmlearn</code> training using the X,lengths tuples on the new folds, subsets must be combined based on the indices given for the folds. A helper utility has been provided in the <code>asl_utils</code> module named <code>combine_sequences</code> for this purpose.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Scoring-models-with-other-criterion">Scoring models with other criterion<a class="anchor-link" href="#Scoring-models-with-other-criterion">¶</a></h5><p>Scoring model topologies with <strong>BIC</strong> balances fit and complexity within the training set for each word. In the BIC equation, a penalty term penalizes complexity to avoid overfitting, so that it is not necessary to also use cross-validation in the selection process. There are a number of references on the internet for this criterion. These <a href="http://www2.imm.dtu.dk/courses/02433/doc/ch6_slides.pdf">slides</a> include a formula you may find helpful for your implementation.</p>
<p>The advantages of scoring model topologies with <strong>DIC</strong> over BIC are presented by <NAME> in this <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf">reference</a> (also found <a href="https://pdfs.semanticscholar.org/ed3d/7c4a5f607201f3848d4c02dd9ba17c791fc2.pdf">here</a>). DIC scores the discriminant ability of a training set for one word against competing words. Instead of a penalty term for complexity, it provides a penalty if model liklihoods for non-matching words are too similar to model likelihoods for the correct word in the word set.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><a id='part2_submission'></a></p>
<h3 id="Model-Selection-Implementation-Submission">Model Selection Implementation Submission<a class="anchor-link" href="#Model-Selection-Implementation-Submission">¶</a></h3><p>Implement <code>SelectorCV</code>, <code>SelectorBIC</code>, and <code>SelectorDIC</code> classes in the <code>my_model_selectors.py</code> module. Run the selectors on the following five words. Then answer the questions about your results.</p>
<p><strong>Tip:</strong> The <code>hmmlearn</code> library may not be able to train or score all models. Implement try/except contructs as necessary to eliminate non-viable models from consideration.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [19]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Feature sets from Part 1</span>
<span class="n">feature_sets</span> <span class="o">=</span> <span class="p">[</span><span class="n">features_ground</span><span class="p">,</span> <span class="n">features_norm</span><span class="p">,</span> <span class="n">features_delta</span><span class="p">,</span>
<span class="n">features_polar</span><span class="p">,</span> <span class="n">features_polar_norm</span><span class="p">,</span> <span class="n">features_delta_polar_norm</span><span class="p">]</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [20]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">words_to_train</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'FISH'</span><span class="p">,</span> <span class="s1">'BOOK'</span><span class="p">,</span> <span class="s1">'VEGETABLE'</span><span class="p">,</span> <span class="s1">'FUTURE'</span><span class="p">,</span> <span class="s1">'JOHN'</span><span class="p">]</span>
<span class="kn">import</span> <span class="nn">timeit</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [31]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># DONE: Implement SelectorCV in my_model_selector.py</span>
<span class="kn">from</span> <span class="nn">my_model_selectors</span> <span class="k">import</span> <span class="n">SelectorCV</span>
<span class="c1"># Experiment here with different feature sets defined in part 1</span>
<span class="k">for</span> <span class="n">features</span> <span class="ow">in</span> <span class="n">feature_sets</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Features:"</span><span class="p">,</span> <span class="s2">", "</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">features</span><span class="p">))</span>
<span class="n">training</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">build_training</span><span class="p">(</span><span class="n">features_ground</span><span class="p">)</span>
<span class="n">sequences</span> <span class="o">=</span> <span class="n">training</span><span class="o">.</span><span class="n">get_all_sequences</span><span class="p">()</span>
<span class="n">Xlengths</span> <span class="o">=</span> <span class="n">training</span><span class="o">.</span><span class="n">get_all_Xlengths</span><span class="p">()</span>
<span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">words_to_train</span><span class="p">:</span>
<span class="n">start</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">SelectorCV</span><span class="p">(</span><span class="n">sequences</span><span class="p">,</span> <span class="n">Xlengths</span><span class="p">,</span> <span class="n">word</span><span class="p">,</span> <span class="n">min_n_components</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">max_n_components</span><span class="o">=</span><span class="mi">15</span><span class="p">,</span> <span class="n">random_state</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span><span class="o">.</span><span class="n">select</span><span class="p">()</span>
<span class="n">end</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span><span class="o">-</span><span class="n">start</span>
<span class="k">if</span> <span class="n">model</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">Training complete for </span><span class="si">{}</span><span class="s2"> with </span><span class="si">{}</span><span class="s2"> states with time </span><span class="si">{}</span><span class="s2"> seconds"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="n">model</span><span class="o">.</span><span class="n">n_components</span><span class="p">,</span> <span class="n">end</span><span class="p">))</span>
<span class="k">else</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">Training failed for </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">word</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Features: grnd-rx, grnd-ry, grnd-lx, grnd-ly
Training complete for FISH with 11 states with time 0.30938261200208217 seconds
Training complete for BOOK with 2 states with time 1.6760307389777154 seconds
Training complete for VEGETABLE with 15 states with time 0.763069333974272 seconds
Training complete for FUTURE with 2 states with time 1.6664176819613203 seconds
Training complete for JOHN with 11 states with time 14.59075157402549 seconds
Features: norm-rx, norm-ry, norm-lx, norm-ly
Training complete for FISH with 11 states with time 0.3079779759282246 seconds
Training complete for BOOK with 2 states with time 1.488951308070682 seconds
Training complete for VEGETABLE with 14 states with time 0.7576258550398052 seconds
Training complete for FUTURE with 2 states with time 1.5025653450284153 seconds
Training complete for JOHN with 11 states with time 18.94647005398292 seconds
Features: delta-rx, delta-ry, delta-lx, delta-ly
Training complete for FISH with 11 states with time 0.3112332579912618 seconds
Training complete for BOOK with 2 states with time 1.5842329730512574 seconds
Training complete for VEGETABLE with 14 states with time 0.9587754799285904 seconds
Training complete for FUTURE with 2 states with time 1.783463531988673 seconds
Training complete for JOHN with 10 states with time 18.934746194980107 seconds
Features: polar-rr, polar-rtheta, polar-lr, polar-ltheta
Training complete for FISH with 11 states with time 0.31231858395040035 seconds
Training complete for BOOK with 2 states with time 1.6640070389257744 seconds
Training complete for VEGETABLE with 15 states with time 0.81697547796648 seconds
Training complete for FUTURE with 2 states with time 1.5941970540443435 seconds
Training complete for JOHN with 11 states with time 17.190742827951908 seconds
Features: norm-polar-rr, norm-polar-rtheta, norm-polar-lr, norm-polar-ltheta
Training complete for FISH with 11 states with time 0.3377433599671349 seconds
Training complete for BOOK with 2 states with time 1.649651617044583 seconds
Training complete for VEGETABLE with 13 states with time 0.8082856889814138 seconds
Training complete for FUTURE with 2 states with time 1.635587444063276 seconds
Training complete for JOHN with 12 states with time 18.422505868016742 seconds
Features: delta-norm-polar-rr, delta-norm-polar-rtheta, delta-norm-polar-lr, delta-norm-polar-ltheta
Training complete for FISH with 11 states with time 0.3474839898990467 seconds
Training complete for BOOK with 2 states with time 1.9100318970158696 seconds
Training complete for VEGETABLE with 14 states with time 0.9301408700412139 seconds
Training complete for FUTURE with 2 states with time 1.8428528779186308 seconds
Training complete for JOHN with 12 states with time 18.21182681794744 seconds
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [21]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># DONE: Implement SelectorBIC in module my_model_selectors.py</span>
<span class="kn">from</span> <span class="nn">my_model_selectors</span> <span class="k">import</span> <span class="n">SelectorBIC</span>
<span class="c1"># Experiment here with different feature sets defined in part 1</span>
<span class="k">for</span> <span class="n">features</span> <span class="ow">in</span> <span class="n">feature_sets</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Features:"</span><span class="p">,</span> <span class="s2">", "</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">features</span><span class="p">))</span>
<span class="n">training</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">build_training</span><span class="p">(</span><span class="n">features_ground</span><span class="p">)</span>
<span class="n">sequences</span> <span class="o">=</span> <span class="n">training</span><span class="o">.</span><span class="n">get_all_sequences</span><span class="p">()</span>
<span class="n">Xlengths</span> <span class="o">=</span> <span class="n">training</span><span class="o">.</span><span class="n">get_all_Xlengths</span><span class="p">()</span>
<span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">words_to_train</span><span class="p">:</span>
<span class="n">start</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">SelectorBIC</span><span class="p">(</span><span class="n">sequences</span><span class="p">,</span> <span class="n">Xlengths</span><span class="p">,</span> <span class="n">word</span><span class="p">,</span>
<span class="n">min_n_components</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">max_n_components</span><span class="o">=</span><span class="mi">15</span><span class="p">,</span> <span class="n">random_state</span> <span class="o">=</span> <span class="mi">14</span><span class="p">)</span><span class="o">.</span><span class="n">select</span><span class="p">()</span>
<span class="n">end</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span><span class="o">-</span><span class="n">start</span>
<span class="k">if</span> <span class="n">model</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">Training complete for </span><span class="si">{}</span><span class="s2"> with </span><span class="si">{}</span><span class="s2"> states with time </span><span class="si">{}</span><span class="s2"> seconds"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="n">model</span><span class="o">.</span><span class="n">n_components</span><span class="p">,</span> <span class="n">end</span><span class="p">))</span>
<span class="k">else</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">Training failed for </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">word</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Features: grnd-rx, grnd-ry, grnd-lx, grnd-ly
Training complete for FISH with 3 states with time 0.3057803069241345 seconds
Training complete for BOOK with 3 states with time 1.9818233950063586 seconds
Training complete for VEGETABLE with 3 states with time 0.7051587359746918 seconds
Training complete for FUTURE with 3 states with time 2.0583770239027217 seconds
Training complete for JOHN with 3 states with time 18.4661514069885 seconds
Features: norm-rx, norm-ry, norm-lx, norm-ly
Training complete for FISH with 3 states with time 0.35854105500038713 seconds
Training complete for BOOK with 3 states with time 2.05461867491249 seconds
Training complete for VEGETABLE with 3 states with time 1.0314897170756012 seconds
Training complete for FUTURE with 3 states with time 2.5589805219788104 seconds
Training complete for JOHN with 3 states with time 19.139441056991927 seconds
Features: delta-rx, delta-ry, delta-lx, delta-ly
Training complete for FISH with 3 states with time 0.32778833899647 seconds
Training complete for BOOK with 3 states with time 2.059590006014332 seconds
Training complete for VEGETABLE with 3 states with time 0.8182098970282823 seconds
Training complete for FUTURE with 3 states with time 2.262031613034196 seconds
Training complete for JOHN with 3 states with time 19.15304817899596 seconds
Features: polar-rr, polar-rtheta, polar-lr, polar-ltheta
Training complete for FISH with 3 states with time 0.34682155796326697 seconds
Training complete for BOOK with 3 states with time 2.167186788050458 seconds
Training complete for VEGETABLE with 3 states with time 0.7713171700015664 seconds
Training complete for FUTURE with 3 states with time 2.2929844049504027 seconds
Training complete for JOHN with 3 states with time 19.090151929995045 seconds
Features: norm-polar-rr, norm-polar-rtheta, norm-polar-lr, norm-polar-ltheta
Training complete for FISH with 3 states with time 0.3672055930364877 seconds
Training complete for BOOK with 3 states with time 2.1501747319707647 seconds
Training complete for VEGETABLE with 3 states with time 0.7522715439554304 seconds
Training complete for FUTURE with 3 states with time 2.2637577010318637 seconds
Training complete for JOHN with 3 states with time 18.990468845004216 seconds
Features: delta-norm-polar-rr, delta-norm-polar-rtheta, delta-norm-polar-lr, delta-norm-polar-ltheta
Training complete for FISH with 3 states with time 0.36364465998485684 seconds
Training complete for BOOK with 3 states with time 2.383899515029043 seconds
Training complete for VEGETABLE with 3 states with time 0.7313544860808179 seconds
Training complete for FUTURE with 3 states with time 2.1871640810277313 seconds
Training complete for JOHN with 3 states with time 19.044111091061495 seconds
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [33]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># DONE: Implement SelectorDIC in module my_model_selectors.py</span>
<span class="kn">from</span> <span class="nn">my_model_selectors</span> <span class="k">import</span> <span class="n">SelectorDIC</span>
<span class="c1"># Experiment here with different feature sets defined in part 1</span>
<span class="k">for</span> <span class="n">features</span> <span class="ow">in</span> <span class="n">feature_sets</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Features:"</span><span class="p">,</span> <span class="s2">", "</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">features</span><span class="p">))</span>
<span class="n">training</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">build_training</span><span class="p">(</span><span class="n">features_ground</span><span class="p">)</span>
<span class="n">sequences</span> <span class="o">=</span> <span class="n">training</span><span class="o">.</span><span class="n">get_all_sequences</span><span class="p">()</span>
<span class="n">Xlengths</span> <span class="o">=</span> <span class="n">training</span><span class="o">.</span><span class="n">get_all_Xlengths</span><span class="p">()</span>
<span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">words_to_train</span><span class="p">:</span>
<span class="n">start</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">SelectorDIC</span><span class="p">(</span><span class="n">sequences</span><span class="p">,</span> <span class="n">Xlengths</span><span class="p">,</span> <span class="n">word</span><span class="p">,</span>
<span class="n">min_n_components</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">max_n_components</span><span class="o">=</span><span class="mi">15</span><span class="p">,</span> <span class="n">random_state</span> <span class="o">=</span> <span class="mi">14</span><span class="p">)</span><span class="o">.</span><span class="n">select</span><span class="p">()</span>
<span class="n">end</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">default_timer</span><span class="p">()</span><span class="o">-</span><span class="n">start</span>
<span class="k">if</span> <span class="n">model</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">Training complete for </span><span class="si">{}</span><span class="s2"> with </span><span class="si">{}</span><span class="s2"> states with time </span><span class="si">{}</span><span class="s2"> seconds"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">word</span><span class="p">,</span> <span class="n">model</span><span class="o">.</span><span class="n">n_components</span><span class="p">,</span> <span class="n">end</span><span class="p">))</span>
<span class="k">else</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">Training failed for </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">word</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Features: grnd-rx, grnd-ry, grnd-lx, grnd-ly
Training complete for FISH with 3 states with time 0.7577526069944724 seconds
Training complete for BOOK with 15 states with time 3.5864144739462063 seconds
Training complete for VEGETABLE with 15 states with time 2.865610480075702 seconds
Training complete for FUTURE with 15 states with time 3.7713247389765456 seconds
Training complete for JOHN with 15 states with time 19.292432175017893 seconds
Features: norm-rx, norm-ry, norm-lx, norm-ly
Training complete for FISH with 3 states with time 0.7737183739664033 seconds
Training complete for BOOK with 15 states with time 3.474299839930609 seconds
Training complete for VEGETABLE with 15 states with time 2.8652542090276256 seconds
Training complete for FUTURE with 15 states with time 3.654713768977672 seconds
Training complete for JOHN with 15 states with time 19.127161617041565 seconds
Features: delta-rx, delta-ry, delta-lx, delta-ly
Training complete for FISH with 3 states with time 0.7548882580595091 seconds
Training complete for BOOK with 15 states with time 3.777210394036956 seconds
Training complete for VEGETABLE with 15 states with time 2.983916159020737 seconds
Training complete for FUTURE with 15 states with time 3.824597480939701 seconds
Training complete for JOHN with 15 states with time 19.2216105889529 seconds
Features: polar-rr, polar-rtheta, polar-lr, polar-ltheta
Training complete for FISH with 3 states with time 0.7304423790192232 seconds
Training complete for BOOK with 15 states with time 3.5829816929763183 seconds
Training complete for VEGETABLE with 15 states with time 2.995281042996794 seconds
Training complete for FUTURE with 15 states with time 3.8428223150549456 seconds
Training complete for JOHN with 15 states with time 19.300517566967756 seconds
Features: norm-polar-rr, norm-polar-rtheta, norm-polar-lr, norm-polar-ltheta
Training complete for FISH with 3 states with time 0.7508241380564868 seconds
Training complete for BOOK with 15 states with time 3.5805505430325866 seconds
Training complete for VEGETABLE with 15 states with time 3.291483458946459 seconds
Training complete for FUTURE with 15 states with time 4.240771924960427 seconds
Training complete for JOHN with 15 states with time 20.988245385000482 seconds
Features: delta-norm-polar-rr, delta-norm-polar-rtheta, delta-norm-polar-lr, delta-norm-polar-ltheta
Training complete for FISH with 3 states with time 0.7367886040592566 seconds
Training complete for BOOK with 15 states with time 3.856764534022659 seconds
Training complete for VEGETABLE with 15 states with time 3.659647807944566 seconds
Training complete for FUTURE with 15 states with time 4.613638506969437 seconds
Training complete for JOHN with 15 states with time 21.025277429027483 seconds
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><strong>Question 2:</strong> Compare and contrast the possible advantages and disadvantages of the various model selectors implemented.</p>
<p><strong>Answer 2:</strong></p>
<blockquote><p>Comparing the training time for our sample runs, CV was the fastest one, whereas DIC was the slowest one.</p>
<p>All of the selectors use GaussianHMM as the model algorithm.</p>
<p>CV utilizes KFold cross-validation (with a size split of 2) to split the word sequences and eventually calculate the average scores for all split runs. The average score is then used to evaluate the best score/model. This technique should provide certain level of protection against overfitting. One of the disadvantages is that the models needs to be evaluated K times over the sequence splits. Although the performance hit in our test runs do not reflect this drawback, it should be more apparent for larger sequences. The other 2 selectors don’t suffer from this disadvantage.</p>
<p>BIC utilizes a score function that depends on the number of “free” parameters that can be hard to calculate, <a href="https://discussions.udacity.com/t/number-of-parameters-bic-calculation/233235">as described in this post</a>. The number of parameters can vary, and it is somehow arbitrary and influenced by one’s interpretation of the problem space. Under this algorithm, the model with <a href="https://en.wikipedia.org/wiki/Bayesian_information_criterion">the lowest BIC is preferred</a>. In simple terms, this algorithm is based on “the likelihood” function, which takes into account the different parameters of the given model data. More parameters increases the likelihood; yet, it can also lead to overfitting, which the algorithm accounts for by penalizing a larger number of parameters.</p>
<p>DIC utilizes a score function that compares the probability of the word in question versus the probability of other words (different than the one in question). This algorithm penalizes models that produce ambiguous outcomes, while it favors models that show a higher level of confidence when predicting the intended word during the training phase.</p>
</blockquote>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><a id='part2_test'></a></p>
<h3 id="Model-Selector-Unit-Testing">Model Selector Unit Testing<a class="anchor-link" href="#Model-Selector-Unit-Testing">¶</a></h3><p>Run the following unit tests as a sanity check on the implemented model selectors. The test simply looks for valid interfaces but is not exhaustive. However, the project should not be submitted if these tests don't pass.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [22]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">asl_test_model_selectors</span> <span class="k">import</span> <span class="n">TestSelectors</span>
<span class="n">suite</span> <span class="o">=</span> <span class="n">unittest</span><span class="o">.</span><span class="n">TestLoader</span><span class="p">()</span><span class="o">.</span><span class="n">loadTestsFromModule</span><span class="p">(</span><span class="n">TestSelectors</span><span class="p">())</span>
<span class="n">unittest</span><span class="o">.</span><span class="n">TextTestRunner</span><span class="p">()</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">suite</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stderr output_text">
<pre>....
----------------------------------------------------------------------
Ran 4 tests in 24.578s
OK
</pre>
</div>
</div>
<div class="output_area">
<div class="prompt output_prompt">Out[22]:</div>
<div class="output_text output_subarea output_execute_result">
<pre><unittest.runner.TextTestResult run=4 errors=0 failures=0></pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><a id='part3_tutorial'></a></p>
<h2 id="PART-3:-Recognizer">PART 3: Recognizer<a class="anchor-link" href="#PART-3:-Recognizer">¶</a></h2><p>The objective of this section is to "put it all together". Using the four feature sets created and the three model selectors, you will experiment with the models and present your results. Instead of training only five specific words as in the previous section, train the entire set with a feature set and model selector strategy.</p>
<h3 id="Recognizer-Tutorial">Recognizer Tutorial<a class="anchor-link" href="#Recognizer-Tutorial">¶</a></h3><h5 id="Train-the-full-training-set">Train the full training set<a class="anchor-link" href="#Train-the-full-training-set">¶</a></h5><p>The following example trains the entire set with the example <code>features_ground</code> and <code>SelectorConstant</code> features and model selector. Use this pattern for you experimentation and final submission cells.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [23]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># autoreload for automatically reloading changes made in my_model_selectors and my_recognizer</span>
<span class="o">%</span><span class="k">load_ext</span> autoreload
<span class="o">%</span><span class="k">autoreload</span> 2
<span class="kn">from</span> <span class="nn">my_model_selectors</span> <span class="k">import</span> <span class="n">SelectorConstant</span>
<span class="k">def</span> <span class="nf">train_all_words</span><span class="p">(</span><span class="n">features</span><span class="p">,</span> <span class="n">model_selector</span><span class="p">):</span>
<span class="n">training</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">build_training</span><span class="p">(</span><span class="n">features</span><span class="p">)</span> <span class="c1"># Experiment here with different feature sets defined in part 1</span>
<span class="n">sequences</span> <span class="o">=</span> <span class="n">training</span><span class="o">.</span><span class="n">get_all_sequences</span><span class="p">()</span>
<span class="n">Xlengths</span> <span class="o">=</span> <span class="n">training</span><span class="o">.</span><span class="n">get_all_Xlengths</span><span class="p">()</span>
<span class="n">model_dict</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">training</span><span class="o">.</span><span class="n">words</span><span class="p">:</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">model_selector</span><span class="p">(</span><span class="n">sequences</span><span class="p">,</span> <span class="n">Xlengths</span><span class="p">,</span> <span class="n">word</span><span class="p">,</span>
<span class="n">n_constant</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span><span class="o">.</span><span class="n">select</span><span class="p">()</span>
<span class="n">model_dict</span><span class="p">[</span><span class="n">word</span><span class="p">]</span><span class="o">=</span><span class="n">model</span>
<span class="k">return</span> <span class="n">model_dict</span>
<span class="n">models</span> <span class="o">=</span> <span class="n">train_all_words</span><span class="p">(</span><span class="n">features_ground</span><span class="p">,</span> <span class="n">SelectorConstant</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Number of word models returned = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">models</span><span class="p">)))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of word models returned = 112
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="Load-the-test-set">Load the test set<a class="anchor-link" href="#Load-the-test-set">¶</a></h5><p>The <code>build_test</code> method in <code>ASLdb</code> is similar to the <code>build_training</code> method already presented, but there are a few differences:</p>
<ul>
<li>the object is type <code>SinglesData</code> </li>
<li>the internal dictionary keys are the index of the test word rather than the word itself</li>
<li>the getter methods are <code>get_all_sequences</code>, <code>get_all_Xlengths</code>, <code>get_item_sequences</code> and <code>get_item_Xlengths</code></li>
</ul>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [24]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">test_set</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">build_test</span><span class="p">(</span><span class="n">features_ground</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Number of test set items: </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">test_set</span><span class="o">.</span><span class="n">num_items</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Number of test set sentences: </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">test_set</span><span class="o">.</span><span class="n">sentences_index</span><span class="p">)))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Number of test set items: 178
Number of test set sentences: 40
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><a id='part3_submission'></a></p>
<h3 id="Recognizer-Implementation-Submission">Recognizer Implementation Submission<a class="anchor-link" href="#Recognizer-Implementation-Submission">¶</a></h3><p>For the final project submission, students must implement a recognizer following guidance in the <code>my_recognizer.py</code> module. Experiment with the four feature sets and the three model selection methods (that's 12 possible combinations). You can add and remove cells for experimentation or run the recognizers locally in some other way during your experiments, but retain the results for your discussion. For submission, you will provide code cells of <strong>only three</strong> interesting combinations for your discussion (see questions below). At least one of these should produce a word error rate of less than 60%, i.e. WER < 0.60 .</p>
<p><strong>Tip:</strong> The hmmlearn library may not be able to train or score all models. Implement try/except contructs as necessary to eliminate non-viable models from consideration.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [35]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># DONE implement the recognize method in my_recognizer</span>
<span class="kn">from</span> <span class="nn">my_recognizer</span> <span class="k">import</span> <span class="n">recognize</span>
<span class="kn">from</span> <span class="nn">asl_utils</span> <span class="k">import</span> <span class="n">show_errors</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [37]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># Choose a feature set and model selector</span>
<span class="n">features</span> <span class="o">=</span> <span class="n">features_ground</span> <span class="c1"># change as needed</span>
<span class="n">model_selector</span> <span class="o">=</span> <span class="n">SelectorConstant</span> <span class="c1"># change as needed</span>
<span class="c1"># Recognize the test set and display the result with the show_errors method</span>
<span class="n">models</span> <span class="o">=</span> <span class="n">train_all_words</span><span class="p">(</span><span class="n">features</span><span class="p">,</span> <span class="n">model_selector</span><span class="p">)</span>
<span class="n">test_set</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">build_test</span><span class="p">(</span><span class="n">features</span><span class="p">)</span>
<span class="n">probabilities</span><span class="p">,</span> <span class="n">guesses</span> <span class="o">=</span> <span class="n">recognize</span><span class="p">(</span><span class="n">models</span><span class="p">,</span> <span class="n">test_set</span><span class="p">)</span>
<span class="n">show_errors</span><span class="p">(</span><span class="n">guesses</span><span class="p">,</span> <span class="n">test_set</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>
**** WER = 0.6685393258426966
Total correct: 59 out of 178
Video Recognized Correct
=====================================================================================================
2: *GO WRITE *ARRIVE JOHN WRITE HOMEWORK
7: *SOMETHING-ONE *GO1 *IX CAN JOHN CAN GO CAN
12: JOHN *HAVE *WHAT CAN JOHN CAN GO CAN
21: JOHN *HOMEWORK *NEW *PREFER *CAR *CAR *FUTURE *EAT JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: *FRANK *TELL *LOVE *TELL *LOVE JOHN LIKE IX IX IX
28: *FRANK *TELL *LOVE *TELL *LOVE JOHN LIKE IX IX IX
30: *SHOULD LIKE *GO *GO *GO JOHN LIKE IX IX IX
36: *VISIT VEGETABLE *YESTERDAY *GIVE *MARY *MARY MARY VEGETABLE KNOW IX LIKE CORN1
40: *SUE *GIVE *CORN *VEGETABLE *GO JOHN IX THINK MARY LOVE
43: *FRANK *GO BUY HOUSE JOHN MUST BUY HOUSE
50: *FRANK *SEE BUY CAR *SOMETHING-ONE FUTURE JOHN BUY CAR SHOULD
54: JOHN SHOULD *WHO BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *MARY *VISIT VISIT *VISIT JOHN DECIDE VISIT MARY
67: *LIKE FUTURE NOT BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *FINISH VISIT MARY JOHN WILL VISIT MARY
74: *IX *VISIT *GO *GO JOHN NOT VISIT MARY
77: *JOHN BLAME *LOVE ANN BLAME MARY
84: *LOVE *ARRIVE *HOMEWORK BOOK IX-1P FIND SOMETHING-ONE BOOK
89: *GIVE *GIVE GIVE *IX IX *ARRIVE *BOOK JOHN IX GIVE MAN IX NEW COAT
90: *SOMETHING-ONE *SOMETHING-ONE IX *IX WOMAN *COAT JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: *FRANK GIVE *WOMAN *WOMAN WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW CAR BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: *FRANK *VEGETABLE JOHN LEG
107: *SHOULD *IX FRIEND *GO *JANA JOHN POSS FRIEND HAVE CANDY
108: *GIVE *LOVE WOMAN ARRIVE
113: IX CAR *CAR *IX *IX IX CAR BLUE SUE BUY
119: *PREFER *BUY1 IX *BLAME *IX SUE BUY IX CAR BLUE
122: JOHN *GIVE1 *COAT JOHN READ BOOK
139: *SHOULD *BUY1 *CAR *BLAME BOOK JOHN BUY WHAT YESTERDAY BOOK
142: *FRANK *STUDENT YESTERDAY *TEACHER BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE *MARY WHO LOVE JOHN WHO
167: *MARY IX *VISIT *WOMAN *LOVE JOHN IX SAY LOVE MARY
171: *VISIT *VISIT BLAME JOHN MARY BLAME
174: *CAN *GIVE3 GIVE1 *APPLE *WHAT PEOPLE GROUP GIVE1 JANA TOY
181: *BLAME ARRIVE JOHN ARRIVE
184: *GIVE1 BOY *GIVE1 TEACHER APPLE ALL BOY GIVE TEACHER APPLE
189: *JANA *SOMETHING-ONE *YESTERDAY *WHAT JOHN GIVE GIRL BOX
193: JOHN *SOMETHING-ONE *YESTERDAY BOX JOHN GIVE GIRL BOX
199: *LOVE CHOCOLATE WHO LIKE CHOCOLATE WHO
201: JOHN *GIVE *GIVE *LOVE *ARRIVE HOUSE JOHN TELL MARY IX-1P BUY HOUSE
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="Multiple-feature-sets-/-model-selectors">Multiple feature sets / model selectors<a class="anchor-link" href="#Multiple-feature-sets-/-model-selectors">¶</a></h4>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [49]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">itertools</span>
<span class="k">for</span> <span class="n">features</span><span class="p">,</span> <span class="n">model_selector</span> <span class="ow">in</span> <span class="n">itertools</span><span class="o">.</span><span class="n">product</span><span class="p">(</span><span class="n">feature_sets</span><span class="p">,</span> <span class="p">[</span><span class="n">SelectorCV</span><span class="p">,</span> <span class="n">SelectorBIC</span><span class="p">,</span> <span class="n">SelectorDIC</span><span class="p">]):</span>
<span class="c1"># Choose a feature set and model selector</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Features:"</span><span class="p">,</span> <span class="s2">", "</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">features</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Selector:"</span><span class="p">,</span> <span class="n">model_selector</span><span class="o">.</span><span class="vm">__name__</span><span class="p">)</span>
<span class="c1"># Recognize the test set and display the result with the show_errors method</span>
<span class="n">models</span> <span class="o">=</span> <span class="n">train_all_words</span><span class="p">(</span><span class="n">features</span><span class="p">,</span> <span class="n">model_selector</span><span class="p">)</span>
<span class="n">test_set</span> <span class="o">=</span> <span class="n">asl</span><span class="o">.</span><span class="n">build_test</span><span class="p">(</span><span class="n">features</span><span class="p">)</span>
<span class="n">probabilities</span><span class="p">,</span> <span class="n">guesses</span> <span class="o">=</span> <span class="n">recognize</span><span class="p">(</span><span class="n">models</span><span class="p">,</span> <span class="n">test_set</span><span class="p">)</span>
<span class="n">show_errors</span><span class="p">(</span><span class="n">guesses</span><span class="p">,</span> <span class="n">test_set</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">,</span> <span class="s2">"*************************************"</span><span class="p">,</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Features: grnd-rx, grnd-ry, grnd-lx, grnd-ly
Selector: SelectorCV
**** WER = 0.5955056179775281
Total correct: 72 out of 178
Video Recognized Correct
=====================================================================================================
2: JOHN WRITE HOMEWORK JOHN WRITE HOMEWORK
7: JOHN CAN GO CAN JOHN CAN GO CAN
12: *IX *CAR *CAN CAN JOHN CAN GO CAN
21: JOHN *HOMEWORK *JOHN *FUTURE *CAR *CAR *VISIT *WHO JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN *IX *LOVE *TELL IX JOHN LIKE IX IX IX
28: JOHN *TELL IX IX *LOVE JOHN LIKE IX IX IX
30: JOHN LIKE IX IX *GO JOHN LIKE IX IX IX
36: MARY VEGETABLE *GIVE *GO *IX *IX MARY VEGETABLE KNOW IX LIKE CORN1
40: JOHN *GIVE *JOHN *JOHN *GO JOHN IX THINK MARY LOVE
43: JOHN *SHOULD BUY HOUSE JOHN MUST BUY HOUSE
50: *JOHN *FRANK BUY CAR *SOMETHING-ONE FUTURE JOHN BUY CAR SHOULD
54: JOHN SHOULD NOT BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *IX *VISIT VISIT *IX JOHN DECIDE VISIT MARY
67: JOHN *POSS *WHO BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *FINISH *GO MARY JOHN WILL VISIT MARY
74: *IX *VISIT *MARY *GO JOHN NOT VISIT MARY
77: *JOHN BLAME MARY ANN BLAME MARY
84: *LOVE *ARRIVE *HOMEWORK BOOK IX-1P FIND SOMETHING-ONE BOOK
89: *MARY *POSS GIVE *SOMETHING-ONE *SOMETHING-ONE *ARRIVE *BOOK JOHN IX GIVE MAN IX NEW COAT
90: JOHN *SOMETHING-ONE *SOMETHING-ONE SOMETHING-ONE WOMAN *HERE JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN GIVE *SOMETHING-ONE *WOMAN *GIVE1 BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW CAR *BOOK POSS NEW CAR BREAK-DOWN
105: JOHN *FRANK JOHN LEG
107: JOHN *MARY FRIEND *GO *SHOOT JOHN POSS FRIEND HAVE CANDY
108: *MARY *LOVE WOMAN ARRIVE
113: *MARY *CAN *GIVE SUE *BOX IX CAR BLUE SUE BUY
119: *VEGETABLE *LOVE *GO *CAN *MARY SUE BUY IX CAR BLUE
122: JOHN *HOUSE BOOK JOHN READ BOOK
139: JOHN *BUY1 *CAN YESTERDAY *ARRIVE JOHN BUY WHAT YESTERDAY BOOK
142: JOHN *NEW *FUTURE *CAR BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE *MARY WHO LOVE JOHN WHO
167: JOHN *VISIT *JANA *WOMAN *GO JOHN IX SAY LOVE MARY
171: *MARY *VISIT *MARY JOHN MARY BLAME
174: *CAN *NEW GIVE1 *GO *CAN PEOPLE GROUP GIVE1 JANA TOY
181: *YESTERDAY *SOMETHING-ONE JOHN ARRIVE
184: *SOMETHING-ONE BOY *HOUSE TEACHER *GO ALL BOY GIVE TEACHER APPLE
189: JOHN *VISIT *VISIT *CAN JOHN GIVE GIRL BOX
193: *MARY *GIVE1 *VISIT BOX JOHN GIVE GIRL BOX
199: *LOVE CHOCOLATE *TELL LIKE CHOCOLATE WHO
201: JOHN *SHOULD *GIVE *JOHN BUY HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: grnd-rx, grnd-ry, grnd-lx, grnd-ly
Selector: SelectorBIC
**** WER = 0.6685393258426966
Total correct: 59 out of 178
Video Recognized Correct
=====================================================================================================
2: *GO WRITE *ARRIVE JOHN WRITE HOMEWORK
7: *SOMETHING-ONE *GO1 *IX CAN JOHN CAN GO CAN
12: JOHN *HAVE *WHAT CAN JOHN CAN GO CAN
21: JOHN *HOMEWORK *NEW *PREFER *CAR *CAR *FUTURE *EAT JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: *FRANK *TELL *LOVE *TELL *LOVE JOHN LIKE IX IX IX
28: *FRANK *TELL *LOVE *TELL *LOVE JOHN LIKE IX IX IX
30: *SHOULD LIKE *GO *GO *GO JOHN LIKE IX IX IX
36: *VISIT VEGETABLE *YESTERDAY *GIVE *MARY *MARY MARY VEGETABLE KNOW IX LIKE CORN1
40: *SUE *GIVE *CORN *VEGETABLE *GO JOHN IX THINK MARY LOVE
43: *FRANK *GO BUY HOUSE JOHN MUST BUY HOUSE
50: *FRANK *SEE BUY CAR *SOMETHING-ONE FUTURE JOHN BUY CAR SHOULD
54: JOHN SHOULD *WHO BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *MARY *VISIT VISIT *VISIT JOHN DECIDE VISIT MARY
67: *LIKE FUTURE NOT BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *FINISH VISIT MARY JOHN WILL VISIT MARY
74: *IX *VISIT *GO *GO JOHN NOT VISIT MARY
77: *JOHN BLAME *LOVE ANN BLAME MARY
84: *LOVE *ARRIVE *HOMEWORK BOOK IX-1P FIND SOMETHING-ONE BOOK
89: *GIVE *GIVE GIVE *IX IX *ARRIVE *BOOK JOHN IX GIVE MAN IX NEW COAT
90: *SOMETHING-ONE *SOMETHING-ONE IX *IX WOMAN *COAT JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: *FRANK GIVE *WOMAN *WOMAN WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW CAR BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: *FRANK *VEGETABLE JOHN LEG
107: *SHOULD *IX FRIEND *GO *JANA JOHN POSS FRIEND HAVE CANDY
108: *GIVE *LOVE WOMAN ARRIVE
113: IX CAR *CAR *IX *IX IX CAR BLUE SUE BUY
119: *PREFER *BUY1 IX *BLAME *IX SUE BUY IX CAR BLUE
122: JOHN *GIVE1 *COAT JOHN READ BOOK
139: *SHOULD *BUY1 *CAR *BLAME BOOK JOHN BUY WHAT YESTERDAY BOOK
142: *FRANK *STUDENT YESTERDAY *TEACHER BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE *MARY WHO LOVE JOHN WHO
167: *MARY IX *VISIT *WOMAN *LOVE JOHN IX SAY LOVE MARY
171: *VISIT *VISIT BLAME JOHN MARY BLAME
174: *CAN *GIVE3 GIVE1 *APPLE *WHAT PEOPLE GROUP GIVE1 JANA TOY
181: *BLAME ARRIVE JOHN ARRIVE
184: *GIVE1 BOY *GIVE1 TEACHER APPLE ALL BOY GIVE TEACHER APPLE
189: *JANA *SOMETHING-ONE *YESTERDAY *WHAT JOHN GIVE GIRL BOX
193: JOHN *SOMETHING-ONE *YESTERDAY BOX JOHN GIVE GIRL BOX
199: *LOVE CHOCOLATE WHO LIKE CHOCOLATE WHO
201: JOHN *GIVE *GIVE *LOVE *ARRIVE HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: grnd-rx, grnd-ry, grnd-lx, grnd-ly
Selector: SelectorDIC
**** WER = 0.5730337078651685
Total correct: 76 out of 178
Video Recognized Correct
=====================================================================================================
2: JOHN *NEW *GIVE1 JOHN WRITE HOMEWORK
7: *SOMETHING-ONE *CAR *ARRIVE *ARRIVE JOHN CAN GO CAN
12: *IX *WHAT *WHAT *CAR JOHN CAN GO CAN
21: JOHN *GIVE1 *JOHN *FUTURE *CAR *CAR *FUTURE *MARY JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN *IX IX *WHO IX JOHN LIKE IX IX IX
28: JOHN *WHO IX IX *LOVE JOHN LIKE IX IX IX
30: JOHN *MARY *MARY *MARY *MARY JOHN LIKE IX IX IX
36: *VISIT *VISIT *GIVE *GO *MARY *IX MARY VEGETABLE KNOW IX LIKE CORN1
40: *MARY *GO *GIVE MARY *MARY JOHN IX THINK MARY LOVE
43: JOHN *IX BUY HOUSE JOHN MUST BUY HOUSE
50: *JOHN *FUTURE *GIVE1 CAR *JOHN FUTURE JOHN BUY CAR SHOULD
54: JOHN SHOULD NOT BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *MARY *VISIT VISIT MARY JOHN DECIDE VISIT MARY
67: JOHN FUTURE *MARY BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *FINISH VISIT MARY JOHN WILL VISIT MARY
74: *IX *GO *MARY MARY JOHN NOT VISIT MARY
77: *JOHN BLAME *LOVE ANN BLAME MARY
84: *JOHN *GIVE1 *VISIT BOOK IX-1P FIND SOMETHING-ONE BOOK
89: *MARY IX *IX *IX IX *ARRIVE *BOOK JOHN IX GIVE MAN IX NEW COAT
90: JOHN *SOMETHING-ONE IX *IX *VISIT *ARRIVE JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *IX IX *IX *IX BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: *IX NEW CAR *ARRIVE POSS NEW CAR BREAK-DOWN
105: JOHN *FRANK JOHN LEG
107: JOHN *IX *HAVE *ARRIVE *JOHN JOHN POSS FRIEND HAVE CANDY
108: *IX ARRIVE WOMAN ARRIVE
113: IX CAR *IX *MARY *BOX IX CAR BLUE SUE BUY
119: *VISIT *BUY1 IX *BOX *IX SUE BUY IX CAR BLUE
122: JOHN *BUY BOOK JOHN READ BOOK
139: JOHN *BUY1 WHAT *MARY BOOK JOHN BUY WHAT YESTERDAY BOOK
142: JOHN BUY YESTERDAY WHAT BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE JOHN WHO LOVE JOHN WHO
167: JOHN *MARY *GO LOVE MARY JOHN IX SAY LOVE MARY
171: <NAME> <NAME>
174: *CAR *GIVE1 GIVE1 *YESTERDAY *WHAT PEOPLE GROUP GIVE1 JANA TOY
181: JOHN ARRIVE JOHN ARRIVE
184: *IX BOY *GIVE1 TEACHER *YESTERDAY ALL BOY GIVE TEACHER APPLE
189: JOHN *SOMETHING-ONE *VISIT BOX JOHN GIVE GIRL BOX
193: JOHN *SOMETHING-ONE *VISIT BOX JOHN GIVE GIRL BOX
199: *JOHN *ARRIVE *GO LIKE CHOCOLATE WHO
201: JOHN *MARY *LOVE *JOHN *GIVE1 HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: norm-rx, norm-ry, norm-lx, norm-ly
Selector: SelectorCV
**** WER = 0.6629213483146067
Total correct: 60 out of 178
Video Recognized Correct
=====================================================================================================
2: JOHN WRITE HOMEWORK JOHN WRITE HOMEWORK
7: JOHN *NEW GO *ARRIVE JOHN CAN GO CAN
12: JOHN CAN *GO1 CAN JOHN CAN GO CAN
21: *LIKE *NEW *HAVE *GO *BLAME *CAR *FUTURE *WRITE JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: *GO LIKE *LIKE *LIKE *GO JOHN LIKE IX IX IX
28: *ANN LIKE *ANN *LIKE *ANN JOHN LIKE IX IX IX
30: *IX-1P LIKE *LOVE *LIKE *MARY JOHN LIKE IX IX IX
36: *SHOOT *NOT *YESTERDAY *VISIT *LEAVE *LIKE MARY VEGETABLE KNOW IX LIKE CORN1
40: *SHOOT *VISIT *FUTURE1 *SHOULD LOVE JOHN IX THINK MARY LOVE
43: JOHN *JOHN BUY HOUSE JOHN MUST BUY HOUSE
50: *POSS *SEE *NEW CAR *HAVE FUTURE JOHN BUY CAR SHOULD
54: JOHN SHOULD *SHOULD *HAVE HOUSE JOHN SHOULD NOT BUY HOUSE
57: JOHN *WHO *MARY MARY JOHN DECIDE VISIT MARY
67: JOHN *SOMETHING-ONE *JOHN *ARRIVE *CAN JOHN FUTURE NOT BUY HOUSE
71: JOHN WILL VISIT MARY JOHN WILL VISIT MARY
74: JOHN *VISIT VISIT *VISIT JOHN NOT VISIT MARY
77: *JOHN BLAME MARY ANN BLAME MARY
84: *JOHN *ARRIVE *POSS *WRITE IX-1P FIND SOMETHING-ONE BOOK
89: *TELL *HAVE *SOMETHING-ONE *SOMETHING-ONE *SOMETHING-ONE NEW COAT JOHN IX GIVE MAN IX NEW COAT
90: *SELF *GIVE1 *SOMETHING-ONE *GIVE1 WOMAN *VIDEOTAPE JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *GIVE1 *WOMAN *WOMAN WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW *HOUSE BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: JOHN *POSS JOHN LEG
107: JOHN *IX *GIVE1 *LIKE *TOY1 JOHN POSS FRIEND HAVE CANDY
108: *LOVE *HOMEWORK WOMAN ARRIVE
113: IX *CAN *IX SUE *HAVE IX CAR BLUE SUE BUY
119: *WHO *BUY1 *HAVE *ARRIVE *FUTURE SUE BUY IX CAR BLUE
122: JOHN *GIVE1 BOOK JOHN READ BOOK
139: JOHN *BUY1 *CAR YESTERDAY *NEW JOHN BUY WHAT YESTERDAY BOOK
142: JOHN *ARRIVE *GO WHAT *COAT JOHN BUY YESTERDAY WHAT BOOK
158: *GIVE1 *MARY *CORN LOVE JOHN WHO
167: JOHN *VISIT *SAY-1P *MARY *LOVE JOHN IX SAY LOVE MARY
171: *JANA *JOHN BLAME JOHN MARY BLAME
174: *NEW *GIVE1 GIVE1 *WHO *VISIT PEOPLE GROUP GIVE1 JANA TOY
181: *SOMETHING-ONE *GIVE1 JOHN ARRIVE
184: *IX BOY *GIVE1 TEACHER *GIVE ALL BOY GIVE TEACHER APPLE
189: *JANA *GIVE1 *FINISH *ARRIVE JOHN GIVE GIRL BOX
193: JOHN *YESTERDAY *FINISH BOX JOHN GIVE GIRL BOX
199: *JOHN CHOCOLATE *TELL LIKE CHOCOLATE WHO
201: JOHN *SHOULD *WOMAN *WOMAN BUY HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: norm-rx, norm-ry, norm-lx, norm-ly
Selector: SelectorBIC
**** WER = 0.6235955056179775
Total correct: 67 out of 178
Video Recognized Correct
=====================================================================================================
2: *MARY WRITE *ARRIVE JOHN WRITE HOMEWORK
7: JOHN *NEW *JOHN CAN JOHN CAN GO CAN
12: *SHOULD *HAVE *GO1 CAN JOHN CAN GO CAN
21: *LIKE *NEW *HAVE *IX-1P *CAR *BLAME *CHICKEN *WRITE JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: *IX LIKE *LIKE *LIKE IX JOHN LIKE IX IX IX
28: *ANN LIKE *ANN *LIKE *ANN JOHN LIKE IX IX IX
30: *SHOOT LIKE *LOVE *LIKE *MARY JOHN LIKE IX IX IX
36: *LEAVE *NOT *YESTERDAY *VISIT LIKE *JOHN MARY VEGETABLE KNOW IX LIKE CORN1
40: JOHN *LEAVE *FUTURE1 *VEGETABLE LOVE JOHN IX THINK MARY LOVE
43: JOHN *SHOULD BUY HOUSE JOHN MUST BUY HOUSE
50: *FRANK *SEE *ARRIVE CAR *CAR FUTURE JOHN BUY CAR SHOULD
54: JOHN SHOULD *FUTURE *STUDENT HOUSE JOHN SHOULD NOT BUY HOUSE
57: *MARY *MARY *MARY MARY JOHN DECIDE VISIT MARY
67: *IX-1P FUTURE *JOHN *ARRIVE HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN WILL VISIT MARY JOHN WILL VISIT MARY
74: *WOMAN *VISIT VISIT *FRANK JOHN NOT VISIT MARY
77: *IX BLAME MARY ANN BLAME MARY
84: *IX *ARRIVE *NEW BOOK IX-1P FIND SOMETHING-ONE BOOK
89: *FUTURE *THROW *JOHN *JOHN *WOMAN *BOOK *BREAK-DOWN JOHN IX GIVE MAN IX NEW COAT
90: *SELF *GIVE1 IX *IX WOMAN *CHOCOLATE JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *GIVE1 IX *IX WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW CAR BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: *WHO *SEE JOHN LEG
107: *TELL *IX *BOX *LIKE *JANA JOHN POSS FRIEND HAVE CANDY
108: *LOVE *HOMEWORK WOMAN ARRIVE
113: IX CAR *IX SUE *HAVE IX CAR BLUE SUE BUY
119: *VEGETABLE *BUY1 IX CAR *GO SUE BUY IX CAR BLUE
122: JOHN *HOUSE *COAT JOHN READ BOOK
139: JOHN *BUY1 *CAR YESTERDAY BOOK JOHN BUY WHAT YESTERDAY BOOK
142: JOHN BUY YESTERDAY WHAT BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE *MARY *CORN LOVE JOHN WHO
167: JOHN *JOHN *SAY-1P LOVE MARY JOHN IX SAY LOVE MARY
171: *SHOOT *JOHN BLAME JOHN MARY BLAME
174: *NEW *GIVE1 GIVE1 *WHO *CAR PEOPLE GROUP GIVE1 JANA TOY
181: JOHN *BOX JOHN ARRIVE
184: *IX *IX *GIVE1 TEACHER APPLE ALL BOY GIVE TEACHER APPLE
189: *JANA *SEE *PREFER *ARRIVE JOHN GIVE GIRL BOX
193: JOHN *SEE *YESTERDAY BOX JOHN GIVE GIRL BOX
199: *JOHN CHOCOLATE *JOHN LIKE CHOCOLATE WHO
201: JOHN *THINK *WOMAN *WOMAN *STUDENT HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: norm-rx, norm-ry, norm-lx, norm-ly
Selector: SelectorDIC
**** WER = 0.5955056179775281
Total correct: 72 out of 178
Video Recognized Correct
=====================================================================================================
2: JOHN WRITE *ARRIVE JOHN WRITE HOMEWORK
7: *MARY *CAR GO CAN JOHN CAN GO CAN
12: JOHN *WHAT *ARRIVE CAN JOHN CAN GO CAN
21: *MARY *JOHN *JOHN *BLAME *CAR *CAR *FUTURE CHICKEN JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN LIKE IX *LIKE IX JOHN LIKE IX IX IX
28: *ANN *ANN IX *MARY IX JOHN LIKE IX IX IX
30: *IX-1P *CHOCOLATE *MARY *LOVE *LOVE JOHN LIKE IX IX IX
36: MARY *MARY *YESTERDAY *SHOOT LIKE *IX MARY VEGETABLE KNOW IX LIKE CORN1
40: *MARY *JOHN *FUTURE1 *VEGETABLE *MARY JOHN IX THINK MARY LOVE
43: JOHN *FUTURE BUY HOUSE JOHN MUST BUY HOUSE
50: *POSS *SEE *JOHN CAR *IX FUTURE JOHN BUY CAR SHOULD
54: JOHN *FUTURE *SHOULD *ARRIVE HOUSE JOHN SHOULD NOT BUY HOUSE
57: *SHOOT *IX *JOHN *VISIT JOHN DECIDE VISIT MARY
67: *MARY *IX *JOHN *ARRIVE HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *FUTURE VISIT MARY JOHN WILL VISIT MARY
74: *GO *VISIT VISIT MARY JOHN NOT VISIT MARY
77: ANN BLAME MARY ANN BLAME MARY
84: *JOHN *ARRIVE *VISIT BOOK IX-1P FIND SOMETHING-ONE BOOK
89: *MARY *POSS *IX *IX IX *ARRIVE *BREAK-DOWN JOHN IX GIVE MAN IX NEW COAT
90: *SELF *IX IX *IX WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *IX IX *IX *LOVE BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW CAR BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: JOHN *POSS JOHN LEG
107: *MARY POSS *BOX *MARY *TOY1 JOHN POSS FRIEND HAVE CANDY
108: *LOVE *JOHN WOMAN ARRIVE
113: *SHOULD CAR *IX *JOHN *BOX IX CAR BLUE SUE BUY
119: SUE *BUY1 IX *JOHN *GO SUE BUY IX CAR BLUE
122: JOHN *GIVE1 BOOK JOHN READ BOOK
139: JOHN *BUY1 *CAR *JOHN BOOK JOHN BUY WHAT YESTERDAY BOOK
142: JOHN BUY YESTERDAY WHAT BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE JOHN WHO LOVE JOHN WHO
167: JOHN IX *SAY-1P LOVE *IX JOHN IX SAY LOVE MARY
171: *MARY *JOHN BLAME JOHN MARY BLAME
174: *CAR *GIVE1 GIVE1 *YESTERDAY *CAR PEOPLE GROUP GIVE1 JANA TOY
181: JOHN *BOX JOHN ARRIVE
184: *IX BOY *GIVE1 TEACHER APPLE ALL BOY GIVE TEACHER APPLE
189: *MARY *MARY *YESTERDAY BOX JOHN GIVE GIRL BOX
193: *LEAVE *YESTERDAY *YESTERDAY BOX JOHN GIVE GIRL BOX
199: *JOHN *ARRIVE *JOHN LIKE CHOCOLATE WHO
201: JOHN *GIVE1 *IX *WOMAN *ARRIVE HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: delta-rx, delta-ry, delta-lx, delta-ly
Selector: SelectorCV
**** WER = 0.6123595505617978
Total correct: 69 out of 178
Video Recognized Correct
=====================================================================================================
2: *POSS *LOVE HOMEWORK JOHN WRITE HOMEWORK
7: JOHN *STUDENT *GIVE1 *GO JOHN CAN GO CAN
12: JOHN CAN *GO1 CAN JOHN CAN GO CAN
21: JOHN *YESTERDAY *GO1 *YESTERDAY *BUY *GO *FUTURE *JOHN JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN *MARY *LOVE IX *MARY JOHN LIKE IX IX IX
28: JOHN *MARY *MARY IX IX JOHN LIKE IX IX IX
30: JOHN *MARY IX *JOHN IX JOHN LIKE IX IX IX
36: MARY *MARY *IX IX *MARY *MARY MARY VEGETABLE KNOW IX LIKE CORN1
40: JOHN IX *JOHN MARY *MARY JOHN IX THINK MARY LOVE
43: JOHN *WHO BUY HOUSE JOHN MUST BUY HOUSE
50: *JOHN *NOT BUY CAR *MARY FUTURE JOHN BUY CAR SHOULD
54: JOHN *MARY *JOHN BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *GIVE1 *WHO *IX *IX JOHN DECIDE VISIT MARY
67: JOHN *WHO *IX BUY *FUTURE JOHN FUTURE NOT BUY HOUSE
71: JOHN *JOHN VISIT MARY JOHN WILL VISIT MARY
74: JOHN *IX *MARY MARY JOHN NOT VISIT MARY
77: *JOHN *CAR MARY ANN BLAME MARY
84: *JOHN *GO *GIVE1 *MOVIE IX-1P FIND SOMETHING-ONE BOOK
89: *IX IX *IX *IX IX *CAR COAT JOHN IX GIVE MAN IX NEW COAT
90: *MARY *JOHN *JOHN *IX WOMAN *MARY JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *MARY IX *IX WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: *JOHN NEW CAR *CAN POSS NEW CAR BREAK-DOWN
105: JOHN *MARY JOHN LEG
107: JOHN POSS FRIEND *GIVE1 *MARY JOHN POSS FRIEND HAVE CANDY
108: *WHO ARRIVE WOMAN ARRIVE
113: *JOHN *GIVE1 *MARY *IX *BUY1 IX CAR BLUE SUE BUY
119: *WHO *BUY1 *GIVE1 *GIVE1 *MARY SUE BUY IX CAR BLUE
122: JOHN *FINISH BOOK JOHN READ BOOK
139: JOHN *NEW *JOHN *MARY *MARY JOHN BUY WHAT YESTERDAY BOOK
142: JOHN BUY YESTERDAY *MARY BOOK JOHN BUY YESTERDAY WHAT BOOK
158: *NEW *MARY *MARY LOVE JOHN WHO
167: JOHN *JOHN *IX *BOOK MARY JOHN IX SAY LOVE MARY
171: *IX *WHO BLAME JOHN MARY BLAME
174: *GIVE1 *MARY GIVE1 *MARY *CAN PEOPLE GROUP GIVE1 JANA TOY
181: *WHO *NEW <NAME>IVE
184: *GIVE *JOHN *GIVE1 TEACHER *MARY ALL BOY GIVE TEACHER APPLE
189: JOHN *IX *MARY *GIVE1 JOHN GIVE GIRL BOX
193: JOHN *JOHN *IX BOX JOHN GIVE GIRL BOX
199: *JOHN *ARRIVE *MARY LIKE CHOCOLATE WHO
201: JOHN *MARY MARY *POSS BUY HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: delta-rx, delta-ry, delta-lx, delta-ly
Selector: SelectorBIC
**** WER = 0.6404494382022472
Total correct: 64 out of 178
Video Recognized Correct
=====================================================================================================
2: JOHN *JOHN HOMEWORK JOHN WRITE HOMEWORK
7: JOHN *HAVE *GIVE1 *TEACHER JOHN CAN GO CAN
12: JOHN CAN *GO1 CAN JOHN CAN GO CAN
21: *MARY *MARY *JOHN *MARY *CAR *GO *FUTURE *MARY JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN *MARY *JOHN IX *MARY JOHN LIKE IX IX IX
28: JOHN *MARY *MARY IX IX JOHN LIKE IX IX IX
30: JOHN *MARY *JOHN *JOHN IX JOHN LIKE IX IX IX
36: MARY *JOHN *JOHN IX *MARY *MARY MARY VEGETABLE KNOW IX LIKE CORN1
40: *MARY IX *MARY MARY *MARY JOHN IX THINK MARY LOVE
43: JOHN *JOHN *FINISH HOUSE JOHN MUST BUY HOUSE
50: *JOHN JOHN BUY CAR *MARY FUTURE JOHN BUY CAR SHOULD
54: JOHN *MARY *MARY BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: JOHN *JOHN *IX *JOHN JOHN DECIDE VISIT MARY
67: JOHN *JOHN *JOHN BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *JOHN VISIT MARY JOHN WILL VISIT MARY
74: JOHN *JOHN *MARY MARY JOHN NOT VISIT MARY
77: *JOHN BLAME MARY ANN BLAME MARY
84: *JOHN *GO *IX *WHAT IX-1P FIND SOMETHING-ONE BOOK
89: *GIVE1 *JOHN *IX *JOHN IX *WHAT *HOUSE JOHN IX GIVE MAN IX NEW COAT
90: *MARY *JOHN *JOHN *IX *IX *MARY JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *MARY *JOHN *JOHN WOMAN *ARRIVE JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: *JOHN NEW *WHAT BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: JOHN *MARY JOHN LEG
107: JOHN POSS FRIEND *LOVE *MARY JOHN POSS FRIEND HAVE CANDY
108: *JOHN ARRIVE WOMAN ARRIVE
113: *JOHN CAR *MARY *MARY *GIVE1 IX CAR BLUE SUE BUY
119: *JOHN *BUY1 IX CAR *IX SUE BUY IX CAR BLUE
122: JOHN *VISIT *YESTERDAY JOHN READ BOOK
139: JOHN *BUY1 WHAT *MARY *ARRIVE JOHN BUY WHAT YESTERDAY BOOK
142: JOHN BUY *MARY *MARY *YESTERDAY JOHN BUY YESTERDAY WHAT BOOK
158: *BOY *WHO *MARY LOVE JOHN WHO
167: *MARY *MARY *IX *ARRIVE *WHAT JOHN IX SAY LOVE MARY
171: JOHN *JOHN BLAME JOHN MARY BLAME
174: *GIVE1 *MARY GIVE1 *MARY *FINISH PEOPLE GROUP GIVE1 JANA TOY
181: JOHN *GIVE1 JOHN ARRIVE
184: *IX *WHO *GIVE1 *HAVE *MARY ALL BOY GIVE TEACHER APPLE
189: JOHN *IX *MARY *VISIT JOHN GIVE GIRL BOX
193: JOHN *IX *IX BOX JOHN GIVE GIRL BOX
199: *JOHN *ARRIVE *MARY LIKE CHOCOLATE WHO
201: JOHN *MARY MARY *LIKE *VISIT HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: delta-rx, delta-ry, delta-lx, delta-ly
Selector: SelectorDIC
**** WER = 0.6292134831460674
Total correct: 66 out of 178
Video Recognized Correct
=====================================================================================================
2: JOHN *GIVE1 *ARRIVE JOHN WRITE HOMEWORK
7: JOHN *GIVE1 *GIVE1 *ARRIVE JOHN CAN GO CAN
12: JOHN *BOX *JOHN CAN JOHN CAN GO CAN
21: JOHN *MARY *LOVE *MARY *HOUSE *FUTURE *FUTURE *MARY JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN *IX *JOHN IX IX JOHN LIKE IX IX IX
28: JOHN *MARY *JOHN IX *SHOULD JOHN LIKE IX IX IX
30: JOHN *IX *SHOULD *JOHN IX JOHN LIKE IX IX IX
36: *JOHN *JOHN *JOHN IX *MARY *MARY MARY VEGETABLE KNOW IX LIKE CORN1
40: *MARY IX *JOHN MARY *MARY JOHN IX THINK MARY LOVE
43: JOHN *IX BUY HOUSE JOHN MUST BUY HOUSE
50: *JOHN JOHN BUY CAR *MARY FUTURE JOHN BUY CAR SHOULD
54: JOHN *JOHN *JOHN BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *MARY *JOHN *IX *IX JOHN DECIDE VISIT MARY
67: JOHN *JOHN *MARY BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *MARY VISIT MARY JOHN WILL VISIT MARY
74: JOHN *JOHN *IX MARY JOHN NOT VISIT MARY
77: *JOHN *ARRIVE MARY ANN BLAME MARY
84: *GO *CAR *IX *LOVE IX-1P FIND SOMETHING-ONE BOOK
89: *MARY *JOHN *IX *IX *JOHN *WHAT *CAN JOHN IX GIVE MAN IX NEW COAT
90: JOHN *JOHN *JOHN *IX *IX *MARY JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *IX *JOHN *IX WOMAN *MARY JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: *JOHN *ARRIVE CAR *HOUSE POSS NEW CAR BREAK-DOWN
105: JOHN *JOHN JOHN LEG
107: JOHN POSS *ARRIVE *MARY *JOHN JOHN POSS FRIEND HAVE CANDY
108: *JOHN *LOVE WOMAN ARRIVE
113: *JOHN CAR *MARY *IX *GIVE1 IX CAR BLUE SUE BUY
119: *JOHN *GIVE1 IX CAR *MARY SUE BUY IX CAR BLUE
122: JOHN *GIVE1 *WHAT JOHN READ BOOK
139: JOHN *GIVE1 WHAT *JOHN *WHAT JOHN BUY WHAT YESTERDAY BOOK
142: JOHN BUY *FUTURE WHAT *WHAT JOHN BUY YESTERDAY WHAT BOOK
158: LOVE JOHN *JOHN LOVE JOHN WHO
167: JOHN IX *IX *WHAT MARY JOHN IX SAY LOVE MARY
171: JOHN *JOHN BLAME JOHN MARY BLAME
174: *GIVE1 *LOVE GIVE1 *JOHN *CAR PEOPLE GROUP GIVE1 JANA TOY
181: JOHN ARRIVE JOHN ARRIVE
184: *IX *JOHN *GIVE1 TEACHER *MARY ALL BOY GIVE TEACHER APPLE
189: JOHN *JOHN *JOHN *ARRIVE JOHN GIVE GIRL BOX
193: JOHN *IX *WOMAN BOX JOHN GIVE GIRL BOX
199: *JOHN *WHAT *MARY LIKE CHOCOLATE WHO
201: JOHN *IX *IX *JOHN BUY HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: polar-rr, polar-rtheta, polar-lr, polar-ltheta
Selector: SelectorCV
**** WER = 0.6235955056179775
Total correct: 67 out of 178
Video Recognized Correct
=====================================================================================================
2: *POSS WRITE HOMEWORK JOHN WRITE HOMEWORK
7: JOHN CAN GO CAN JOHN CAN GO CAN
12: *IX *CAR *WHAT CAN JOHN CAN GO CAN
21: JOHN *HOMEWORK WONT *JOHN *CAR *CAR *FUTURE *TOMORROW JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN *TELL *LOVE *TELL IX JOHN LIKE IX IX IX
28: JOHN *TELL *LOVE *TELL *LOVE JOHN LIKE IX IX IX
30: JOHN LIKE *GO *LIKE *GO JOHN LIKE IX IX IX
36: *VISIT *VISIT *GIVE *SHOOT *MARY *IX MARY VEGETABLE KNOW IX LIKE CORN1
40: *IX *VISIT *CORN *JOHN *MARY JOHN IX THINK MARY LOVE
43: JOHN *SHOULD BUY HOUSE JOHN MUST BUY HOUSE
50: *JOHN *FRANK BUY CAR SHOULD FUTURE JOHN BUY CAR SHOULD
54: JOHN *FRANK *WHO BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *IX *VISIT VISIT MARY JOHN DECIDE VISIT MARY
67: JOHN FUTURE *WHO BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *FINISH *GO *BLAME JOHN WILL VISIT MARY
74: *GO *VISIT *MARY *GO JOHN NOT VISIT MARY
77: *JOHN BLAME *LOVE ANN BLAME MARY
84: *HOMEWORK *BLAME *GO BOOK IX-1P FIND SOMETHING-ONE BOOK
89: *GIVE1 *GIVE *SOMETHING-ONE *SOMETHING-ONE *SOMETHING-ONE *ARRIVE COAT JOHN IX GIVE MAN IX NEW COAT
90: JOHN *HAVE *SOMETHING-ONE SOMETHING-ONE *VISIT *ARRIVE JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN GIVE *SOMETHING-ONE SOMETHING-ONE *SOMETHING-ONE BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW CAR BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: JOHN *PREFER JOHN LEG
107: JOHN *GIVE *HAVE *GO *GO JOHN POSS FRIEND HAVE CANDY
108: *MARY *HOMEWORK WOMAN ARRIVE
113: IX *HAVE *SUE *JOHN *BUY1 IX CAR BLUE SUE BUY
119: *VISIT *BUY1 *GO *VISIT *VISIT SUE BUY IX CAR BLUE
122: JOHN *BOOK BOOK JOHN READ BOOK
139: JOHN *BUY1 *DECIDE YESTERDAY *ARRIVE JOHN BUY WHAT YESTERDAY BOOK
142: JOHN *NEW *GO *CAR BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE JOHN WHO LOVE JOHN WHO
167: JOHN *JOHN *VISIT LOVE *GO JOHN IX SAY LOVE MARY
171: JOHN *JOHN *SOMETHING-ONE JOHN MARY BLAME
174: *CAN *GIVE3 GIVE1 *CORN *VISIT PEOPLE GROUP GIVE1 JANA TOY
181: *YESTERDAY *SOMETHING-ONE JOHN ARRIVE
184: *GIVE BOY *GO TEACHER *CORN ALL BOY GIVE TEACHER APPLE
189: JOHN *VISIT *VISIT *CAN JOHN GIVE GIRL BOX
193: *IX *HAVE *VISIT BOX JOHN GIVE GIRL BOX
199: *HOMEWORK CHOCOLATE *TELL LIKE CHOCOLATE WHO
201: JOHN *SHOULD *GIVE *JOHN BUY HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: polar-rr, polar-rtheta, polar-lr, polar-ltheta
Selector: SelectorBIC
**** WER = 0.6179775280898876
Total correct: 68 out of 178
Video Recognized Correct
=====================================================================================================
2: *GO WRITE HOMEWORK JOHN WRITE HOMEWORK
7: JOHN *WHAT *MARY *WHAT JOHN CAN GO CAN
12: JOHN *WHAT *GO1 CAN JOHN CAN GO CAN
21: *IX *HOMEWORK WONT *FUTURE *CAR *CAR *GO *TOMORROW JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: *FRANK LIKE IX *WHO IX JOHN LIKE IX IX IX
28: *IX *WHO *FUTURE *FUTURE IX JOHN LIKE IX IX IX
30: *SHOULD LIKE *GO *MARY *GO JOHN LIKE IX IX IX
36: *SOMETHING-ONE VEGETABLE *GIRL *GIVE *MARY *MARY MARY VEGETABLE KNOW IX LIKE CORN1
40: *SUE *GIVE *DECIDE MARY *GO JOHN IX THINK MARY LOVE
43: *IX *GO BUY HOUSE JOHN MUST BUY HOUSE
50: *POSS *SEE BUY CAR *ARRIVE FUTURE JOHN BUY CAR SHOULD
54: JOHN SHOULD *WHO BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *MARY *PREFER *MARY MARY JOHN DECIDE VISIT MARY
67: *LIKE *MOTHER NOT BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *FINISH *GIVE1 MARY JOHN WILL VISIT MARY
74: *GO *WHO *GO *GO JOHN NOT VISIT MARY
77: *IX BLAME *LOVE ANN BLAME MARY
84: *HOMEWORK *GIVE1 *POSS BOOK IX-1P FIND SOMETHING-ONE BOOK
89: *MAN *GIVE *WOMAN *IX IX *BUY *BOOK JOHN IX GIVE MAN IX NEW COAT
90: JOHN *GIVE1 IX *GIVE3 *GIVE1 *COAT JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *WOMAN *WOMAN *WOMAN WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW CAR BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: *FRANK *VEGETABLE JOHN LEG
107: *LIKE *SOMETHING-ONE *HAVE *GO *WHO JOHN POSS FRIEND HAVE CANDY
108: *IX ARRIVE WOMAN ARRIVE
113: IX CAR *SUE *SOMETHING-ONE *ARRIVE IX CAR BLUE SUE BUY
119: *PREFER *BUY1 IX CAR *SOMETHING-ONE SUE BUY IX CAR BLUE
122: JOHN *GIVE1 BOOK JOHN READ BOOK
139: *SHOULD *BUY1 *CAR YESTERDAY BOOK JOHN BUY WHAT YESTERDAY BOOK
142: *FRANK BUY YESTERDAY WHAT BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE *MARY WHO LOVE JOHN WHO
167: *MARY *SOMETHING-ONE *MARY LOVE *LOVE JOHN IX SAY LOVE MARY
171: *SOMETHING-ONE *SOMETHING-ONE BLAME JOHN MARY BLAME
174: *CAN *GIVE3 GIVE1 *GO *WHAT PEOPLE GROUP GIVE1 JANA TOY
181: *SUE ARRIVE JOHN ARRIVE
184: *IX BOY *GIVE1 TEACHER APPLE ALL BOY GIVE TEACHER APPLE
189: *SUE *SOMETHING-ONE *YESTERDAY *ARRIVE JOHN GIVE GIRL BOX
193: JOHN *SOMETHING-ONE *YESTERDAY BOX JOHN GIVE GIRL BOX
199: *HOMEWORK CHOCOLATE WHO LIKE CHOCOLATE WHO
201: JOHN *MAN *MAN *JOHN BUY HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: polar-rr, polar-rtheta, polar-lr, polar-ltheta
Selector: SelectorDIC
**** WER = 0.5449438202247191
Total correct: 81 out of 178
Video Recognized Correct
=====================================================================================================
2: JOHN *NEW *GIVE1 JOHN WRITE HOMEWORK
7: JOHN CAN GO CAN JOHN CAN GO CAN
12: JOHN *WHAT *JOHN CAN JOHN CAN GO CAN
21: JOHN *NEW *JOHN *PREFER *GIVE1 *WHAT *FUTURE *WHO JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN *IX IX *WHO IX JOHN LIKE IX IX IX
28: JOHN *FUTURE IX *FUTURE *LOVE JOHN LIKE IX IX IX
30: JOHN LIKE *MARY *MARY *MARY JOHN LIKE IX IX IX
36: *IX *VISIT *GIVE *GIVE *MARY *MARY MARY VEGETABLE KNOW IX LIKE CORN1
40: JOHN *GO *GIVE *JOHN *MARY JOHN IX THINK MARY LOVE
43: JOHN *IX BUY HOUSE JOHN MUST BUY HOUSE
50: *JOHN *SEE BUY CAR *JOHN FUTURE JOHN BUY CAR SHOULD
54: JOHN SHOULD NOT BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *MARY *GO *GO MARY JOHN DECIDE VISIT MARY
67: *SHOULD FUTURE *MARY BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *FUTURE *GIVE1 MARY JOHN WILL VISIT MARY
74: *IX *GO *GO *VISIT JOHN NOT VISIT MARY
77: *JOHN *GIVE1 MARY ANN BLAME MARY
84: *HOMEWORK *GIVE1 *GIVE1 *COAT IX-1P FIND SOMETHING-ONE BOOK
89: *GIVE *GIVE *WOMAN *WOMAN IX *ARRIVE *BOOK JOHN IX GIVE MAN IX NEW COAT
90: JOHN GIVE IX SOMETHING-ONE WOMAN *ARRIVE JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *WOMAN IX *WOMAN WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW CAR BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: JOHN *SEE JOHN LEG
107: JOHN POSS *HAVE HAVE *MARY JOHN POSS FRIEND HAVE CANDY
108: *LOVE *LOVE WOMAN ARRIVE
113: IX CAR *IX *MARY *JOHN IX CAR BLUE SUE BUY
119: *MARY *BUY1 IX *BLAME *IX SUE BUY IX CAR BLUE
122: JOHN *GIVE1 BOOK JOHN READ BOOK
139: JOHN *ARRIVE WHAT *MARY *ARRIVE JOHN BUY WHAT YESTERDAY BOOK
142: JOHN BUY YESTERDAY WHAT BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE JOHN WHO LOVE JOHN WHO
167: JOHN *MARY *VISIT LOVE MARY JOHN IX SAY LOVE MARY
171: *IX MARY BLAME JOHN MARY BLAME
174: *JOHN *JOHN GIVE1 *YESTERDAY *JOHN PEOPLE GROUP GIVE1 JANA TOY
181: *EAT ARRIVE JOHN ARRIVE
184: *GO BOY *GIVE1 TEACHER *YESTERDAY ALL BOY GIVE TEACHER APPLE
189: *MARY *GO *YESTERDAY BOX JOHN GIVE GIRL BOX
193: JOHN *GO *YESTERDAY BOX JOHN GIVE GIRL BOX
199: *JOHN *STUDENT *GO LIKE CHOCOLATE WHO
201: JOHN *MAN *LOVE *JOHN BUY HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: norm-polar-rr, norm-polar-rtheta, norm-polar-lr, norm-polar-ltheta
Selector: SelectorCV
**** WER = 0.6404494382022472
Total correct: 64 out of 178
Video Recognized Correct
=====================================================================================================
2: JOHN WRITE HOMEWORK JOHN WRITE HOMEWORK
7: JOHN *HOUSE GO CAN JOHN CAN GO CAN
12: JOHN *CAR *CAN CAN JOHN CAN GO CAN
21: *GO *VIDEOTAPE *NEW *MARY *HOUSE *CAR *FUTURE *WRITE JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: *GO LIKE *GO *MARY *LOVE JOHN LIKE IX IX IX
28: *GO *MARY *LOVE *MARY *LOVE JOHN LIKE IX IX IX
30: *SHOOT LIKE IX *WOMAN IX JOHN LIKE IX IX IX
36: *IX VEGETABLE *GIVE IX *LOVE *IX MARY VEGETABLE KNOW IX LIKE CORN1
40: *JANA *VISIT *FUTURE1 *JANA LOVE JOHN IX THINK MARY LOVE
43: JOHN *JOHN *HAVE HOUSE JOHN MUST BUY HOUSE
50: *POSS *GIVE1 BUY CAR *GO FUTURE JOHN BUY CAR SHOULD
54: JOHN SHOULD NOT BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *IX *MOTHER VISIT *IX JOHN DECIDE VISIT MARY
67: JOHN *GIVE1 *IX *ARRIVE HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *GIVE1 VISIT MARY JOHN WILL VISIT MARY
74: *SHOOT NOT *GO MARY JOHN NOT VISIT MARY
77: *GO BLAME MARY ANN BLAME MARY
84: *IX *BLAME *POSS BOOK IX-1P FIND SOMETHING-ONE BOOK
89: *WHO *SHOULD *THROW *WOMAN *GIVE NEW COAT JOHN IX GIVE MAN IX NEW COAT
90: JOHN *GIVE1 *POSS *POSS *VISIT *VIDEOTAPE JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN GIVE *WOMAN *WOMAN *VISIT BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS *ARRIVE CAR BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: JOHN *SEE JOHN LEG
107: *LIKE *SHOULD *HAVE *WOMAN CANDY JOHN POSS FRIEND HAVE CANDY
108: *IX *HOMEWORK WOMAN ARRIVE
113: *JOHN *CAN *IX *IX *NEW IX CAR BLUE SUE BUY
119: *VEGETABLE *BUY1 *SOMETHING-ONE *ARRIVE *FUTURE SUE BUY IX CAR BLUE
122: JOHN *HOUSE BOOK JOHN READ BOOK
139: JOHN *BUY1 *CAN *GO *NEW JOHN BUY WHAT YESTERDAY BOOK
142: JOHN *HAVE *GO *CAR BOOK JOHN BUY YESTERDAY WHAT BOOK
158: *BLAME *MARY WHO LOVE JOHN WHO
167: JOHN IX *VISIT *MARY *LOVE JOHN IX SAY LOVE MARY
171: JOHN *BROCCOLI BLAME JOHN MARY BLAME
174: *BLAME *NEW GIVE1 *GO *VISIT PEOPLE GROUP GIVE1 JANA TOY
181: *VISIT *NEW JOHN ARRIVE
184: *SOMETHING-ONE BOY *HOUSE TEACHER *GIVE ALL BOY GIVE TEACHER APPLE
189: *JANA *SELF *YESTERDAY *ARRIVE JOHN GIVE GIRL BOX
193: JOHN *GIVE1 *VISIT BOX JOHN GIVE GIRL BOX
199: *LOVE *HOMEWORK *IX LIKE CHOCOLATE WHO
201: JOHN *WHO *IX *WOMAN BUY HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: norm-polar-rr, norm-polar-rtheta, norm-polar-lr, norm-polar-ltheta
Selector: SelectorBIC
**** WER = 0.6235955056179775
Total correct: 67 out of 178
Video Recognized Correct
=====================================================================================================
2: *WOMAN WRITE HOMEWORK JOHN WRITE HOMEWORK
7: JOHN *BUY *MARY CAN JOHN CAN GO CAN
12: *IX *CAR *WHAT *WHAT JOHN CAN GO CAN
21: JOHN *NEW *NEW *IX-1P *HOUSE *CAR *FUTURE *WHO JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: *IX *IX *MARY IX *MARY JOHN LIKE IX IX IX
28: *IX *JOHN *LOVE IX *MARY JOHN LIKE IX IX IX
30: *SHOOT LIKE *MARY *LOVE *MARY JOHN LIKE IX IX IX
36: MARY *NOT *GIRL *TELL *LOVE *LIKE MARY VEGETABLE KNOW IX LIKE CORN1
40: *SUE *GIVE *FUTURE1 *SUE *MARY JOHN IX THINK MARY LOVE
43: *FRANK *SHOULD BUY HOUSE JOHN MUST BUY HOUSE
50: *FRANK *SEE BUY CAR *SOMETHING-ONE FUTURE JOHN BUY CAR SHOULD
54: JOHN *FRANK NOT BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: JOHN *MOTHER *WOMAN MARY JOHN DECIDE VISIT MARY
67: JOHN *GIVE1 *GO BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *SEE *GO MARY JOHN WILL VISIT MARY
74: *SHOOT NOT *GIVE MARY JOHN NOT VISIT MARY
77: *IX BLAME MARY ANN BLAME MARY
84: *LOVE *SOMETHING-ONE *POSS BOOK IX-1P FIND SOMETHING-ONE BOOK
89: *FUTURE *SHOULD *THROW *WOMAN IX NEW *BREAK-DOWN JOHN IX GIVE MAN IX NEW COAT
90: *SEE *FUTURE IX *POSS WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN GIVE IX *IX WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW CAR BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: *FRANK *SEE JOHN LEG
107: *LIKE *JOHN *HAVE *MARY CANDY JOHN POSS FRIEND HAVE CANDY
108: *WHO *HOMEWORK WOMAN ARRIVE
113: IX *CAN *SUE *LEAVE *SOMETHING-ONE IX CAR BLUE SUE BUY
119: *PREFER *BUY1 *CAR *ARRIVE *SEE SUE BUY IX CAR BLUE
122: JOHN *GIVE1 BOOK JOHN READ BOOK
139: JOHN *BUY1 *CAR *GO BOOK JOHN BUY WHAT YESTERDAY BOOK
142: *FRANK *ARRIVE YESTERDAY WHAT BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE *MARY WHO LOVE JOHN WHO
167: JOHN *LEAVE *NOT *MARY *LOVE JOHN IX SAY LOVE MARY
171: *LIKE *JOHN BLAME JOHN MARY BLAME
174: *COAT *GIVE3 GIVE1 *NOT *CAR PEOPLE GROUP GIVE1 JANA TOY
181: JOHN ARRIVE JOHN ARRIVE
184: *IX BOY *GIVE1 TEACHER APPLE ALL BOY GIVE TEACHER APPLE
189: *JANA *FUTURE *GIVE *ARRIVE JOHN GIVE GIRL BOX
193: JOHN *SOMETHING-ONE *YESTERDAY BOX JOHN GIVE GIRL BOX
199: *LOVE *HOMEWORK WHO LIKE CHOCOLATE WHO
201: JOHN *MAN *WOMAN *JOHN *STUDENT HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: norm-polar-rr, norm-polar-rtheta, norm-polar-lr, norm-polar-ltheta
Selector: SelectorDIC
**** WER = 0.5730337078651685
Total correct: 76 out of 178
Video Recognized Correct
=====================================================================================================
2: JOHN WRITE *ARRIVE JOHN WRITE HOMEWORK
7: *SOMETHING-ONE *NEW GO CAN JOHN CAN GO CAN
12: JOHN *CAR *WHAT *HOUSE JOHN CAN GO CAN
21: JOHN *NEW *JOHN *ANN *CAR *HOUSE *ARRIVE *YESTERDAY JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN *MARY *MARY *JOHN *JOHN JOHN LIKE IX IX IX
28: JOHN *JOHN *JOHN *JOHN *JOHN JOHN LIKE IX IX IX
30: JOHN LIKE *MARY *MARY *SHOOT JOHN LIKE IX IX IX
36: *IX *NOT *YESTERDAY *TELL *LOVE *MARY MARY VEGETABLE KNOW IX LIKE CORN1
40: *LEAVE *JOHN *FUTURE1 *JOHN LOVE JOHN IX THINK MARY LOVE
43: JOHN *JOHN BUY HOUSE JOHN MUST BUY HOUSE
50: *JOHN *SEE BUY CAR *JOHN FUTURE JOHN BUY CAR SHOULD
54: JOHN SHOULD *MARY BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *MARY *VISIT *GO MARY JOHN DECIDE VISIT MARY
67: JOHN FUTURE *JOHN BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *FUTURE *GO MARY JOHN WILL VISIT MARY
74: *IX *JOHN *JOHN *LOVE JOHN NOT VISIT MARY
77: *JOHN BLAME MARY ANN BLAME MARY
84: *JOHN *ARRIVE *VISIT *NEW IX-1P FIND SOMETHING-ONE BOOK
89: *FUTURE IX *IX *THROW IX NEW COAT JOHN IX GIVE MAN IX NEW COAT
90: *FUTURE *SOMETHING-ONE IX SOMETHING-ONE WOMAN *VIDEOTAPE JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *IX IX *IX WOMAN *VISIT JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW CAR BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: JOHN *POSS JOHN LEG
107: JOHN *IX *NEW *MARY CANDY JOHN POSS FRIEND HAVE CANDY
108: *IX *JOHN WOMAN ARRIVE
113: IX *CAN *IX *SOMETHING-ONE *BOX IX CAR BLUE SUE BUY
119: *PREFER *LOVE IX CAR *GO SUE BUY IX CAR BLUE
122: JOHN *GIVE1 BOOK JOHN READ BOOK
139: JOHN *ARRIVE WHAT *JOHN BOOK JOHN BUY WHAT YESTERDAY BOOK
142: JOHN BUY YESTERDAY WHAT BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE JOHN *NOT LOVE JOHN WHO
167: JOHN IX *SAY-1P *MARY *LOVE JOHN IX SAY LOVE MARY
171: JOHN *SOMETHING-ONE BLAME JOHN MARY BLAME
174: *CAR *GIVE1 GIVE1 *WHO *CAR PEOPLE GROUP GIVE1 JANA TOY
181: JOHN ARRIVE JOHN ARRIVE
184: *IX *FUTURE *GIVE1 TEACHER APPLE ALL BOY GIVE TEACHER APPLE
189: *MARY *LEAVE *YESTERDAY *ARRIVE JOHN GIVE GIRL BOX
193: JOHN *SOMETHING-ONE *GO BOX JOHN GIVE GIRL BOX
199: *JOHN *BUY1 WHO LIKE CHOCOLATE WHO
201: JOHN *MAN *IX *JOHN BUY HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: delta-norm-polar-rr, delta-norm-polar-rtheta, delta-norm-polar-lr, delta-norm-polar-ltheta
Selector: SelectorCV
**** WER = 0.6067415730337079
Total correct: 70 out of 178
Video Recognized Correct
=====================================================================================================
2: *POSS WRITE HOMEWORK JOHN WRITE HOMEWORK
7: JOHN CAN *GIVE *MANY JOHN CAN GO CAN
12: JOHN *BOX *FUTURE CAN JOHN CAN GO CAN
21: JOHN *WHAT *HOMEWORK *NOT *BUY *GO *WHAT *MARY JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN *IX *JOHN IX IX JOHN LIKE IX IX IX
28: JOHN *MARY IX IX IX JOHN LIKE IX IX IX
30: JOHN *WHO *PUTASIDE *PAST IX JOHN LIKE IX IX IX
36: *CANDY *YESTERDAY *MAN *SEARCH-FOR *VISIT *MARY MARY VEGETABLE KNOW IX LIKE CORN1
40: *VEGETABLE IX *JOHN *LIKE *JOHN JOHN IX THINK MARY LOVE
43: JOHN *IX BUY HOUSE JOHN MUST BUY HOUSE
50: *JOHN *SHOULD BUY CAR *YESTERDAY FUTURE JOHN BUY CAR SHOULD
54: JOHN *PAST *JOHN BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: JOHN *PAST *MAN *IX JOHN DECIDE VISIT MARY
67: JOHN *IX *READ *WOMAN HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN WILL VISIT *CAR JOHN WILL VISIT MARY
74: JOHN *IX *GIVE2 MARY JOHN NOT VISIT MARY
77: *JOHN *VIDEOTAPE MARY ANN BLAME MARY
84: *JOHN *GO *BROTHER BOOK IX-1P FIND SOMETHING-ONE BOOK
89: *LEAVE IX GIVE *THROW *THROW *CAR COAT JOHN IX GIVE MAN IX NEW COAT
90: *MARY GIVE IX *GIVE WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN GIVE IX *POSS WOMAN *BUY JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: POSS NEW CAR *HOUSE POSS NEW CAR BREAK-DOWN
105: *ANN *IX JOHN LEG
107: *WHO *WOMAN FRIEND *MARY *JOHN JOHN POSS FRIEND HAVE CANDY
108: WOMAN *BOOK WOMAN ARRIVE
113: *JOHN *GO *MARY *GIVE *BUY1 IX CAR BLUE SUE BUY
119: *IX *STUDENT *CAR *GO BLUE SUE BUY IX CAR BLUE
122: JOHN *GO BOOK JOHN READ BOOK
139: JOHN BUY *TEACHER *WHO *BUY1 JOHN BUY WHAT YESTERDAY BOOK
142: JOHN BUY *WHAT *MARY *WHAT JOHN BUY YESTERDAY WHAT BOOK
158: *NEW *MARY WHO LOVE JOHN WHO
167: JOHN *WHO *OLD *FRIEND *HERE JOHN IX SAY LOVE MARY
171: JOHN *VEGETABLE BLAME JOHN MARY BLAME
174: *GO *WHAT GIVE1 *IX *CAN PEOPLE GROUP GIVE1 JANA TOY
181: *IX *BOOK JOHN ARRIVE
184: *GIVE BOY *GIVE1 TEACHER *WHO ALL BOY GIVE TEACHER APPLE
189: *IX GIVE *OLD *BOOK JOHN GIVE GIRL BOX
193: JOHN *YESTERDAY *WHO BOX JOHN GIVE GIRL BOX
199: *JOHN *FISH *MARY LIKE CHOCOLATE WHO
201: JOHN *WHO *WHO *CHOCOLATE *GO HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: delta-norm-polar-rr, delta-norm-polar-rtheta, delta-norm-polar-lr, delta-norm-polar-ltheta
Selector: SelectorBIC
**** WER = 0.5898876404494382
Total correct: 73 out of 178
Video Recognized Correct
=====================================================================================================
2: JOHN *IX HOMEWORK JOHN WRITE HOMEWORK
7: JOHN *HAVE *GIVE *HOUSE JOHN CAN GO CAN
12: JOHN CAN *GO1 CAN JOHN CAN GO CAN
21: JOHN FISH WONT *JOHN *CAR *FUTURE *YESTERDAY *WHAT JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN *MARY *JOHN IX IX JOHN LIKE IX IX IX
28: JOHN *MARY *MARY IX IX JOHN LIKE IX IX IX
30: JOHN *VEGETABLE *PUTASIDE *JOHN IX JOHN LIKE IX IX IX
36: MARY *MOTHER *SEARCH-FOR *GO *CANDY *MARY MARY VEGETABLE KNOW IX LIKE CORN1
40: *FRANK IX *WHO *PUTASIDE *SAY-1P JOHN IX THINK MARY LOVE
43: JOHN *SHOULD BUY HOUSE JOHN MUST BUY HOUSE
50: *JOHN *VEGETABLE BUY CAR *MARY FUTURE JOHN BUY CAR SHOULD
54: JOHN *MARY *SUE BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: JOHN *JOHN *WOMAN *JOHN JOHN DECIDE VISIT MARY
67: JOHN *IX *SHOULD BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *SOMETHING-ONE *GO *CAR JOHN WILL VISIT MARY
74: JOHN *IX *GIVE2 *JOHN JOHN NOT VISIT MARY
77: *JOHN BLAME MARY ANN BLAME MARY
84: *JOHN *GIVE1 *FUTURE BOOK IX-1P FIND SOMETHING-ONE BOOK
89: JOHN *JOHN GIVE *GIVE *THROW *CAR COAT JOHN IX GIVE MAN IX NEW COAT
90: *MARY *YESTERDAY IX *MARY WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *IX IX *IX WOMAN *NEW JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: *IX NEW CAR BREAK-DOWN POSS NEW CAR BREAK-DOWN
105: JOHN *IX JOHN LEG
107: JOHN POSS *HAVE HAVE *JOHN JOHN POSS FRIEND HAVE CANDY
108: *IX *STUDENT WOMAN ARRIVE
113: *JOHN *PEOPLE *WHO *JOHN *BUY1 IX CAR BLUE SUE BUY
119: *JOHN *BUY1 *HOUSE *PEOPLE *HAVE SUE BUY IX CAR BLUE
122: JOHN *VISIT BOOK JOHN READ BOOK
139: *WILL BUY *COAT *WHO *STOLEN JOHN BUY WHAT YESTERDAY BOOK
142: JOHN BUY *GO WHAT BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE *WHO WHO LOVE JOHN WHO
167: *ANN *BILL *IX *FRIEND *HERE JOHN IX SAY LOVE MARY
171: JOHN *JOHN BLAME JO<NAME> BLAME
174: *CAR *WHAT GIVE1 *IX *FINISH PEOPLE GROUP GIVE1 JANA TOY
181: JOHN *BOOK JOHN ARRIVE
184: ALL *WANT *GIVE1 TEACHER *SEE ALL BOY GIVE TEACHER APPLE
189: JOHN *YESTERDAY *WANT *BOOK JOHN GIVE GIRL BOX
193: JOHN *YESTERDAY *CORN BOX JOHN GIVE GIRL BOX
199: *JOHN *ARRIVE WHO LIKE CHOCOLATE WHO
201: JOHN *WHO *WHO *POSS *VISIT HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
Features: delta-norm-polar-rr, delta-norm-polar-rtheta, delta-norm-polar-lr, delta-norm-polar-ltheta
Selector: SelectorDIC
**** WER = 0.5842696629213483
Total correct: 74 out of 178
Video Recognized Correct
=====================================================================================================
2: JOHN *IX HOMEWORK JOHN WRITE HOMEWORK
7: JOHN *VISIT GO *ARRIVE JOHN CAN GO CAN
12: JOHN *BOX *GIVE1 CAN JOHN CAN GO CAN
21: JOHN FISH *GO *MARY *HOUSE *GO *GIVE1 *MARY JOHN FISH WONT EAT BUT CAN EAT CHICKEN
25: JOHN *IX IX IX IX JOHN LIKE IX IX IX
28: JOHN *MARY IX IX IX JOHN LIKE IX IX IX
30: JOHN *SHOULD *PUTASIDE *GIVE IX JOHN LIKE IX IX IX
36: *JOHN *JOHN *SEARCH-FOR IX *CANDY *IX MARY VEGETABLE KNOW IX LIKE CORN1
40: JOHN *CORN *WHO *PUTASIDE *PREFER JOHN IX THINK MARY LOVE
43: JOHN *IX BUY HOUSE JOHN MUST BUY HOUSE
50: *JOHN *NOT BUY CAR *MARY FUTURE JOHN BUY CAR SHOULD
54: JOHN *MARY *JOHN BUY HOUSE JOHN SHOULD NOT BUY HOUSE
57: *MARY *PAST VISIT *IX JOHN DECIDE VISIT MARY
67: JOHN *IX *HAVE BUY HOUSE JOHN FUTURE NOT BUY HOUSE
71: JOHN *IX *GO *GO JOHN WILL VISIT MARY
74: JOHN *IX VISIT *IX JOHN NOT VISIT MARY
77: *JOHN *GIVE1 MARY ANN BLAME MARY
84: *GIVE1 *GIVE1 *IX BOOK IX-1P FIND SOMETHING-ONE BOOK
89: JOHN IX GIVE *THROW *THROW *WHAT *CAN JOHN IX GIVE MAN IX NEW COAT
90: JOHN *SEARCH-FOR IX *GIVE WOMAN BOOK JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
92: JOHN *IX IX *IX *WHO *HOUSE JOHN GIVE IX SOMETHING-ONE WOMAN BOOK
100: *IX NEW CAR *HOUSE POSS NEW CAR BREAK-DOWN
105: JOHN *MARY JOHN LEG
107: *MARY POSS *VISIT *MARY *JOHN JOHN POSS FRIEND HAVE CANDY
108: *IX *BOOK WOMAN ARRIVE
113: *JOHN CAR *MARY *GIVE *BOOK IX CAR BLUE SUE BUY
119: *IX *BUY1 IX CAR *WHO SUE BUY IX CAR BLUE
122: JOHN *CAR BOOK JOHN READ BOOK
139: JOHN *ARRIVE *TEACHER *JOHN *STOLEN JOHN BUY WHAT YESTERDAY BOOK
142: JOHN BUY *HOUSE WHAT BOOK JOHN BUY YESTERDAY WHAT BOOK
158: LOVE *WHO *MARY LOVE JOHN WHO
167: *MARY *SHOULD *WOMAN LOVE *HERE JOHN IX SAY LOVE MARY
171: *THINK *JOHN BLAME JOHN MARY BLAME
174: *CAR *JOHN GIVE1 *MARY *PEOPLE PEOPLE GROUP GIVE1 JANA TOY
181: JOHN ARRIVE JOHN ARRIVE
184: *GIVE *GIVE1 *GIVE1 TEACHER *YESTERDAY ALL BOY GIVE TEACHER APPLE
189: JOHN GIVE GIRL *BOOK JOHN GIVE GIRL BOX
193: JOHN *KNOW *HAVE BOX JOHN GIVE GIRL BOX
199: *JOHN *BOOK *JOHN LIKE CHOCOLATE WHO
201: JOHN *WHO *WHO *POSS *VISIT HOUSE JOHN TELL MARY IX-1P BUY HOUSE
*************************************
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><strong>Question 3:</strong> Summarize the error results from three combinations of features and model selectors. What was the "best" combination and why? What additional information might we use to improve our WER? For more insight on improving WER, take a look at the introduction to Part 4.</p>
<p><strong>Answer 3:</strong></p>
<blockquote><p>Based on WERs, these are the best 3 combinations:</p>
<p>Features: polar-rr, polar-rtheta, polar-lr, polar-ltheta<br/>
Selector: SelectorDIC<br/>
WER = 0.5449438202247191</p>
<p>Features: grnd-rx, grnd-ry, grnd-lx, grnd-ly<br/>
Selector: SelectorDIC<br/>
WER = 0.5730337078651685</p>
<p>Features: norm-polar-rr, norm-polar-rtheta, norm-polar-lr, norm-polar-ltheta<br/>
Selector: SelectorDIC<br/>
WER = 0.5730337078651685</p>
<p>The best combination was the polar features (polar-rr, polar-rtheta, polar-lr, polar-ltheta), and the DIC selector. The discriminatory aspect of the DIC selector seems to generate better predictors in this case. Interestingly enough, DIC produced the same results when using ground features and normalized polar features, although not as good as DIC with polar features. Nonetheless, this means DIC is a good technique to use in this domain.</p>
<p>To improve the WER, we can use Statistical Language Models (SMLs). With this technique, we could combine the HMM results (i.e., the work we've done so far) with the probability of certain words ocurring in a given sentence (SMLs) to come up with a final score.</p>
</blockquote>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><a id='part3_test'></a></p>
<h3 id="Recognizer-Unit-Tests">Recognizer Unit Tests<a class="anchor-link" href="#Recognizer-Unit-Tests">¶</a></h3><p>Run the following unit tests as a sanity check on the defined recognizer. The test simply looks for some valid values but is not exhaustive. However, the project should not be submitted if these tests don't pass.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [50]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">asl_test_recognizer</span> <span class="k">import</span> <span class="n">TestRecognize</span>
<span class="n">suite</span> <span class="o">=</span> <span class="n">unittest</span><span class="o">.</span><span class="n">TestLoader</span><span class="p">()</span><span class="o">.</span><span class="n">loadTestsFromModule</span><span class="p">(</span><span class="n">TestRecognize</span><span class="p">())</span>
<span class="n">unittest</span><span class="o">.</span><span class="n">TextTestRunner</span><span class="p">()</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">suite</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="prompt"></div>
<div class="output_subarea output_stream output_stderr output_text">
<pre>..
----------------------------------------------------------------------
Ran 2 tests in 23.768s
OK
</pre>
</div>
</div>
<div class="output_area">
<div class="prompt output_prompt">Out[50]:</div>
<div class="output_text output_subarea output_execute_result">
<pre><unittest.runner.TextTestResult run=2 errors=0 failures=0></pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><a id='part4_info'></a></p>
<h2 id="PART-4:-(OPTIONAL)--Improve-the-WER-with-Language-Models">PART 4: (OPTIONAL) Improve the WER with Language Models<a class="anchor-link" href="#PART-4:-(OPTIONAL)--Improve-the-WER-with-Language-Models">¶</a></h2><p>We've squeezed just about as much as we can out of the model and still only get about 50% of the words right! Surely we can do better than that. Probability to the rescue again in the form of <a href="https://en.wikipedia.org/wiki/Language_model">statistical language models (SLM)</a>. The basic idea is that each word has some probability of occurrence within the set, and some probability that it is adjacent to specific other words. We can use that additional information to make better choices.</p>
<h5 id="Additional-reading-and-resources">Additional reading and resources<a class="anchor-link" href="#Additional-reading-and-resources">¶</a></h5><ul>
<li><a href="https://web.stanford.edu/class/cs124/lec/languagemodeling.pdf">Introduction to N-grams (Stanford Jurafsky slides)</a></li>
<li><a href="https://www-i6.informatik.rwth-aachen.de/publications/download/154/Dreuw--2007.pdf">Speech Recognition Techniques for a Sign Language Recognition System, <NAME> et al</a> see the improved results of applying LM on <em>this</em> data!</li>
<li><a href="ftp://wasserstoff.informatik.rwth-aachen.de/pub/rwth-boston-104/lm/">SLM data for <em>this</em> ASL dataset</a></li>
</ul>
<h5 id="Optional-challenge">Optional challenge<a class="anchor-link" href="#Optional-challenge">¶</a></h5><p>The recognizer you implemented in Part 3 is equivalent to a "0-gram" SLM. Improve the WER with the SLM data provided with the data set in the link above using "1-gram", "2-gram", and/or "3-gram" statistics. The <code>probabilities</code> data you've already calculated will be useful and can be turned into a pandas DataFrame if desired (see next cell).<br>
Good luck! Share your results with the class!</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># create a DataFrame of log likelihoods for the test word items</span>
<span class="n">df_probs</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">data</span><span class="o">=</span><span class="n">probabilities</span><span class="p">)</span>
<span class="n">df_probs</span><span class="o">.</span><span class="n">head</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
| 57bcdbc6a5eba9736235ac80949beff1223029d8 | [
"Python",
"HTML"
]
| 2 | Python | iterativo/aind-recognizer | 29e67e1e1607c3da155f8b8a139dd07b8a30056a | 64f20216525efc46d09230714910b8280c2fa72e |
refs/heads/master | <repo_name>readme/readme.github.com<file_sep>/_posts/2011-07-01-Hello-world.markdown
---
layout: post
categories: [news, cms]
title: Hello world
summary: This is my first post using Github and Jekyll
---
This is an experiment. If it works out I will begin publishing on Github.
I have lots of experience with complicated content management systems. This is different. The documents are written in plain text on my computer, then saved and published to a folder on Github.com. After that, they're auto-magically transformed from text into web pages.
The setup, unfortunately, has a pretty steep learning curve, but I'm going to be very, very happy if it works.
Thanks to those who have gone before, making this easier for me, especially <a href="http://johnsonpage.org">Johnson Page</a>, who figured out how to use Blueprint with Github and Jekyll.
**Update:** Now I'm editing the site using [prose.io](http://prose.io).<file_sep>/_posts/2011-07-07-Why-so-excited.markdown
---
layout: post
categories: [news, cms]
title: Why so excited?
summary: Who cares about Github and Jekyll?
---
Whatever I store in this text file can be quickly turned into a page on my site.
**That's** why I'm excited!<file_sep>/_layouts/post.php
---
layout: default
---
{% assign post = page %}
{% assign use_content = true %}
{% include post.html %}
<file_sep>/more/php-microframeworks/microframeworks.md
!SLIDE
# PHP Microframeworks
## <NAME> — [@jwpage](http://twitter.com/jwpage)
!SLIDE
## Sinatra
* <http://www.sinatrarb.com>
* Ruby DSL for creating web applications.
* Filters, Templates, Helpers
* Extensible
!SLIDE
@@@ ruby
require 'sinatra'
require 'erb'
get '/hello/:name' do |name|
@name = name
erb :hello
end
@@@
!SLIDE
## Sinatra Clones
* Filters, Templates, Helpers
* No Rack middleware.
* Harder to test/mock requests
* Less DSL-ish syntax.
!SLIDE
## Hello, World!
* <http://myapp/hello/Brisbane> → Hello, Brisbane!
* Using templates for output: `Hello, <?= $name ?>!`
<br />
* Slim
* Limonade
* Fitzgerald
* Silex (based on Symfony2)
* Lithium (as a microframework)
!SLIDE
## Slim
* <http://www.slimframework.com/>
* PHP 5+
* Documented, tested, maintained.
!SLIDE
@@@ php
<?php
require_once 'slim/Slim.php';
Slim::init();
Slim::get('/hello/:name', function($name) {
Slim::render('hello.php', array('name' => $name));
});
Slim::run();
@@@
!SLIDE
## Limonade
* <http://www.limonade-php.net>
* PHP 5+
* Documented, tested, maintained.
!SLIDE
@@@ php
<?php
require_once 'lib/limonade.php';
dispatch('/hello/:name', function() {
return render(
'hello.php',
array('name' => params('name'))
);
});
@@@
!SLIDE
## Fitzgerald
* <https://github.com/jim/fitzgerald>
* PHP 5+
* Little documentation, good examples.
* No tests.
!SLIDE
@@@ php
<?php
require_once 'lib/fitzgerald.php';
$app = new Application();
$app->get('/hello/:name', function($name) {
return $this->render('hello', array('name' => $name));
});
$app->run();
@@@
!SLIDE
## Silex
* <http://github.com/fabpot/silex/>
* PHP 5.3+
* Based on Symfony2, proof of concept.
* Silex: Little documentation, no tests.
* Symfony2: Well documented and tested.
!SLIDE
@@@ php
<?php
require_once 'silex.phar';
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Templating\Engine;
use Symfony\Component\Templating\Loader\FilesystemLoader;
use Silex\Framework;
$framework = new Framework(array(
'GET /hello/:name' => function($name) {
$loader = new FilesystemLoader('views/%name%.php');
$view = new Engine($loader);
return new Response($view->render(
'hello',
array('name' => $name)
));
}
));
$framework->handle()->send();
@@@
!SLIDE
## Lithium (as a microframework)
* <http://rad-dev.org/lithium/>
* <http://jamalsa.tumblr.com/post/1521361137/lithify-it-like-sinatra>
* PHP 5.3+
* Based on Lithium, proof of concept.
* Lithium: Well documented, tested.
!SLIDE
@@@ php
<?php
use lithium\action\Dispatcher;
use lithium\action\Request;
use lithium\action\Response;
use lithium\core\Libraries;
use lithium\net\http\Router;
use lithium\template\View;
require_once 'libraries/lithium/core/Libraries.php';
Libraries::add('lithium');
Router::connect(
"/hello/{:name}",
array(
"http:method" => "GET",
"name" => null
),
function($request) {
$view = new View(array(
'paths' => array('template' => 'views/{:template}.php')
));
$output = $view->render(
'template',
array('name' => $request->name),
array('template' => 'hello')
);
return new Response(array('body' => $output));
}
);
echo Dispatcher::run(new Request());
@@@
!SLIDE
## Finally
* Many Sinatra clones, just choose one!
* Solve simple problems.
* Know when to switch.
!SLIDE
# That's all.
<file_sep>/colophon/index.markdown
---
layout: page
title: Colophon
---
# Colophon --- About This Site
Under construction. Site design is (obviously) based on <a href="http://johnsonpage.org/colophon/">johnsonpage.org</a><file_sep>/more/analytics/index.php
---
layout: more
title: Google Analytics Bookmarklets
more_css: >
#bookmarklets { display: none; }
img {
padding: 0.5em;
background: #FFF;
border: 1px solid #666;
}
li {
padding-bottom: 1em;
}
li li {
padding: 0;
}
more_javascript: |
$(function() {
$('#analytics_id').keyup(function(event) {
$('#bookmarklets').fadeIn();
var id = $(this).val();
window.setTimeout(function() {
$('#bookmarklets a').attr('href', function(a, b) {
return b.replace(/var id='.*?';/, "var id='"+id+"';");
});
}, 1);
});
});
---
<p>
Follow these simple steps to create some handy Google Analytics bookmarklets!
</p>
<ol>
<li>Open Google Analytics and click "View Report".
<div><img src="view_report.png" /></div>
</li>
<li>Copy the ID from the URL in the address bar.
<div><img src="id.png" /></div>
</li>
<li>Enter your ID here: <input id="analytics_id" type="text" /></li>
<li id="bookmarklets">Drag these newly created bookmarklets into your toolbar:
<ul>
<li><a href="javascript:var id='';var d,p,tm,fm,fy;d=new Date();p=function(n){return ''+((n<10)?'0'+n:n);};fm=p(d.getMonth()+1);fy=p(d.getFullYear());fd=p(d.getDate());location.href='https://www.google.com/analytics/reporting/?id='+id+'&pdr='+fy+fm+fd+'-'+fy+fm+fd;">Today</a></li>
<li><a href="javascript:var id='';var d,p,ty,tm,fm,fy,td,fd;d=new Date();t=new Date();t.setDate(t.getDate()-7);p=function(n){return ''+((n<10)?'0'+n:n);};ty=d.getFullYear();tm=p(d.getMonth()+1);fm=p(t.getMonth()+1);fy=t.getFullYear();fd=p(t.getDate());td=p(d.getDate());location.href='https://www.google.com/analytics/reporting/?id='+id+'&pdr='+fy+fm+fd+'-'+ty+tm+td;">Last Week</a></li>
<li><a href="javascript:var id='';var d,p,ty,tm,fm,fy,td,fd;d=new Date();t=new Date();t.setMonth(t.getMonth()-1);p=function(n){return ''+((n<10)?'0'+n:n);};ty=d.getFullYear();tm=p(d.getMonth()+1);fm=p(t.getMonth()+1);fy=t.getFullYear();fd=p(t.getDate());td=p(d.getDate());location.href='https://www.google.com/analytics/reporting/?id='+id+'&pdr='+fy+fm+fd+'-'+ty+tm+td;">Last Month</a></li>
</ul>
</li>
</ol><file_sep>/README.markdown
standing on the shoulders of <http://johnsonpage.org><file_sep>/_layouts/page.php
---
layout: default
---
<article>
{{ content }}
</article> | 4fd559101de5d5622cad491135a8bf972208ea7a | [
"Markdown",
"PHP"
]
| 8 | Markdown | readme/readme.github.com | a201eecdfb7fef6048a8c4a95d86db869960c4d2 | 9668ed0866b5d8991c8244e830f1e9087acec0b1 |
refs/heads/master | <file_sep>// Get a sunken position depending on whether or not we have an expansion.
BWAPI::TilePosition BuildingManager::getSunkenPosition()
{
// Always make sunkens at natural expansion if you can.
if (createdHatcheriesSet.size() >= 1)
{
BWAPI::TilePosition hatchPosition = createdHatcheriesVector[0];
const std::set<BWTA::BaseLocation*, std::less<BWTA::BaseLocation*>> locations = BWTA::getBaseLocations();
BWTA::BaseLocation *myLocation;
for (BWTA::BaseLocation *p : locations) {
BWAPI::TilePosition z = p->getTilePosition();
if (z == hatchPosition){
// This is the BWTA::Location of the first hatchery.
myLocation = p;
}
}
// Get the set of mineral patches closest to BWTA::Location of the hatchery(it will return like 8 mineral patches usually in the set)
const BWAPI::Unitset mineralSet = myLocation->getMinerals();
//const std::set<BWAPI::Unit*> mineralSet = myLocation->getMinerals();
std::vector<bool> place(8);
std::vector<bool> direction(8);
place = { true, true, true, true, true, true, true, true }; // means[up, left, bot, right,up, left, bot, right]
direction = { true, true, true, true, true, true, true, true }; //means[up,left,bot,right,up,left,bot,right]
int mineX = 0;
int mineY = 0;
int mindis = 999999;
for (BWAPI::Unit p : mineralSet)
{
// Calculate the difference between LeftMostMineralPatch.x - ExpansionHatchery.x and store it in theX
int theX = p->getTilePosition().x - hatchPosition.x;
// Calculate the difference between LeftMostMineralPatch.y - ExpansionHatchery.y and store it in theY
int theY = p->getTilePosition().y - hatchPosition.y;
if ((theX*theX + theY*theY) < mindis){ mineX = theX; mineY = theY; mindis = (theX*theX + theY*theY); }
//break;
}
int gasX;
int gasY;
//Get all geysers near the expansion -- it should only return 1 for every map we play..
const BWAPI::Unitset gasSet = myLocation->getGeysers();
for (BWAPI::Unit p : gasSet)
{
// Calculate the difference between Geyser.x- ExpansionHatchery.x and store it in gasX
gasX = p->getTilePosition().x - hatchPosition.x;
// Calculate the difference between Geyser.y- ExpansionHatchery.y and store it in gasY
gasY = p->getTilePosition().y - hatchPosition.y;
break;
}
// define which side is it
// we donít want to build in the same side. And also block the direction to expand there as well.
if ((mineX*mineX) > (mineY*mineY)){
if (mineX < 0){
// mineral at left
place[1] = false; place[5] = false; direction[1] = false; direction[5] = false;
// gas up or bot
if (gasX >= 0){ if (gasY < 0){ place[0] = false; place[4] = false; } else{ place[2] = false; place[6] = false; } }// for place
if (gasX > 0){ if (gasY < 0){ direction[0] = false; direction[4] = false; } else{ direction[2] = false; direction[6] = false; } } // for direction
}
else{
// mineral at right
place[3] = false; place[7] = false; direction[3] = false; direction[0] = false;
if (gasX <= 0){ if (gasY < 0){ place[0] = false; place[4] = false; } else{ place[2] = false; place[6] = false; } }
if (gasX < 0){ if (gasY < 0){ direction[0] = false; direction[4] = false; } else{ direction[2] = false; direction[6] = false; } }
}
}
else{
if (mineY < 0){
// mineral at up
place[0] = false; place[4] = false; direction[0] = false; direction[4] = false;
if (gasY >= 0){ if (gasX < 0){ place[1] = false; place[5] = false; } else{ place[3] = false; place[7] = false; } }// for place
if (gasY > 0){ if (gasX < 0){ direction[1] = false; direction[5] = false; } else{ direction[3] = false; direction[7] = false; } } // for direction
}
else{
// mineral at bot
place[2] = false; place[6] = false; direction[2] = false; direction[7] = false;
if (gasY <= 0){ if (gasX < 0){ place[1] = false; place[5] = false; } else{ place[3] = false; place[7] = false; } }// for place
if (gasY < 0){ if (gasX < 0){ direction[1] = false; direction[5] = false; } else{ direction[3] = false; direction[7] = false; } } // for direction
}
}
// get gas position
int gaspos = 0;
if ((gasX*gasX) >(gasY*gasY)){ if (gasX < 0){ gaspos = 1; } else{ gaspos = 3; } }// left and right
else{ if (gasY < 0){ gaspos = 4; } else{ gaspos = 2; } }// top and bot
// get mineral position
int minepos = 0;
if ((mineX*mineX) >(mineY*mineY)){ if (mineX < 0){ minepos = 1; } else{ minepos = 3; } }// left and right
else{ if (mineY < 0){ minepos = 4; } else{ minepos = 2; } }// top and bot
// the place position nearest gas
int placepos = -1;
if (place[gaspos]){ placepos = gaspos; }
else if (place[gaspos + 1]){ placepos = gaspos + 1; }
else if (place[gaspos - 1]){ placepos = gaspos - 1; }
else if (place[gaspos + 2]){ placepos = gaspos + 2; }
// give the sunken position
int sunkenX = hatchPosition.x;
int sunkenY = hatchPosition.y;
switch (placepos){
case 5:
case 1://left
sunkenX -= 3;
direction[3] = false; direction[7] = false;
break;
case 6:
case 2://bot
sunkenY += 4;
direction[0] = false; direction[4] = false;
break;
case 7:
case 3://right
sunkenX += 3;
direction[1] = false; direction[5] = false;
break;
case 0:
case 4://top
sunkenY -= 3;
direction[2] = false; direction[6] = false;
break;
}
// the direction position nearest gas
int direcpos = -1;
if (direction[gaspos]){ direcpos = gaspos; }
else if (direction[gaspos + 1]){ direcpos = gaspos + 1; }
else if (direction[gaspos - 1]){ direcpos = gaspos - 1; }
else if (direction[gaspos + 2]){ direcpos = gaspos + 2; }
// use for second row of
int sunkenX2;
int sunkenY2;
int rowpos = -1;
if ((placepos != direcpos) && (((placepos - direcpos)*(placepos - direcpos)) != 16)){ rowpos = placepos; } // placepos == direction
else if (((minepos + 2) != direcpos) && ((((minepos + 2) - direcpos)*((minepos + 2) - direcpos)) != 16)){ rowpos = minepos + 2; } // opposite of mineral == direction
else { rowpos = gaspos + 2; } // opposite of gas == direction
// to see which place is availible
BWAPI::TilePosition sunkPosition;
BWAPI::UnitType sunk = BWAPI::UnitTypes::Zerg_Creep_Colony;
for (int i = 0; i < 5; i++){
sunkPosition = BWAPI::TilePosition(sunkenX, sunkenY);
Building b(sunk, sunkPosition);
if (BWAPI::Broodwar->hasCreep(sunkPosition) && BuildingPlacer::Instance().canBuildHere(sunkPosition, b)) //|| createdBuilding.find(sunkPosition) != createdBuilding.end())
{
return sunkPosition;
}
// look at the second row
switch (rowpos){
case 5:
case 1://left
sunkenX2 = sunkenX - 2;
sunkenY2 = sunkenY;
break;
case 6:
case 2://bot
sunkenY2 = sunkenY + 2;
sunkenX2 = sunkenX;
break;
case 7:
case 3://right
sunkenX2 = sunkenX + 2;
sunkenY2 = sunkenY;
break;
case 0:
case 4://top
sunkenY2 = sunkenY - 2;
sunkenX2 = sunkenX;
break;
}
sunkPosition = BWAPI::TilePosition(sunkenX2, sunkenY2);
Building c(sunk, sunkPosition);
if (BWAPI::Broodwar->hasCreep(sunkPosition) && BuildingPlacer::Instance().canBuildHere(sunkPosition, c)) //|| createdBuilding.find(sunkPosition) != createdBuilding.end())
{
return sunkPosition;
}
// next one of the row
switch (direcpos){
case 5:
case 1://left
sunkenX -= 2;
break;
case 6:
case 2://bot
sunkenY += 2;
break;
case 7:
case 3://right
sunkenX += 2;
break;
case 0:
case 4://top
sunkenY -= 2;
break;
}
}
//return BWAPI::TilePositions::(sunkenX, sunkenY);
}
return BWAPI::TilePositions::None;
}
// gets called every frasme from GameCommander
void BuildingManager::update()
{
validateWorkersAndBuildings(); // check to see if assigned workers have died en route or while constructing
assignWorkersToUnassignedBuildings(); // assign workers to the unassigned buildings and label them 'planned'
constructAssignedBuildings(); // for each planned building, if the worker isn't constructing, send the command
checkForStartedConstruction(); // check to see if any buildings have started construction and update data structures
checkForDeadTerranBuilders(); // if we are terran and a building is under construction without a worker, assign a new one
checkForCompletedBuildings(); // check to see if any buildings have completed and update data structures
}
bool BuildingManager::isBeingBuilt(BWAPI::UnitType type)
{
for (auto & b : _buildings)
{
if (b.type == type)
{
return true;
}
}
return false;
}
// STEP 1: DO BOOK KEEPING ON WORKERS WHICH MAY HAVE DIED
void BuildingManager::validateWorkersAndBuildings()
{
// TODO: if a terran worker dies while constructing and its building
// is under construction, place unit back into buildingsNeedingBuilders
std::vector<Building> toRemove;
// find any buildings which have become obsolete
for (auto & b : _buildings)
{
if (b.status != BuildingStatus::UnderConstruction)
{
continue;
}
if (b.buildingUnit == nullptr || !b.buildingUnit->getType().isBuilding() || b.buildingUnit->getHitPoints() <= 0)
{
toRemove.push_back(b);
}
}
removeBuildings(toRemove);
}
// STEP 2: ASSIGN WORKERS TO BUILDINGS WITHOUT THEM
void BuildingManager::assignWorkersToUnassignedBuildings()
{
// for each building that doesn't have a builder, assign one
for (Building & b : _buildings)
{
if (b.status != BuildingStatus::Unassigned)
{
continue;
}
if (_debugMode) { BWAPI::Broodwar->printf("Assigning Worker To: %s", b.type.getName().c_str()); }
// grab a worker unit from WorkerManager which is closest to this final position
BWAPI::Unit workerToAssign = WorkerManager::Instance().getBuilder(b);
if (workerToAssign)
{
//BWAPI::Broodwar->printf("VALID WORKER BEING ASSIGNED: %d", workerToAssign->getID());
// TODO: special case of terran building whose worker died mid construction
// send the right click command to the buildingUnit to resume construction
// skip the buildingsAssigned step and push it back into buildingsUnderConstruction
b.builderUnit = workerToAssign;
BWAPI::TilePosition testLocation = getBuildingLocation(b);
if (!testLocation.isValid())
{
continue;
}
b.finalPosition = testLocation;
// reserve this building's space
BuildingPlacer::Instance().reserveTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight());
b.status = BuildingStatus::Assigned;
}
}
}
<file_sep>#include "ScoutManager.h"
#include "ProductionManager.h"
#include "UnitUtil.h"
using namespace UAlbertaBot;
ScoutManager::ScoutManager()
: _scouter1(nullptr)
, _scouter2(nullptr)
, _overlordScout(nullptr)
{
}
ScoutManager & ScoutManager::Instance()
{
static ScoutManager instance;
return instance;
}
void ScoutManager::update()
{
moveScouts();
}
bool ScoutManager::setScout(BWAPI::Unit unit)
{
// if we have a previous worker scout, release it back to the worker manager
if (_scouter1 && _scouter2) return false;
if (_scouter1)_scouter2 = unit;
else _scouter1 = unit;
return true;
}
void ScoutManager::moveScouts()
{
if (!_overlordScout && BWAPI::Broodwar->enemy()->getRace() != BWAPI::Races::Terran)
{
for (auto & unit : BWAPI::Broodwar->self()->getUnits())
{
if (UnitUtil::IsValidUnit(unit) && unit->getType() == BWAPI::UnitTypes::Zerg_Overlord)
{
_overlordScout = unit;
}
}
}
BWTA::BaseLocation * enemyBaseLocation = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy());
if (enemyBaseLocation)
{
if (_overlordScout) Micro::SmartMove(_overlordScout,BWTA::getNearestChokepoint(enemyBaseLocation->getPosition())->getCenter());
if (_scouter1) Micro::SmartMove(_scouter1, BWAPI::Position(enemyBaseLocation->getTilePosition()));
if (_scouter2) Micro::SmartMove(_scouter2, BWAPI::Position(enemyBaseLocation->getTilePosition()));
}
else
{
if (_overlordScout) Micro::SmartMove(_overlordScout, BWAPI::Position(BWAPI::Broodwar->mapWidth() * 16, BWAPI::Broodwar->mapHeight() * 16));
int count = 0;
for (BWTA::BaseLocation * startLocation : BWTA::getStartLocations())
{
if (!BWAPI::Broodwar->isExplored(startLocation->getTilePosition()))
{
if (_scouter1 && !count) Micro::SmartMove(_scouter1, BWAPI::Position(startLocation->getTilePosition()));
if (_scouter2 && count == 1) Micro::SmartMove(_scouter2, BWAPI::Position(startLocation->getTilePosition()));
++count;
}
}
}
}<file_sep>#include "MeleeManager.h"
#include "UnitUtil.h"
//TOMMY
#include "CombatSimulation.h"
using namespace UAlbertaBot;
MeleeManager::MeleeManager()
{
}
void MeleeManager::executeMicro(const BWAPI::Unitset & targets)
{
assignTargetsOld(targets);
}
void MeleeManager::assignTargetsOld(const BWAPI::Unitset & targets)
{
const BWAPI::Unitset & meleeUnits = getUnits();
// figure out targets
BWAPI::Unitset meleeUnitTargets;
for (auto & target : targets)
{
// conditions for targeting
if (!(target->getType().isFlyer()) &&
!(target->isLifted()) &&
!(target->getType() == BWAPI::UnitTypes::Zerg_Larva) &&
!(target->getType() == BWAPI::UnitTypes::Zerg_Egg) &&
target->isVisible())
{
meleeUnitTargets.insert(target);
}
}
// for each meleeUnit
for (auto & meleeUnit : meleeUnits)
{
// if the order is to attack or defend
if (order.getType() == SquadOrderTypes::Attack || order.getType() == SquadOrderTypes::Defend)
{
// run away if we meet the retreat critereon
if (meleeUnitShouldRetreat(meleeUnit, targets))
{
BWAPI::Position fleeTo(BWAPI::Broodwar->self()->getStartLocation());
Micro::SmartMove(meleeUnit, fleeTo);
}
// if there are targets
else if (!meleeUnitTargets.empty())
{
// find the best target for this meleeUnit
BWAPI::Unit target = getTarget(meleeUnit, meleeUnitTargets);
// attack it
Micro::SmartAttackUnit(meleeUnit, target);
}
// if there are no targets
else
{
// if we're not near the order position
if (meleeUnit->getDistance(order.getPosition()) > 100)
{
// move to it
Micro::SmartMove(meleeUnit, order.getPosition());
}
}
}
//NEW
if (order.getType() == SquadOrderTypes::Confuse)
{
// run away if we meet the retreat critereon. this should probably not be used, but it is uncertain
//if (meleeUnitShouldRetreat(meleeUnit, targets))
//{
// BWAPI::Position fleeTo(BWAPI::Broodwar->self()->getStartLocation());
// Micro::SmartMove(meleeUnit, fleeTo);
//}
// if there are targets
// targets contains units in a radius 800 around each unit
/*else*/ if (!meleeUnitTargets.empty())
{
SparCraft::ScoreType score = 0;
CombatSimulation sim;
sim.setCombatUnits(meleeUnit->getPosition(), 1000);
score = sim.simulateCombat();
bool fight = score > 0;
if (fight) // COMBAT SIMULATOR SAYS FIGHT
{
// find the best target for this meleeUnit
BWAPI::Unit target = getTarget(meleeUnit, meleeUnitTargets);
// attack it
Micro::SmartAttackUnit(meleeUnit, target);
_currentRegionVertexIndex[meleeUnit] = -1;
}
else // COMBAT SIMULATOR SAYS KITE.
{
if ((!BWTA::getRegion(meleeUnit->getTilePosition())) ||
(InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy())->getRegion()) == (BWTA::getRegion(meleeUnit->getTilePosition()))) // to do: also move out of enemy base region
{
BWAPI::Position fleeTo(BWAPI::Broodwar->self()->getStartLocation());
Micro::SmartMove(meleeUnit, fleeTo);
_currentRegionVertexIndex[meleeUnit] = -1;
}
else
{
double closestZealotDist = std::numeric_limits<double>::infinity();
BWAPI::Unit closestZealotTarget = nullptr;
for (auto &unit : meleeUnitTargets)
{
if (unit->getType() == BWAPI::UnitTypes::Protoss_Zealot)
{
int distance = meleeUnit->getDistance(unit);
if (!closestZealotTarget || (distance < closestZealotDist))
{
closestZealotDist = distance;
closestZealotTarget = unit;
}
}
}
calculateCurrentRegionVertices2(meleeUnit);
followPerimeter(meleeUnit, closestZealotTarget);
}
}
}
// if there are no targets
else
{
// if we're not near the order position
if (meleeUnit->getDistance(order.getPosition()) > 100)
{
// move to it
Micro::SmartMove(meleeUnit, order.getPosition());
_currentRegionVertexIndex[meleeUnit] = -1;
}
}
}
if (Config::Debug::DrawUnitTargetInfo)
{
BWAPI::Broodwar->drawLineMap(meleeUnit->getPosition().x, meleeUnit->getPosition().y,
meleeUnit->getTargetPosition().x, meleeUnit->getTargetPosition().y, Config::Debug::ColorLineTarget);
}
}
}
std::pair<BWAPI::Unit, BWAPI::Unit> MeleeManager::findClosestUnitPair(const BWAPI::Unitset & attackers, const BWAPI::Unitset & targets)
{
std::pair<BWAPI::Unit, BWAPI::Unit> closestPair(nullptr, nullptr);
double closestDistance = std::numeric_limits<double>::max();
for (auto & attacker : attackers)
{
BWAPI::Unit target = getTarget(attacker, targets);
double dist = attacker->getDistance(attacker);
if (!closestPair.first || (dist < closestDistance))
{
closestPair.first = attacker;
closestPair.second = target;
closestDistance = dist;
}
}
return closestPair;
}
// get a target for the meleeUnit to attack
BWAPI::Unit MeleeManager::getTarget(BWAPI::Unit meleeUnit, const BWAPI::Unitset & targets)
{
int highPriority = 0;
double closestDist = std::numeric_limits<double>::infinity();
BWAPI::Unit closestTarget = nullptr;
// for each target possiblity
for (auto & unit : targets)
{
int priority = getAttackPriority(meleeUnit, unit);
int distance = meleeUnit->getDistance(unit);
// if it's a higher priority, or it's closer, set it
if (!closestTarget || (priority > highPriority) || (priority == highPriority && distance < closestDist))
{
closestDist = distance;
highPriority = priority;
closestTarget = unit;
}
}
return closestTarget;
}
// get the attack priority of a type in relation to a zergling
int MeleeManager::getAttackPriority(BWAPI::Unit attacker, BWAPI::Unit unit)
{
BWAPI::UnitType type = unit->getType();
if (attacker->getType() == BWAPI::UnitTypes::Protoss_Dark_Templar
&& unit->getType() == BWAPI::UnitTypes::Terran_Missile_Turret
&& (BWAPI::Broodwar->self()->deadUnitCount(BWAPI::UnitTypes::Protoss_Dark_Templar) == 0))
{
return 13;
}
if (attacker->getType() == BWAPI::UnitTypes::Protoss_Dark_Templar && unit->getType().isWorker())
{
return 12;
}
// highest priority is something that can attack us or aid in combat
if (type == BWAPI::UnitTypes::Terran_Bunker)
{
return 11;
}
else if (type == BWAPI::UnitTypes::Terran_Medic ||
(type.groundWeapon() != BWAPI::WeaponTypes::None && !type.isWorker()) ||
type == BWAPI::UnitTypes::Terran_Bunker ||
type == BWAPI::UnitTypes::Protoss_High_Templar ||
type == BWAPI::UnitTypes::Protoss_Reaver ||
(type.isWorker() && unitNearChokepoint(unit)))
{
return 10;
}
// next priority is worker
else if (type.isWorker())
{
return 9;
}
// next is special buildings
else if (type == BWAPI::UnitTypes::Zerg_Spawning_Pool)
{
return 5;
}
// next is special buildings
else if (type == BWAPI::UnitTypes::Protoss_Pylon)
{
return 5;
}
// next is buildings that cost gas
else if (type.gasPrice() > 0)
{
return 4;
}
else if (type.mineralPrice() > 0)
{
return 3;
}
// then everything else
else
{
return 1;
}
}
BWAPI::Unit MeleeManager::closestMeleeUnit(BWAPI::Unit target, const BWAPI::Unitset & meleeUnitsToAssign)
{
double minDistance = 0;
BWAPI::Unit closest = nullptr;
for (auto & meleeUnit : meleeUnitsToAssign)
{
double distance = meleeUnit->getDistance(target);
if (!closest || distance < minDistance)
{
minDistance = distance;
closest = meleeUnit;
}
}
return closest;
}
bool MeleeManager::meleeUnitShouldRetreat(BWAPI::Unit meleeUnit, const BWAPI::Unitset & targets)
{
// terran don't regen so it doesn't make any sense to retreat
if (meleeUnit->getType().getRace() == BWAPI::Races::Terran)
{
return false;
}
// we don't want to retreat the melee unit if its shields or hit points are above the threshold set in the config file
// set those values to zero if you never want the unit to retreat from combat individually
if (meleeUnit->getShields() > Config::Micro::RetreatMeleeUnitShields || meleeUnit->getHitPoints() > Config::Micro::RetreatMeleeUnitHP)
{
return false;
}
// if there is a ranged enemy unit within attack range of this melee unit then we shouldn't bother retreating since it could fire and kill it anyway
for (auto & unit : targets)
{
int groundWeaponRange = unit->getType().groundWeapon().maxRange();
if (groundWeaponRange >= 64 && unit->getDistance(meleeUnit) < groundWeaponRange)
{
return false;
}
}
return true;
}
// still has bug in it somewhere, use Old version
void MeleeManager::assignTargetsNew(const BWAPI::Unitset & targets)
{
const BWAPI::Unitset & meleeUnits = getUnits();
// figure out targets
BWAPI::Unitset meleeUnitTargets;
for (auto & target : targets)
{
// conditions for targeting
if (!(target->getType().isFlyer()) &&
!(target->isLifted()) &&
!(target->getType() == BWAPI::UnitTypes::Zerg_Larva) &&
!(target->getType() == BWAPI::UnitTypes::Zerg_Egg) &&
target->isVisible())
{
meleeUnitTargets.insert(target);
}
}
BWAPI::Unitset meleeUnitsToAssign(meleeUnits);
std::map<BWAPI::Unit, int> attackersAssigned;
for (auto & unit : meleeUnitTargets)
{
attackersAssigned[unit] = 0;
}
int smallThreshold = BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Zerg ? 3 : 1;
int bigThreshold = BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Zerg ? 12 : 3;
// keep assigning targets while we have attackers and targets remaining
while (!meleeUnitsToAssign.empty() && !meleeUnitTargets.empty())
{
auto attackerAssignment = findClosestUnitPair(meleeUnitsToAssign, meleeUnitTargets);
BWAPI::Unit & attacker = attackerAssignment.first;
BWAPI::Unit & target = attackerAssignment.second;
UAB_ASSERT_WARNING(attacker, "We should have chosen an attacker!");
if (!attacker)
{
break;
}
if (!target)
{
Micro::SmartMove(attacker, order.getPosition());
continue;
}
Micro::SmartAttackUnit(attacker, target);
// update the number of units assigned to attack the target we found
int & assigned = attackersAssigned[attackerAssignment.second];
assigned++;
// if it's a small / fast unit and there's more than 2 things attacking it already, don't assign more
if ((target->getType().isWorker() || target->getType() == BWAPI::UnitTypes::Zerg_Zergling) && (assigned >= smallThreshold))
{
meleeUnitTargets.erase(target);
}
// if it's a building and there's more than 10 things assigned to it already, don't assign more
else if (assigned > bigThreshold)
{
meleeUnitTargets.erase(target);
}
meleeUnitsToAssign.erase(attacker);
}
// if there's no targets left, attack move to the order destination
if (meleeUnitTargets.empty())
{
for (auto & unit : meleeUnitsToAssign)
{
if (unit->getDistance(order.getPosition()) > 100)
{
// move to it
Micro::SmartMove(unit, order.getPosition());
BWAPI::Broodwar->drawLineMap(unit->getPosition(), order.getPosition(), BWAPI::Colors::Yellow);
}
}
}
}
//PAST THIS POINT IS TOMMY
void MeleeManager::setUnits(const BWAPI::Unitset & u)
{
_units = u;
for (auto &unit : _units)
{
if (_currentRegionVertexIndex.find(unit) == _currentRegionVertexIndex.end()) {
_currentRegionVertexIndex[unit] = -1;
}
}
}
void MeleeManager::calculateCurrentRegionVertices(BWAPI::Unit unit)
{
BWTA::Region* currentRegion = BWTA::getRegion(unit->getTilePosition());
//UAB_ASSERT_WARNING(enemyRegion, "We should have an enemy region if we are fleeing");
if (!currentRegion)
{
UAB_ASSERT_WARNING(currentRegion, "We should have an enemy region if we are fleeing"); // NEW
return;
}
const BWAPI::Position basePosition = BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation());
const std::vector<BWAPI::TilePosition> & closestTobase = MapTools::Instance().getClosestTilesTo(basePosition);
std::set<BWAPI::Position> unsortedVertices;
// check each tile position
for (size_t i(0); i < closestTobase.size(); ++i)
{
const BWAPI::TilePosition & tp = closestTobase[i];
if (BWTA::getRegion(tp) != currentRegion)
{
continue;
}
// a tile is 'surrounded' if
// 1) in all 4 directions there's a tile position in the current region
// 2) in all 4 directions there's a buildable tile
bool surrounded = true;
if (BWTA::getRegion(BWAPI::TilePosition(tp.x + 1, tp.y)) != currentRegion || !BWAPI::Broodwar->isBuildable(BWAPI::TilePosition(tp.x + 1, tp.y))
|| BWTA::getRegion(BWAPI::TilePosition(tp.x, tp.y + 1)) != currentRegion || !BWAPI::Broodwar->isBuildable(BWAPI::TilePosition(tp.x, tp.y + 1))
|| BWTA::getRegion(BWAPI::TilePosition(tp.x - 1, tp.y)) != currentRegion || !BWAPI::Broodwar->isBuildable(BWAPI::TilePosition(tp.x - 1, tp.y))
|| BWTA::getRegion(BWAPI::TilePosition(tp.x, tp.y - 1)) != currentRegion || !BWAPI::Broodwar->isBuildable(BWAPI::TilePosition(tp.x, tp.y - 1)))
{
surrounded = false;
}
// push the tiles that aren't surrounded
if (!surrounded && BWAPI::Broodwar->isBuildable(tp))
{
if (Config::Debug::DrawScoutInfo)
{
int x1 = tp.x * 32 + 2;
int y1 = tp.y * 32 + 2;
int x2 = (tp.x + 1) * 32 - 2;
int y2 = (tp.y + 1) * 32 - 2;
BWAPI::Broodwar->drawTextMap(x1 + 3, y1 + 2, "%d", MapTools::Instance().getGroundDistance(BWAPI::Position(tp), basePosition));
BWAPI::Broodwar->drawBoxMap(x1, y1, x2, y2, BWAPI::Colors::Green, false);
}
unsortedVertices.insert(BWAPI::Position(tp) + BWAPI::Position(16, 16));
}
}
std::vector<BWAPI::Position> sortedVertices;
BWAPI::Position current = *unsortedVertices.begin();
_currentRegionVertices[unit].push_back(current);
unsortedVertices.erase(current);
// while we still have unsorted vertices left, find the closest one remaining to current
while (!unsortedVertices.empty())
{
double bestDist = 1000000;
BWAPI::Position bestPos;
for (const BWAPI::Position & pos : unsortedVertices)
{
double dist = pos.getDistance(current);
if (dist < bestDist)
{
bestDist = dist;
bestPos = pos;
}
}
current = bestPos;
sortedVertices.push_back(bestPos);
unsortedVertices.erase(bestPos);
}
// let's close loops on a threshold, eliminating death grooves
int distanceThreshold = 100;
while (true)
{
// find the largest index difference whose distance is less than the threshold
int maxFarthest = 0;
int maxFarthestStart = 0;
int maxFarthestEnd = 0;
// for each starting vertex
for (int i(0); i < (int)sortedVertices.size(); ++i)
{
int farthest = 0;
int farthestIndex = 0;
// only test half way around because we'll find the other one on the way back
for (size_t j(1); j < sortedVertices.size() / 2; ++j)
{
int jindex = (i + j) % sortedVertices.size();
if (sortedVertices[i].getDistance(sortedVertices[jindex]) < distanceThreshold)
{
farthest = j;
farthestIndex = jindex;
}
}
if (farthest > maxFarthest)
{
maxFarthest = farthest;
maxFarthestStart = i;
maxFarthestEnd = farthestIndex;
}
}
// stop when we have no long chains within the threshold
if (maxFarthest < 4)
{
break;
}
double dist = sortedVertices[maxFarthestStart].getDistance(sortedVertices[maxFarthestEnd]);
std::vector<BWAPI::Position> temp;
for (size_t s(maxFarthestEnd); s != maxFarthestStart; s = (s + 1) % sortedVertices.size())
{
temp.push_back(sortedVertices[s]);
}
sortedVertices = temp;
}
_currentRegionVertices[unit] = sortedVertices;
}
int MeleeManager::getClosestVertexIndex(BWAPI::Unit unit)
{
int closestIndex = -1;
double closestDistance = 10000000;
//BWAPI::Broodwar->printf((std::to_string(_currentRegionVertices[unit].size())).c_str()); // debug. seems to be OK
for (size_t i(0); i < _currentRegionVertices[unit].size(); ++i)
{
double dist = unit->getDistance(_currentRegionVertices[unit][i]);
if (dist < closestDistance)
{
closestDistance = dist;
closestIndex = i;
}
}
return closestIndex;
}
BWAPI::Position MeleeManager::getFleePosition(BWAPI::Unit unit, BWAPI::Unit enemy)
{
UAB_ASSERT_WARNING(!_currentRegionVertices[unit].empty(), "We should have an enemy region vertices if we are fleeing");
BWTA::BaseLocation * enemyBaseLocation = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy());
// if this is the first flee, we will not have a previous perimeter index
if (_currentRegionVertexIndex[unit] == -1)
{
// so return the closest position in the polygon
int closestPolygonIndex = getClosestVertexIndex(unit);
//BWAPI::Broodwar->printf((std::to_string(closestPolygonIndex)).c_str());
UAB_ASSERT_WARNING(closestPolygonIndex != -1, "Couldn't find a closest vertex"); // changed from != to ==
if (closestPolygonIndex == -1)
{
//BWAPI::Broodwar->printf("wtf"); // debug
return BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation());
}
else
{
// set the current index so we know how to iterate if we are still fleeing later
_currentRegionVertexIndex[unit] = closestPolygonIndex;
return _currentRegionVertices[unit][closestPolygonIndex];
}
}
// if we are still fleeing from the previous frame, get the next location if we are close enough
else
{
double distanceFromCurrentVertex = _currentRegionVertices[unit][_currentRegionVertexIndex[unit]].getDistance(unit->getPosition());
// keep going to the next vertex in the perimeter until we get to one we're far enough from to issue another move command
// cycle through vertices clockwise or counterclockwise depending on where the enemy is
// THE FOLLOWING CODE SOMETIMES IMPROVES PATHING BUT ALSO MAY FAIL PATHING OR CAUSE CRASHES
//int posDist = enemy->getDistance(_currentRegionVertices[unit][(_currentRegionVertexIndex[unit] + 1) % _currentRegionVertices[unit].size()]);
//int negDist = enemy->getDistance(_currentRegionVertices[unit][(_currentRegionVertexIndex[unit] - 1) % _currentRegionVertices[unit].size()]);
//if (posDist >= negDist)
//{
while (distanceFromCurrentVertex < 192)
{
_currentRegionVertexIndex[unit] = (_currentRegionVertexIndex[unit] + 1) % _currentRegionVertices[unit].size();
distanceFromCurrentVertex = _currentRegionVertices[unit][_currentRegionVertexIndex[unit]].getDistance(unit->getPosition());
}
//}
//else
//{
// while (distanceFromCurrentVertex < 192)
// {
// _currentRegionVertexIndex[unit] = (_currentRegionVertexIndex[unit] - 1) % _currentRegionVertices[unit].size();
// distanceFromCurrentVertex = _currentRegionVertices[unit][_currentRegionVertexIndex[unit]].getDistance(unit->getPosition());
// }
//}
return _currentRegionVertices[unit][_currentRegionVertexIndex[unit]];
}
}
void MeleeManager::followPerimeter(BWAPI::Unit unit, BWAPI::Unit enemy)
{
BWAPI::Position fleeTo = getFleePosition(unit, enemy);
if (Config::Debug::DrawScoutInfo)
{
BWAPI::Broodwar->drawCircleMap(fleeTo, 5, BWAPI::Colors::Red, true);
}
Micro::SmartMove(unit, fleeTo);
}
// 2ND VERSION OF REGION KITE
void MeleeManager::calculateCurrentRegionVertices2(BWAPI::Unit unit)
{
BWTA::Region* currentRegion = BWTA::getRegion(unit->getTilePosition());
//UAB_ASSERT_WARNING(enemyRegion, "We should have an enemy region if we are fleeing");
if (!currentRegion)
{
UAB_ASSERT_WARNING(currentRegion, "We should have an enemy region if we are fleeing"); // NEW
return;
}
_currentRegionVertices[unit] = currentRegion->getPolygon();
}
/* CURRENT BEST ITERATION OF ZERG KITING
if (!meleeUnitTargets.empty())
{
SparCraft::ScoreType score = 0;
CombatSimulation sim;
sim.setCombatUnits(meleeUnit->getPosition(), 1000);
score = sim.simulateCombat();
bool fight = score > 0;
if (fight) // COMBAT SIMULATOR SAYS FIGHT
{
// find the best target for this meleeUnit
BWAPI::Unit target = getTarget(meleeUnit, meleeUnitTargets);
// attack it
Micro::SmartAttackUnit(meleeUnit, target);
}
else // COMBAT SIMULATOR SAYS KITE
{
// attempt to prevent issuing too many move commands
if (BWAPI::Broodwar->getFrameCount() % 30 != 0)
{
return;
}
double closestZealotDist = std::numeric_limits<double>::infinity();
BWAPI::Unit closestZealotTarget = nullptr;
for (auto &unit : targets)
{
if (unit->getType() == BWAPI::UnitTypes::Protoss_Zealot)
{
int distance = meleeUnit->getDistance(unit);
if (!closestZealotTarget || (distance < closestZealotDist))
{
closestZealotDist = distance;
closestZealotTarget = unit;
}
}
}
// generate random vector that: moves 800u away from the zealot,
// does not come within 500 units of our base, and is walkable
// TO-DO: prevent reissuing a movement command until the prior is complete
BWAPI::Position kiteTo;
int baseDist = meleeUnit->getDistance(InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->self())->getPosition());
int distX = closestZealotTarget->getPosition().x - meleeUnit->getPosition().x;
int distY = closestZealotTarget->getPosition().y - meleeUnit->getPosition().y;
double distAngle = (acos(distX / (sqrt((distX*distX) + (distY*distY))))) * 180 / 3.141593;
bool inMainBase = true;
double distFromBase;
int randAngle;
int newX;
int newY;
while (inMainBase)
{
do
{
randAngle = (rand() % 180) + 90 + distAngle;
newY = 800 * sin(randAngle * 3.141593 / 180);
newX = 800 * cos(randAngle * 3.141593 / 180);
newY += meleeUnit->getPosition().y;
newX += meleeUnit->getPosition().x;
kiteTo = BWAPI::Point<int, 1>::Point(static_cast<int>(newX), static_cast<int>(newY));
} while (!checkPositionWalkable2(kiteTo));
distFromBase = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->self())->getPosition().getApproxDistance(kiteTo);
if (distFromBase > 500) { inMainBase = false; }
}
Micro::SmartMove(meleeUnit, kiteTo);
}
*/
/* RANDOM CODE FOR ZERG KITING
else // COMBAT SIMULATOR SAYS KITE
{
if (regionKiting) // kiting type 1: new
{
double closestZealotDist = std::numeric_limits<double>::infinity();
BWAPI::Unit closestZealotTarget = nullptr;
for (auto &unit : targets)
{
if (unit->getType() == BWAPI::UnitTypes::Protoss_Zealot)
{
int distance = meleeUnit->getDistance(unit);
if (!closestZealotTarget || (distance < closestZealotDist))
{
closestZealotDist = distance;
closestZealotTarget = unit;
}
}
}
BWAPI::Position unitPos = meleeUnit->getPosition();
BWAPI::TilePosition unitTilePos = BWAPI::Point<int, 32>::Point(static_cast<int>(unitPos.x / 32), static_cast<int>(unitPos.y / 32));
BWTA::Region* unitRegion = BWTA::getRegion(unitTilePos);
// if you aren't that close to the zealot (1300 units away), move 50 units in a random direction away from base towards the zealot
if ((closestZealotTarget) && (closestZealotDist > 1300))
{
// this block has code for running away from our base
BWAPI::Position kiteTo;
int baseDist = meleeUnit->getDistance(InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->self())->getPosition());
int zealotDist = meleeUnit->getDistance(closestZealotTarget);
bool toMainBase = true;
bool toZealot = false;
int randAngle;
int newX;
int newY;
int newBaseDist;
int newZealotDist;
while (toMainBase || (!toZealot))
{
do
{
randAngle = rand() % 360;
newY = 50 * sin(randAngle * 3.141593 / 180);
newX = 50 * cos(randAngle * 3.141593 / 180);
newY += unitPos.y;
newX += unitPos.x;
kiteTo = BWAPI::Point<int, 1>::Point(static_cast<int>(newX), static_cast<int>(newY));
} while (!checkPositionWalkable2(kiteTo));
newBaseDist = kiteTo.getApproxDistance(InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->self())->getPosition());
newZealotDist = closestZealotTarget->getDistance(kiteTo);
if (newBaseDist > baseDist) { toMainBase = false; }
if (newZealotDist < zealotDist) { toZealot = true; }
}
Micro::SmartMove(meleeUnit, kiteTo);
}
else if (!unitRegion) // standing in chokepoint
{
Micro::SmartMove(meleeUnit, BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation()));
}
// if Zealot is found, move to the nearest region polygon position that is away from the zealot
// then just run around the polygon
else if (closestZealotTarget)
{
// this block has code for just not going in the BWTA::Region of our base
BWAPI::Position kiteTo;
BWAPI::Position basePosition = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->self())->getPosition();
int zealotDist = meleeUnit->getDistance(closestZealotTarget);
bool inMainBase = true;
bool toZealot = true;
int randAngle;
int newX;
int newY;
int newBaseDist;
int newZealotDist;
BWTA::Region* baseRegion;
BWTA::Region* kiteToRegion;
BWAPI::TilePosition kiteToTile;
while (inMainBase || toZealot)
{
do
{
randAngle = rand() % 360;
newY = 950 * sin(randAngle * 3.141593 / 180);
newX = 950 * cos(randAngle * 3.141593 / 180);
newY += unitPos.y;
newX += unitPos.x;
kiteTo = BWAPI::Point<int, 1>::Point(static_cast<int>(newX), static_cast<int>(newY));
kiteToTile = BWAPI::Point<int, 32>::Point(static_cast<int>(kiteTo.x / 32), static_cast<int>(kiteTo.y / 32));
} while ((!checkPositionWalkable2(kiteTo)) ||
((BWTA::getGroundDistance(unitTilePos, kiteToTile)) > (kiteTo.getApproxDistance(unitPos) + 250))); // trying to make sure that you aren't walking around terrain
// use of MapTools getGroundDistance so frequently is iffy
// try BWTA getGroundDistance
baseRegion = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->self())->getRegion();
kiteToRegion = BWTA::getRegion(kiteToTile);
newZealotDist = closestZealotTarget->getDistance(kiteTo);
if (baseRegion != kiteToRegion) { inMainBase = false; }
if (newZealotDist > zealotDist) { toZealot = false; }
}
Micro::SmartMove(meleeUnit, kiteTo);
}
// if no Zealots, behave like an Attack unit
else
{
// find the best target for this meleeUnit
BWAPI::Unit target = getTarget(meleeUnit, meleeUnitTargets);
// attack it
Micro::SmartAttackUnit(meleeUnit, target);
}
}
else // kiting type 2
{
// assuming that Confuse strategy is not used if non-Zealot combat units are seen
// search meleeUnitTargets for nearest Zealot
double closestZealotDist = std::numeric_limits<double>::infinity();
BWAPI::Unit closestZealotTarget = nullptr;
for (auto &unit : targets)
{
if (unit->getType() == BWAPI::UnitTypes::Protoss_Zealot)
{
int distance = meleeUnit->getDistance(unit);
if (!closestZealotTarget || (distance < closestZealotDist))
{
closestZealotDist = distance;
closestZealotTarget = unit;
}
}
}
// if you aren't that close to the zealot (1300 units away), move 50 units in a random direction away from base towards the zealot
if ((closestZealotTarget) && (closestZealotDist > 1300))
{
// this block has code for running away from our base
BWAPI::Position unitPos = meleeUnit->getPosition();
BWAPI::Position kiteTo;
int baseDist = meleeUnit->getDistance(InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->self())->getPosition());
int zealotDist = meleeUnit->getDistance(closestZealotTarget);
bool toMainBase = true;
bool toZealot = false;
int randAngle;
int newX;
int newY;
int newBaseDist;
int newZealotDist;
while (toMainBase || (!toZealot))
{
do
{
randAngle = rand() % 360;
newY = 50 * sin(randAngle * 3.141593 / 180);
newX = 50 * cos(randAngle * 3.141593 / 180);
newY += unitPos.y;
newX += unitPos.x;
kiteTo = BWAPI::Point<int, 1>::Point(static_cast<int>(newX), static_cast<int>(newY));
} while (!checkPositionWalkable2(kiteTo));
newBaseDist = kiteTo.getApproxDistance(InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->self())->getPosition());
newZealotDist = closestZealotTarget->getDistance(kiteTo);
if (newBaseDist > baseDist) { toMainBase = false; }
if (newZealotDist < zealotDist) { toZealot = true; }
}
Micro::SmartMove(meleeUnit, kiteTo);
}
// if Zealot is found, get a position to flee to that increases distance to the main base and the nearest zealot
// IMPORTANT: fleeing distance must be <= simulator radius == order radius. current flee = 950
else if (closestZealotTarget)
{
// this block has code for just not going in the BWTA::Region of our base
BWAPI::Position unitPos = meleeUnit->getPosition();
BWAPI::Position kiteTo;
BWAPI::Position basePosition = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->self())->getPosition();
int zealotDist = meleeUnit->getDistance(closestZealotTarget);
bool inMainBase = true;
bool toZealot = true;
int randAngle;
int newX;
int newY;
int newBaseDist;
int newZealotDist;
BWTA::Region* baseRegion;
BWTA::Region* kiteToRegion;
BWAPI::TilePosition unitTilePos = BWAPI::Point<int, 32>::Point(static_cast<int>(unitPos.x/32), static_cast<int>(unitPos.y/32));
BWAPI::TilePosition kiteToTile;
while (inMainBase || toZealot)
{
do
{
randAngle = rand() % 360;
newY = 950 * sin(randAngle * 3.141593 / 180);
newX = 950 * cos(randAngle * 3.141593 / 180);
newY += unitPos.y;
newX += unitPos.x;
kiteTo = BWAPI::Point<int, 1>::Point(static_cast<int>(newX), static_cast<int>(newY));
kiteToTile = BWAPI::Point<int, 32>::Point(static_cast<int>(kiteTo.x/32), static_cast<int>(kiteTo.y/32));
} while ((!checkPositionWalkable2(kiteTo)) ||
((BWTA::getGroundDistance(unitTilePos, kiteToTile)) > (kiteTo.getApproxDistance(unitPos) + 250))); // trying to make sure that you aren't walking around terrain
// use of MapTools getGroundDistance so frequently is iffy
// try BWTA getGroundDistance
baseRegion = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->self())->getRegion();
kiteToRegion = BWTA::getRegion(kiteToTile);
newZealotDist = closestZealotTarget->getDistance(kiteTo);
if (baseRegion != kiteToRegion) { inMainBase = false; }
if (newZealotDist > zealotDist) { toZealot = false; }
}
Micro::SmartMove(meleeUnit, kiteTo);
}
// if no Zealots, behave like an Attack unit
else
{
// find the best target for this meleeUnit
BWAPI::Unit target = getTarget(meleeUnit, meleeUnitTargets);
// attack it
Micro::SmartAttackUnit(meleeUnit, target);
}
}
}
*/<file_sep>#include "ScoutManager.h"
#include "ProductionManager.h"
#include "UnitUtil.h"
using namespace UAlbertaBot;
ScoutManager::ScoutManager()
: _scouter1(nullptr)
, _scouter2(nullptr)
, _overlordScout(nullptr)
, _workerScout(nullptr)
, _ninjaBaseLocation(BWAPI::TilePosition(0, 0))
, _enemyRamp(BWAPI::Position(0, 0))
{
}
ScoutManager & ScoutManager::Instance()
{
static ScoutManager instance;
return instance;
}
void ScoutManager::update()
{
moveScouts();
}
bool ScoutManager::setScout(BWAPI::Unit unit)
{
// if we have a previous worker scout, release it back to the worker manager
if (_scouter1 && _scouter2) return false;
if (_scouter1)_scouter2 = unit;
else _scouter1 = unit;
return true;
}
void ScoutManager::setWorkerScout(BWAPI::Unit unit)
{
// if we have a previous worker scout, release it back to the worker manager
if (_workerScout)
{
WorkerManager::Instance().finishedWithWorker(_workerScout);
}
_workerScout = unit;
WorkerManager::Instance().setScoutWorker(_workerScout);
}
void ScoutManager::moveScouts()
{
if (!_overlordScout && BWAPI::Broodwar->enemy()->getRace() != BWAPI::Races::Terran)
{
for (auto & unit : BWAPI::Broodwar->self()->getUnits())
{
if (UnitUtil::IsValidUnit(unit) && unit->getType() == BWAPI::UnitTypes::Zerg_Overlord)
{
_overlordScout = unit;
}
}
}
BWTA::BaseLocation * enemyBaseLocation = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy());
if (enemyBaseLocation)
{
if (_overlordScout) {
if (_enemyRamp == BWAPI::Position(0, 0)) _enemyRamp = getEnemyRamp();
Micro::SmartMove(_overlordScout, _enemyRamp);
}
if (_scouter1) Micro::SmartMove(_scouter1, BWAPI::Position(enemyBaseLocation->getTilePosition()));
if (_scouter2) Micro::SmartMove(_scouter2, BWAPI::Position(enemyBaseLocation->getTilePosition()));
if (_workerScout) buildNinjaBase();
}
else
{
if (_overlordScout) Micro::SmartMove(_overlordScout, BWAPI::Position(BWAPI::Broodwar->mapWidth() * 16, BWAPI::Broodwar->mapHeight() * 16));
int count = 0;
for (BWTA::BaseLocation * startLocation : BWTA::getStartLocations())
{
if (!BWAPI::Broodwar->isExplored(startLocation->getTilePosition()))
{
if (_scouter1 && !count) Micro::SmartMove(_scouter1, BWAPI::Position(startLocation->getTilePosition()));
if (_scouter2 && count == 1) Micro::SmartMove(_scouter2, BWAPI::Position(startLocation->getTilePosition()));
++count;
}
}
}
}
void ScoutManager::buildNinjaBase()
{
if (_ninjaBaseLocation == BWAPI::TilePosition(0, 0)) _ninjaBaseLocation = getFarthestPoint();
if (BWAPI::Broodwar->self()->minerals() >= 300 && _workerScout->getDistance(BWAPI::Position(_ninjaBaseLocation)) <= 100) _workerScout->build(BWAPI::UnitTypes::Zerg_Hatchery, _ninjaBaseLocation);
else Micro::SmartMove(_workerScout, BWAPI::Position(_ninjaBaseLocation));
}
BWAPI::TilePosition ScoutManager::getFarthestPoint()
{
double distance = 1;
double expDist = 999999.0;
BWTA::BaseLocation * farthestLocation;
BWTA::BaseLocation * myExpansion;
BWTA::BaseLocation * enemyBaseLocation = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy());
const std::set<BWTA::BaseLocation*, std::less<BWTA::BaseLocation*>> locations = BWTA::getBaseLocations();
for (auto x : locations)
{
double myDist = BWTA::getGroundDistance(BWTA::getStartLocation(BWAPI::Broodwar->self())->getTilePosition(), x->getTilePosition());
if (myDist >= 1 && myDist < expDist && !x->isMineralOnly() && x != BWTA::getStartLocation(BWAPI::Broodwar->self()))
{
myExpansion = x;
expDist = myDist;
}
}
for (auto x : locations)
{
double myDist = BWTA::getGroundDistance(enemyBaseLocation->getTilePosition(), x->getTilePosition());
if (myDist >= 1 && !x->isMineralOnly() && x != enemyBaseLocation && x != BWTA::getStartLocation(BWAPI::Broodwar->self()) && x != myExpansion && myDist > distance)
{
distance = myDist;
farthestLocation = x;
}
}
BuildingManager::Instance().createdHatcheriesVector[1] = farthestLocation->getTilePosition();
return farthestLocation->getTilePosition();
}
BWAPI::Position ScoutManager::getEnemyRamp(){
std::set<BWTA::Chokepoint *> chokePoints = BWTA::getChokepoints();
double lowestDistance = 999999.0;
double lowestDistance2 = 999999.0;
double expDist = 999999.0;
BWAPI::Position rampPosition;
BWTA::BaseLocation * expansion;
BWTA::BaseLocation * enemyBaseLocation = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy());
const std::set<BWTA::BaseLocation*, std::less<BWTA::BaseLocation*>> locations = BWTA::getBaseLocations();
for (auto x : locations)
{
double myDist = BWTA::getGroundDistance(enemyBaseLocation->getTilePosition(), x->getTilePosition());
if (myDist >= 1 && myDist < expDist && !x->isMineralOnly() && x != enemyBaseLocation)
{
expansion = x;
expDist = myDist;
}
}
for (auto x : chokePoints)
{
double distance1 = BWTA::getGroundDistance(expansion->getTilePosition(), BWAPI::TilePosition(x->getCenter()));
double distance2 = BWTA::getGroundDistance(enemyBaseLocation->getTilePosition(), BWAPI::TilePosition(x->getCenter()));
double sum = distance1 + distance2;
if (sum < lowestDistance)
{
lowestDistance = sum;
rampPosition = x->getCenter();
}
}
return rampPosition;
}<file_sep>#pragma once
#include "Common.h"
#include "BWTA.h"
#include "BuildOrderQueue.h"
#include "InformationManager.h"
#include "WorkerManager.h"
#include "BuildOrder.h"
namespace UAlbertaBot
{
typedef std::pair<MetaType, size_t> MetaPair;
typedef std::vector<MetaPair> MetaPairVector;
struct Strategy
{
std::string _name;
BWAPI::Race _race;
int _wins;
int _losses;
BuildOrder _buildOrder;
Strategy()
: _name("None")
, _race(BWAPI::Races::None)
, _wins(0)
, _losses(0)
{
}
Strategy(const std::string & name, const BWAPI::Race & race, const BuildOrder & buildOrder)
: _name(name)
, _race(race)
, _wins(0)
, _losses(0)
, _buildOrder(buildOrder)
{
}
};
class StrategyManager
{
StrategyManager();
BWAPI::Race _selfRace;
BWAPI::Race _enemyRace;
std::map<std::string, Strategy> _strategies;
int _totalGamesPlayed;
const BuildOrder _emptyBuildOrder;
bool _isLastBuildOrder;
void writeResults();
const int getScore(BWAPI::Player player) const;
const double getUCBValue(const size_t & strategy) const;
//const bool shouldExpandNow() const;
const MetaPairVector getProtossBuildOrderGoal() const;
const MetaPairVector getTerranBuildOrderGoal() const;
const MetaPairVector getZergBuildOrderGoal() const;
//TOMMY
mutable int macroHatchCount;
const bool shouldMakeMacroHatchery() const;
public:
static StrategyManager & Instance();
void onEnd(const bool isWinner);
void addStrategy(const std::string & name, Strategy & strategy);
void setLearnedStrategy();
void readResults();
const bool regroup(int numInRadius);
const bool rushDetected();
const int defendWithWorkers();
const MetaPairVector getBuildOrderGoal();
const BuildOrder & getOpeningBookBuildOrder() const;
const BuildOrder & getAdaptiveBuildOrder() const;
//TOMMY
int getMacroHatchCount();
void removeMacroHatch();
// returns map corresponding to units that need to be made and how many
// current control: in prod manager, if creep colonies or sunkens are currently in the queue, don't call this
// when testing, try each version and see which works better
std::map<BWAPI::UnitType, int> shouldBuildSunkens() const;
std::map<BWAPI::UnitType, int> shouldBuildSunkens2() const;
bool timeToAttack = true;
const bool shouldExpandNow() const;
const bool isSpireBuilding() const;
};
}<file_sep>#pragma once
#include "Common.h"
#include "MapGrid.h"
#ifdef USING_VISUALIZATION_LIBRARIES
#include "Visualizer.h"
#endif
#include "..\..\SparCraft\source\GameState.h"
#include "..\..\SparCraft\source\Game.h"
#include "..\..\SparCraft\source\Unit.h"
#include "..\..\SparCraft\source\AllPlayers.h"
#include "InformationManager.h"
namespace UAlbertaBot
{
class CombatSimulation
{
SparCraft::GameState state;
public:
CombatSimulation();
void setCombatUnits(const BWAPI::Position & center, const int radius); // adds to a simulation all units in a radius
SparCraft::ScoreType simulateCombat();
const SparCraft::Unit getSparCraftUnit(const UnitInfo & ui) const;
const SparCraft::Unit getSparCraftUnit(BWAPI::Unit unit) const;
const SparCraft::GameState & getSparCraftState() const;
const SparCraft::IDType getSparCraftPlayerID(BWAPI::Player player) const;
void logState(const SparCraft::GameState & state);
//NEW
void addToState(BWAPI::Unit unit); // adds to a simulation a single unit
void addToState(const UnitInfo &ui);
void finishMoving(); // call right before simulating combat
};
}
// simple way to use the simulator:
// SparCraft::ScoreType score = 0;
// CombatSimulation sim;
// sim.setCombatUnits(unit->getPosition(), Config::Micro::CombatRegroupRadius); (or any position and radius)
// score = sim.simulateCombat();
// bool fight = score > 0;<file_sep>#pragma once;
#include <Common.h>
#include "MicroManager.h"
namespace UAlbertaBot
{
class MicroManager;
class MeleeManager : public MicroManager
{
//TOMMY
//bool regionKiting = true;
//TOMMY
std::map<BWAPI::Unit, int> _currentRegionVertexIndex; // current position to flee to. must start at -1 and be reset to -1 when unit stops fleeing
std::map<BWAPI::Unit, std::vector<BWAPI::Position>> _currentRegionVertices; // holds border of region that each unit is currently in
//TOMMY
int getClosestVertexIndex(BWAPI::Unit unit); // edge of current region closest to unit
BWAPI::Position getFleePosition(BWAPI::Unit unit, BWAPI::Unit enemy); // figure out where to run to
void followPerimeter(BWAPI::Unit unit, BWAPI::Unit enemy); // run around the current region
void calculateCurrentRegionVertices(BWAPI::Unit unit); // calculate edge of current region for a unit by ScoutManager's algorithm
void calculateCurrentRegionVertices2(BWAPI::Unit unit); // uses BWTA::getPolygon instead
public:
MeleeManager();
~MeleeManager() {}
void executeMicro(const BWAPI::Unitset & targets);
BWAPI::Unit chooseTarget(BWAPI::Unit meleeUnit, const BWAPI::Unitset & targets, std::map<BWAPI::Unit, int> & numTargeting);
BWAPI::Unit closestMeleeUnit(BWAPI::Unit target, const BWAPI::Unitset & meleeUnitToAssign);
int getAttackPriority(BWAPI::Unit attacker, BWAPI::Unit unit);
BWAPI::Unit getTarget(BWAPI::Unit meleeUnit, const BWAPI::Unitset & targets);
bool meleeUnitShouldRetreat(BWAPI::Unit meleeUnit, const BWAPI::Unitset & targets);
std::pair<BWAPI::Unit, BWAPI::Unit> findClosestUnitPair(const BWAPI::Unitset & attackers, const BWAPI::Unitset & targets);
void assignTargetsNew(const BWAPI::Unitset & targets);
void assignTargetsOld(const BWAPI::Unitset & targets);
//TOMMY
void setUnits(const BWAPI::Unitset & u);
};
}<file_sep>#pragma once
#include "Common.h"
#include "MapGrid.h"
#ifdef USING_VISUALIZATION_LIBRARIES
#include "Visualizer.h"
#endif
#include "..\..\SparCraft\source\GameState.h"
#include "..\..\SparCraft\source\Game.h"
#include "..\..\SparCraft\source\Unit.h"
#include "..\..\SparCraft\source\AllPlayers.h"
#include "InformationManager.h"
//TOMMY
#include "..\..\SparCraft\source\SparCraft.h"
#include "UnitUtil.h"
namespace UAlbertaBot
{
class CombatSimulation
{
SparCraft::GameState state;
//TOMMY
int current_x;
int current_y;
public:
CombatSimulation();
void setCombatUnits(const BWAPI::Position & center, const int radius);
SparCraft::ScoreType simulateCombat();
const SparCraft::Unit getSparCraftUnit(const UnitInfo & ui) const;
const SparCraft::Unit getSparCraftUnit(BWAPI::Unit unit) const;
const SparCraft::GameState & getSparCraftState() const;
const SparCraft::IDType getSparCraftPlayerID(BWAPI::Player player) const;
void logState(const SparCraft::GameState & state);
//PAST THIS POINT IS TOMMY
void addToState(BWAPI::Unit unit); // adds to a simulation a single unit
void addToState(const UnitInfo &ui);
void addToState(SparCraft::Unit unit);
void finishMoving(); // call right before simulating combat. actually, may not need to!
const SparCraft::Unit getSparCraftUnit(BWAPI::UnitType unit, int player, int x, int y) const; // if player is 1, it is us. if player is 2, enemy. pass in x and y coordinates
// based on half-tile positions
void generateMap(); // sets the map for the state
void addAllyZergling();
void addAllySunken();
void generateCurrentSituation(); // if copy constructing fails, use these. this is based on all seen enemies
void generateCurrentSituation2();
};
}<file_sep>#include "CombatSimulation.h"
using namespace UAlbertaBot;
CombatSimulation::CombatSimulation()
{
//TOMMY
current_x = 17;
current_y = 17;
}
// sets the starting states based on the combat units within a radius of a given position
// this center will most likely be the position of the forwardmost combat unit we control
void CombatSimulation::setCombatUnits(const BWAPI::Position & center, const int radius)
{
SparCraft::GameState s;
BWAPI::Broodwar->drawCircleMap(center.x, center.y, 10, BWAPI::Colors::Red, true);
BWAPI::Unitset ourCombatUnits;
std::vector<UnitInfo> enemyCombatUnits;
MapGrid::Instance().GetUnits(ourCombatUnits, center, Config::Micro::CombatRegroupRadius, true, false);
InformationManager::Instance().getNearbyForce(enemyCombatUnits, center, BWAPI::Broodwar->enemy(), Config::Micro::CombatRegroupRadius);
for (auto & unit : ourCombatUnits)
{
if (unit->getType().isWorker())
{
continue;
}
if (InformationManager::Instance().isCombatUnit(unit->getType()) && SparCraft::System::isSupportedUnitType(unit->getType()))
{
try
{
s.addUnit(getSparCraftUnit(unit));
}
catch (int e)
{
e=1;
BWAPI::Broodwar->printf("Problem Adding Self Unit with ID: %d", unit->getID());
}
}
}
for (UnitInfo & ui : enemyCombatUnits)
{
if (ui.type.isWorker())
{
continue;
}
if (ui.type == BWAPI::UnitTypes::Terran_Bunker)
{
double hpRatio = static_cast<double>(ui.lastHealth) / ui.type.maxHitPoints();
SparCraft::Unit marine( BWAPI::UnitTypes::Terran_Marine,
SparCraft::Position(ui.lastPosition),
ui.unitID,
getSparCraftPlayerID(ui.player),
static_cast<int>(BWAPI::UnitTypes::Terran_Marine.maxHitPoints() * hpRatio),
0,
BWAPI::Broodwar->getFrameCount(),
BWAPI::Broodwar->getFrameCount());
for (size_t i(0); i < 5; ++i)
{
s.addUnit(marine);
}
continue;
}
if (!ui.type.isFlyer() && SparCraft::System::isSupportedUnitType(ui.type) && ui.completed)
{
try
{
s.addUnit(getSparCraftUnit(ui));
}
catch (int e)
{
BWAPI::Broodwar->printf("Problem Adding Enemy Unit with ID: %d %d", ui.unitID, e);
}
}
}
s.finishedMoving();
state = s;
}
// Gets a SparCraft unit from a BWAPI::Unit, used for our own units since we have all their info
const SparCraft::Unit CombatSimulation::getSparCraftUnit(BWAPI::Unit unit) const
{
return SparCraft::Unit( unit->getType(),
SparCraft::Position(unit->getPosition()),
unit->getID(),
getSparCraftPlayerID(unit->getPlayer()),
unit->getHitPoints() + unit->getShields(),
0,
BWAPI::Broodwar->getFrameCount(),
BWAPI::Broodwar->getFrameCount());
}
// Gets a SparCraft unit from a UnitInfo struct, needed to get units of enemy behind FoW
const SparCraft::Unit CombatSimulation::getSparCraftUnit(const UnitInfo & ui) const
{
BWAPI::UnitType type = ui.type;
// this is a hack, treat medics as a marine for now
if (type == BWAPI::UnitTypes::Terran_Medic)
{
type = BWAPI::UnitTypes::Terran_Marine;
}
return SparCraft::Unit( ui.type,
SparCraft::Position(ui.lastPosition),
ui.unitID,
getSparCraftPlayerID(ui.player),
ui.lastHealth,
0,
BWAPI::Broodwar->getFrameCount(),
BWAPI::Broodwar->getFrameCount());
}
SparCraft::ScoreType CombatSimulation::simulateCombat()
{
try
{
SparCraft::GameState s1(state);
SparCraft::PlayerPtr selfNOK(new SparCraft::Player_NOKDPS(getSparCraftPlayerID(BWAPI::Broodwar->self())));
SparCraft::PlayerPtr enemyNOK(new SparCraft::Player_NOKDPS(getSparCraftPlayerID(BWAPI::Broodwar->enemy())));
SparCraft::Game g (s1, selfNOK, enemyNOK, 2000);
g.play();
SparCraft::ScoreType eval = g.getState().eval(SparCraft::Players::Player_One, SparCraft::EvaluationMethods::LTD2).val();
if (Config::Debug::DrawCombatSimulationInfo)
{
std::stringstream ss1;
ss1 << "Initial State:\n";
ss1 << s1.toStringCompact() << "\n\n";
std::stringstream ss2;
ss2 << "Predicted Outcome: " << eval << "\n";
ss2 << g.getState().toStringCompact() << "\n";
BWAPI::Broodwar->drawTextScreen(150,200,"%s", ss1.str().c_str());
BWAPI::Broodwar->drawTextScreen(300,200,"%s", ss2.str().c_str());
BWAPI::Broodwar->drawTextScreen(240, 280, "Combat Sim : %d", eval);
}
return eval;
}
catch (int e)
{
BWAPI::Broodwar->printf("SparCraft FatalError, simulateCombat() threw");
return e;
}
}
const SparCraft::GameState & CombatSimulation::getSparCraftState() const
{
return state;
}
const SparCraft::IDType CombatSimulation::getSparCraftPlayerID(BWAPI::Player player) const
{
if (player == BWAPI::Broodwar->self())
{
return SparCraft::Players::Player_One;
}
else if (player == BWAPI::Broodwar->enemy())
{
return SparCraft::Players::Player_Two;
}
return SparCraft::Players::Player_None;
}
//PAST THIS POINT IS TOMMY
void CombatSimulation::addToState(BWAPI::Unit unit)
{
// if (!SparCraft::System::isSupportedUnitType(unit->getType()))
try
{
state.addUnit(getSparCraftUnit(unit));
}
catch (int e)
{
e = 1;
BWAPI::Broodwar->printf("Problem Adding Self Unit with ID: %d", unit->getID());
}
}
//NEW
void CombatSimulation::addToState(const UnitInfo &ui)
{
// if (!SparCraft::System::isSupportedUnitType(unit->getType()))
try
{
state.addUnit(getSparCraftUnit(ui));
}
catch (int e)
{
e = 1;
BWAPI::Broodwar->printf("Problem Adding Self Unit");
}
}
void CombatSimulation::addToState(SparCraft::Unit unit)
{
// if (!SparCraft::System::isSupportedUnitType(unit->getType()))
try
{
state.addUnit(unit);
}
catch (int e)
{
e = 1;
BWAPI::Broodwar->printf("Problem Adding Self Unit");
}
}
//NEW
void CombatSimulation::finishMoving()
{
state.finishedMoving();
}
const SparCraft::Unit CombatSimulation::getSparCraftUnit(BWAPI::UnitType unit, int player, int x, int y) const
{
SparCraft::IDType p;
if (player == 1)
{
p = SparCraft::Players::Player_One;
}
else
{
p = SparCraft::Players::Player_Two;
}
SparCraft::Position position(x, y);
SparCraft::Unit sparUnit(unit, p, position);
return sparUnit;
}
void CombatSimulation::generateMap()
{
SparCraft::Map smallMap(32, 32);
state.setMap(&smallMap);
}
void CombatSimulation::addAllyZergling()
{
SparCraft::Unit sparUnit = getSparCraftUnit(BWAPI::UnitTypes::Zerg_Zergling, 1, current_x, current_y);
addToState(sparUnit);
current_x += 16;
if (current_x >= 129)
{
current_x = 17;
current_y += 32;
}
}
void CombatSimulation::addAllySunken()
{
SparCraft::Unit sparUnit = getSparCraftUnit(BWAPI::UnitTypes::Zerg_Sunken_Colony, 1, current_x, current_y);
addToState(sparUnit);
current_x += 16;
if (current_x >= 129)
{
current_x = 17;
current_y += 32;
}
}
// currently need to adjust this to make all units hypothetical
void CombatSimulation::generateCurrentSituation()
{
// add our units along one side of the map
// space them half a tile apart
// when you have 7 units in a row start a new row one tile under
int xPos = 17;
int yPos = 17;
SparCraft::Unit sparUnit;
int ourCombatUnits = 0;
for (auto &unit : BWAPI::Broodwar->self()->getUnits())
{
if (((UnitUtil::IsCombatUnit(unit)) || (unit->getType() == BWAPI::UnitTypes::Zerg_Sunken_Colony)) && (SparCraft::System::isSupportedUnitType(unit->getType()))) // will this code add our sunkens to the sim? (I think so)
{
sparUnit = getSparCraftUnit(unit->getType(), 1, xPos, yPos);
addToState(sparUnit);
xPos += 16;
if (xPos >= 129)
{
xPos = 17;
yPos += 32;
}
ourCombatUnits++;
}
}
BWAPI::Broodwar->printf("We have this many units: %d\n", ourCombatUnits);
current_x = xPos;
current_y = yPos;
// add enemy units along the other side of the map and let them start at the range of a marine
int range = BWAPI::UnitTypes::Terran_Marine.groundWeapon().maxRange();
yPos += range;
xPos = 17;
int theirCombatUnits = 0;
//int theirProducingUnits = 0;
// using InfoManager to see former enemy units
// apparently InfoManager can recognize previously seen enemy units, so this is always more accurate than counting
// currently visible enemy units
for (auto &unit : InformationManager::Instance().getUnitInfo(BWAPI::Broodwar->enemy()))
{
// consider enemy combat units and not static defenses
if ((UnitUtil::IsCombatUnit(unit.second.unit)) && (!unit.second.type.isBuilding()) && (SparCraft::System::isSupportedUnitType(unit.second.type)))
{
sparUnit = getSparCraftUnit(unit.second.type, 2, xPos, yPos);
addToState(sparUnit);
xPos += 16;
if (xPos >= 129)
{
xPos = 17;
yPos += 32;
}
theirCombatUnits++;
}
//medics
else if (unit.second.type == BWAPI::UnitTypes::Terran_Medic)
{
sparUnit = getSparCraftUnit(BWAPI::UnitTypes::Terran_Marine, 2, xPos, yPos);
addToState(sparUnit);
xPos += 16;
if (xPos >= 129)
{
xPos = 17;
yPos += 32;
}
theirCombatUnits++;
}
// if unit is building and can produce a combat unit seen in the enemy's roster
// add to state all the units of that type the building can produce in the time to build a sunken
/*
if (unit.second.type.isBuilding())
{
BWAPI::UnitType::set thingsUnitCanMake(unit.second.type.buildsWhat());
int buildTime;
int sunkenTime = BWAPI::UnitTypes::Zerg_Sunken_Colony.buildTime() + BWAPI::UnitTypes::Zerg_Creep_Colony.buildTime();
int unitCount = 0;
// only consider potential unit production of enemy units we know they have made. is this bad?
for (auto &seenUnit : InformationManager::Instance().getUnitInfo(BWAPI::Broodwar->enemy()))
{
// potential issue: if enemy has been making two types of units from the same building, it will overestimate
// production. however it is quite unlikely for the enemy to do this early in the game
if (thingsUnitCanMake.find(seenUnit.second.type) != thingsUnitCanMake.end())
{
buildTime = seenUnit.second.type.buildTime();
if (!(buildTime > 0))
{
continue;
}
unitCount = sunkenTime / buildTime;
while (unitCount > 0)
{
sparUnit = getSparCraftUnit(seenUnit.second.type, 2, xPos, yPos);
addToState(sparUnit);
xPos += 16;
if (xPos >= 129)
{
xPos = 17;
yPos += 32;
}
unitCount--;
theirProducingUnits++;
}
}
}
}*/
}
BWAPI::Broodwar->printf("They currently have this many units: %d\n", theirCombatUnits);
//BWAPI::Broodwar->printf("They might make this many more units: %d\n", theirProducingUnits);
}
void CombatSimulation::generateCurrentSituation2()
{
// add our units along one side of the map
// space them half a tile apart
// when you have 7 units in a row start a new row one tile under
int xPos = 17;
int yPos = 17;
SparCraft::Unit sparUnit;
int ourCombatUnits = 0;
for (auto &unit : BWAPI::Broodwar->self()->getUnits())
{
if ((UnitUtil::IsCombatUnit(unit)) || (unit->getType() == BWAPI::UnitTypes::Zerg_Sunken_Colony)) // will this code add our sunkens to the sim? (I think so)
{
sparUnit = getSparCraftUnit(unit->getType(), 1, xPos, yPos);
addToState(sparUnit);
xPos += 16;
if (xPos >= 129)
{
xPos = 17;
yPos += 32;
}
ourCombatUnits++;
}
}
BWAPI::Broodwar->printf("We have this many units: %d\n", ourCombatUnits);
current_x = xPos;
current_y = yPos;
// add enemy units along the other side of the map and let them start at the range of a marine
int range = BWAPI::UnitTypes::Terran_Marine.groundWeapon().maxRange();
yPos += range;
xPos = 17;
int theirCombatUnits = 0;
for (auto &unit : InformationManager::Instance().getEnemyProductionEstimate())
{
if (unit.first == BWAPI::UnitTypes::Terran_Barracks)
{
for (int i = 0; i < unit.second; i++)
{
sparUnit = getSparCraftUnit(BWAPI::UnitTypes::Terran_Marine, 2, xPos, yPos);
addToState(sparUnit);
xPos += 16;
if (xPos >= 129)
{
xPos = 17;
yPos += 32;
}
theirCombatUnits++;
}
}
if (unit.first == BWAPI::UnitTypes::Protoss_Gateway)
{
for (int j = 0; j < unit.second; j++)
{
sparUnit = getSparCraftUnit(BWAPI::UnitTypes::Protoss_Zealot, 2, xPos, yPos);
addToState(sparUnit);
xPos += 16;
if (xPos >= 129)
{
xPos = 17;
yPos += 32;
}
theirCombatUnits++;
}
}
}
BWAPI::Broodwar->printf("They could have this many units: %d\n", theirCombatUnits);
/*
//int theirProducingUnits = 0;
for (auto &unit : InformationManager::Instance().getUnitInfo(BWAPI::Broodwar->enemy()))
{
// if unit is building and can produce a combat unit seen in the enemy's roster
// add to state all the units of that type the building can produce in the time to build a sunken
if (unit.second.type.isBuilding())
{
BWAPI::UnitType::set thingsUnitCanMake(unit.second.type.buildsWhat());
int buildTime;
int sunkenTime = BWAPI::UnitTypes::Zerg_Sunken_Colony.buildTime() + BWAPI::UnitTypes::Zerg_Creep_Colony.buildTime();
int unitCount = 0;
// only consider potential unit production of enemy units we know they have made. is this bad?
for (auto &seenUnit : InformationManager::Instance().getUnitInfo(BWAPI::Broodwar->enemy()))
{
// potential issue: if enemy has been making two types of units from the same building, it will overestimate
// production. however it is quite unlikely for the enemy to do this early in the game
if (thingsUnitCanMake.find(seenUnit.second.type) != thingsUnitCanMake.end())
{
buildTime = seenUnit.second.type.buildTime();
if (!(buildTime > 0))
{
continue;
}
unitCount = sunkenTime / buildTime;
while (unitCount > 0)
{
sparUnit = getSparCraftUnit(seenUnit.second.type, 2, xPos, yPos);
addToState(sparUnit);
xPos += 16;
if (xPos >= 129)
{
xPos = 17;
yPos += 32;
}
unitCount--;
theirProducingUnits++;
}
}
}
}
}
BWAPI::Broodwar->printf("They could be making this many units: %d\n", theirProducingUnits);
*/
}<file_sep>#pragma once
#include "Common.h"
#include "MicroManager.h"
#include "InformationManager.h"
namespace UAlbertaBot
{
class ScoutManager
{
BWAPI::Unit _scouter1;
BWAPI::Unit _scouter2;
BWAPI::Unit _overlordScout;
BWAPI::Unit _workerScout;
BWAPI::TilePosition _ninjaBaseLocation;
BWAPI::Position _enemyRamp;
void moveScouts();
ScoutManager();
public:
static ScoutManager & Instance();
void update();
bool setScout(BWAPI::Unit unit);
void setWorkerScout(BWAPI::Unit worker);
void buildNinjaBase();
BWAPI::TilePosition ScoutManager::getFarthestPoint();
BWAPI::Position getEnemyRamp();
void onSendText(std::string text);
void onUnitShow(BWAPI::Unit unit);
void onUnitHide(BWAPI::Unit unit);
void onUnitCreate(BWAPI::Unit unit);
void onUnitRenegade(BWAPI::Unit unit);
void onUnitDestroy(BWAPI::Unit unit);
void onUnitMorph(BWAPI::Unit unit);
};
}<file_sep>#include "Common.h"
#include "BuildingManager.h"
#include "Micro.h"
#include "ScoutManager.h"
#include "ProductionManager.h"
#include <algorithm>
using namespace UAlbertaBot;
BuildingManager::BuildingManager()
: _debugMode(false)
, _reservedMinerals(0)
, _reservedGas(0)
{
}
BWAPI::TilePosition BuildingManager::getExtractorPosition(BWAPI::TilePosition desiredPosition)
{
if (createdBuilding.find(desiredPosition) != createdBuilding.end() && baseCount == 2)
{
return naturalGas->getTilePosition();
}
else if (createdBuilding.find(desiredPosition) != createdBuilding.end() && baseCount >= 3 && createdHatcheriesSet.size() >= 3)
{
BWAPI::TilePosition hatchPosition = createdBaseVector[createdBaseVector.size() - 1];
BWAPI::TilePosition gasPosition;
const std::set<BWTA::BaseLocation*, std::less<BWTA::BaseLocation*>> locations = BWTA::getBaseLocations();
BWTA::BaseLocation *myLocation;
for (BWTA::BaseLocation *p : locations) {
BWAPI::TilePosition z = p->getTilePosition();
if (z == hatchPosition){
// This is the BWTA::Location of the first hatchery.
myLocation = p;
}
}
const BWAPI::Unitset gasSet = myLocation->getGeysers();
for (BWAPI::Unit p : gasSet)
{
gasPosition = p->getTilePosition();
break;
}
return gasPosition;
}
else
{
return desiredPosition;
}
}
// Get a sunken position depending on whether or not we have an expansion.
BWAPI::TilePosition BuildingManager::getSunkenPosition()
{
BWAPI::UnitType sunk = BWAPI::UnitTypes::Zerg_Creep_Colony;
// Always make sunkens at natural expansion if you can.
if (createdHatcheriesSet.size() >= 1)
{
BWAPI::TilePosition hatchPosition = createdHatcheriesVector[0];
/*
BWAPI::Unit pExpansion = BWAPI::Broodwar->getClosestUnit(BWAPI::Position(hatchPosition), BWAPI::Filter::IsResourceDepot);
BWAPI::Unitset myUnits = pExpansion->getUnitsInRadius(200);
BWAPI::UnitType larva = BWAPI::UnitTypes::Zerg_Larva;
BWAPI::UnitType egg = BWAPI::UnitTypes::Zerg_Egg;
std::set<BWAPI::TilePosition> stuffBlocking;
for (BWAPI::Unit p : myUnits)
{
if (p->getType() == larva || p->getType() == egg)
{
stuffBlocking.insert(p->getTilePosition());
}
}
*/
while (buildableSunkenTilePositions.size() >= 1)
{
std::set<BWAPI::TilePosition>::iterator it = buildableSunkenTilePositions.begin();
BWAPI::TilePosition mySunkPosition = *it;
Building z(sunk, mySunkPosition);
if (buildable(mySunkPosition.x, mySunkPosition.y, mySunkPosition))
{
return *it; }
else
{
buildableSunkenTilePositions.erase(*it);
}
}
//BWAPI::Position hatchPositionBWP = BWAPI::Position(hatchPosition);
BWAPI::TilePosition sunkPosition;
const std::set<BWTA::BaseLocation*, std::less<BWTA::BaseLocation*>> locations = BWTA::getBaseLocations();
BWTA::BaseLocation *myLocation;
for (BWTA::BaseLocation *p : locations) {
BWAPI::TilePosition z = p->getTilePosition();
if (z == hatchPosition){
// This is the BWTA::Location of the first hatchery.
myLocation = p;
}
}
// Get the set of mineral patches closest to BWTA::Location of the hatchery(it will return like 8 mineral patches usually in the set)
const BWAPI::Unitset mineralSet = myLocation->getMinerals();
//const std::set<BWAPI::Unit*> mineralSet = myLocation->getMinerals();
int counter3 = 0;
int theX = 0;
int theY = 0;
for (BWAPI::Unit p : mineralSet)
{
// Calculate the difference between LeftMostMineralPatch.x - ExpansionHatchery.x and store it in theX
theX = p->getTilePosition().x - hatchPosition.x;
// Calculate the difference between LeftMostMineralPatch.y - ExpansionHatchery.y and store it in theY
theY = p->getTilePosition().y - hatchPosition.y;
break;
}
int gasX = 0;
int gasY = 0;
int counter4 = 0;
//Get all geysers near the expansion -- it should only return 1 for every map we play..
const BWAPI::Unitset gasSet = myLocation->getGeysers();
for (BWAPI::Unit p : gasSet)
{
naturalGas = p;
// Calculate the difference between Geyser.x- ExpansionHatchery.x and store it in gasX
gasX = p->getTilePosition().x - hatchPosition.x;
// Calculate the difference between Geyser.y- ExpansionHatchery.y and store it in gasY
gasY = p->getTilePosition().y - hatchPosition.y;
break;
}
int newx, newy;
int outercounter = 0;
int counter = 0;
newx = hatchPosition.x;
newy = hatchPosition.y;
int beginX = hatchPosition.x;
int beginY = hatchPosition.y;
//sunkPosition = BWAPI::TilePosition(newx, newy);
//test4 = BuildingPlacer::Instance().canBuildHere(sunkPosition, b);
// Form a new sunken position that starts at the hatchery positive.
std::vector<bool> incrementDecrement(8);
bool useGasX = false;
bool useGasY = false;
bool useMinX = false;
bool useMinY = false;
if (abs(gasX) > abs(gasY))
{
useGasX = true;
}
else
{
useGasY = true;
}
if (abs(theX) > abs(theY))
{
useMinX = true;
}
else
{
useMinY = true;
}
// Gas differences is probably more reliable than mineral differences.
if (useGasX && useMinX)
{
useMinX = false;
useMinY = true;
}
// Gas differences is probably more reliable than mineral differences.
if (useGasY && useMinY)
{
useMinY = false;
useMinX = true;
}
// This is where we decide which directions we can make sunkens in
// It is based on X and Y differences in LeftMostMineral - Hatchery and Geyser - Hatchery
// It is not very good right now because we only use two variables. We should use four variables for better dection : theX, theY, gasX, gasY
// If the difference between LeftMostMineral.y - Hatchery.y is negative : It means the mierals are North of the hatchery
// If the difference between Geyser.X - Hatchery.X is negative : It means that the geyser is Left of the Hatchery
if (useMinY && useGasX)
{
if (theY < 0 && gasX < 0)
{
/* Allow the following directions for sunken to be built :
Increase X & Keep Y the same (East)
Increase X & Increase Y (Go South East)
Decrease X & Increase Y (Go South West)
Keep X Same, Increase Y (Go South)
Go NORTHEAST **Test**
*/
incrementDecrement = { true, false, true, true, false, false, true, false };
}
// If the difference between LeftMostMineral.y - Hatchery.y is positive : It means the mierals are South of the hatchery
// If the difference between Geyser.X - Hatchery.X is negative : It means that the geyser is Left of the Hatchery
else if (gasX < 0 && theY > 0)
{
/* Allow the following directions for sunken to be built :
Increase X & Keep Y the same (East)
Increase X & Decrease Y (Go North East)
Decrease X & Decrease Y (Go North West)
Keep X Same, Decrease Y (Go North)
GO SOUTHEAST --> Test
*/
incrementDecrement = { false, true, true, false, true, false, false, true };
}
// If the difference between LeftMostMineral.y - Hatchery.y is negative : It means the mierals are North of the hatchery
// If the difference between Geyser.X - Hatchery.X is positive : It means that the geyser is Right or East of the Hatchery
else if (gasX > 0 && theY < 0)
{
/* Allow the following directions for sunken to be built :
Decrease X & Keep Y the same (West)
Decrease X & Increase Y (Go South West)
Increase X & Increase Y (Go South East)
Keep X Same, Increase Y (Go South)
Go Northwest
*/
incrementDecrement = { true, false, false, true, false, true, true, false };
}
// If the difference between LeftMostMineral.y - Hatchery.y is positive : It means the mierals are South of the hatchery
// If the difference between Geyser.X - Hatchery.X is positive : It means that the geyser is Right or East of the Hatchery
else if (theY > 0 && gasX > 0)
{
/* Decrease X & Keep Y the same (West)
Decrease X & Decrease Y (Go North West)
Increase X & Decrease Y (Go North East)
Don't change X Decrease y (Go North)
Go Southwest
*/
incrementDecrement = { false, true, false, false, true, true, false, true };
}
}
else if (useMinX && useGasY)
{
// If the difference between LeftMostMineral.x - Hatchery.x is positive : It means the mierals are East of the hatchery
// If the difference between Geyser.Y - Hatchery.Y is negative : It means that the geyser is North of the Hatchery
if (gasY < 0 && theX > 0)
{
/* Decrease X(Go West)
Increase Y(Go South)
Decrease X, Increase Y(Go South West)
Decrease X, Decrease Y(Go North West)
I think can try SouthEast ? */
incrementDecrement = { false, false, false, true, true, true, true, false };
}
// If the difference between LeftMostMineral.x - Hatchery.x is positive : It means the mierals are East of the hatchery
// If the difference between Geyser.Y - Hatchery.Y is positive : It means that the geyser is South of the Hatchery
else if (theX > 0 && gasY > 0)
{
/* Decrease X(Go West)
Decrease Y(Go North)
Decrease X, INcrease Y(Go SOuth West)
Decrease X, Decrease Y(Go North West)
I think can try NOrthEast?
*/
incrementDecrement = { false, false, false, true, true, true, false, true };
}
// If the difference between LeftMostMineral.x - Hatchery.x is negative : It means the minerals are West of the hatchery
// If the difference between Geyser.Y - Hatchery.Y is negative : It means that the geyser is North of the Hatchery
else if (gasY < 0 && theX < 0)
{
/* Increase X(Go East)
Increase Y(Go South)
Increase X, Increase Y(Go South East)
Increase X, Decrease Y(Go North East)
I think maybe Southwest is okay?.. Even NW might be okay */
incrementDecrement = { true, true, true, false, false, false, true, false };
}
// If the difference between LeftMostMineral.x - Hatchery.x is negative : It means the minerals are West of the hatchery
// If the difference between Geyser.Y - Hatchery.Y is positive : It means that the geyser is South of the Hatchery
else if (gasY > 0 && theX < 0)
{
incrementDecrement = { true, true, true, false, false, false, false, true };
/* Increase X(Go East)
Decrease Y(Go North)
Increase X, Increase Y(Go South East)
Increase X, Decrease Y(Go North East)
I think maybe Northwest is okay? */
}
}
beginX = hatchPosition.x;
beginY = hatchPosition.y;
std::vector<std::pair<int, int> > myVec;
std::pair<int, int> p1;
for (int i = 0; i < 8; i++)
{
if (incrementDecrement[i])
{
if (i == 0)
{
p1.first = 1;
p1.second = 1;
}
else if (i == 1)
{
p1.first = 1;
p1.second = -1;
}
else if (i == 2)
{
p1.first = 1;
p1.second = 0;
}
else if (i == 3)
{
p1.first = -1;
p1.second = 1;
}
else if (i == 4)
{
p1.first = -1;
p1.second = -1;
}
else if (i == 5)
{
p1.first = -1;
p1.second = 0;
}
else if (i == 6)
{
p1.first = 0;
p1.second = 1;
}
else if (i == 7)
{
p1.first = 0;
p1.second = -1;
}
myVec.push_back(p1);
}
}
int N = 20;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
for (int l = 0; l < N; l++)
{
int xChange = beginX;
int yChange = beginY;
xChange += i * myVec[0].first;
yChange += i * myVec[0].second;
xChange += j * myVec[1].first;
yChange += j * myVec[1].second;
xChange += k * myVec[2].first;
yChange += k * myVec[2].second;
xChange += l * myVec[3].first;
yChange += l * myVec[3].second;
sunkPosition = BWAPI::TilePosition(xChange, yChange);
Building b(sunk, sunkPosition);
if (buildable(xChange, yChange, sunkPosition))
{
buildableSunkenTilePositions.insert(sunkPosition);
}
}
if (buildableSunkenTilePositions.size() != 0)
{
std::set<BWAPI::TilePosition>::iterator it = buildableSunkenTilePositions.begin();
return *it;
}
else
{
return BWAPI::TilePositions::None;
}
}
}
/* We check the following conditions :
Do we not have creep at the sunken position?
Can we not build at the sunken position?
Have we built at this position before?
If any of these are true and counter <= 7 --> Remain in loop
Is the counter <= 7 --> Makes sure not to go out of bounds for the incrementDecrement vector
*/
// Since counter == 8, it means we tried all 8 directions and couldnt find a sunken position, so return None(sunken will be made in main base)
// gets called every frasme from GameCommander
void BuildingManager::update()
{
/*
std::set<BWAPI::Unit> CreepSet;
std::set<BWAPI::TilePosition> CreepSet2;
BWAPI::Unit testUnit;
for (BWAPI::Unit p : BWAPI::Broodwar->self()->getUnits())
{
if (p->getType() == BWAPI::UnitTypes::Zerg_Creep_Colony)
{
CreepSet2.insert(p->getTilePosition());
CreepSet.insert(p);
testUnit = p;
//BWAPI::Broodwar->printf("Creep Position %d %d\n", p->getTilePosition().x, p->getTilePosition().y;)x
}
}
for (auto x : CreepSet2)
{
BWAPI::Broodwar->printf("Creep Position %d %d Distance is : %f\n", x.x, x.y, x.getDistance(testUnit->getTilePosition()));
//BWAPI::Broodwar->printf->("The distance is %d\n", x.getDistance(testUnit->getTilePosition()));
}
//double tempDist = Euclidean_Distance(x->getTilePosition().x, testUnit->getTilePosition().x, x->getTilePosition().y, testUnit->getTilePosition().y);
//BWAPI::Broodwar->printf("Creep Position %d %d Distance is : %d\n", x->getTilePosition().x, x->getTilePosition().y,tempDist);
*/
//BWTA::getNearestChokepoint(BWTA::getStartLocation(BWAPI::Broodwar->self())->getTilePosition());
//BWTA::getStartLocation(BWAPI::Broodwar->self())->getNearestChokePoint();
//BWTA::BaseLocation = BWTA::getStartLocation(BWAPI::Broodwar->self());
//BWAPI::Broodwar->printf("Making sunken at %d %d. Main base is %d %d, Expansion is %d %d", sunkPos.x, sunkPos.y, BWTA::getStartLocation(BWAPI::Broodwar->self())->getTilePosition().x, BWTA::getStartLocation(BWAPI::Broodwar->self())->getTilePosition().y, createdHatcheriesVector[0].x, createdHatcheriesVector[0].y);
//BWAPI::Broodwar->printf("My ChokePoint is %d %d", baseChoke.x, baseChoke.y,
if (canBuild && BWAPI::Broodwar->getFrameCount() > sunkenBuildTimer)
{
MetaType type(BWAPI::UnitTypes::Zerg_Creep_Colony);
ProductionManager::Instance()._queue.queueAsHighestPriority(type, true);
canBuild = false;
}
validateWorkersAndBuildings(); // check to see if assigned workers have died en route or while constructing
assignWorkersToUnassignedBuildings(); // assign workers to the unassigned buildings and label them 'planned'
constructAssignedBuildings(); // for each planned building, if the worker isn't constructing, send the command
checkForStartedConstruction(); // check to see if any buildings have started construction and update data structures
checkForDeadTerranBuilders(); // if we are terran and a building is under construction without a worker, assign a new one
checkForCompletedBuildings(); // check to see if any buildings have completed and update data structures
}
bool BuildingManager::isBeingBuilt(BWAPI::UnitType type)
{
for (auto & b : _buildings)
{
if (b.type == type)
{
return true;
}
}
return false;
}
// STEP 1: DO BOOK KEEPING ON WORKERS WHICH MAY HAVE DIED
void BuildingManager::validateWorkersAndBuildings()
{
// TODO: if a terran worker dies while constructing and its building
// is under construction, place unit back into buildingsNeedingBuilders
std::vector<Building> toRemove;
// find any buildings which have become obsolete
for (auto & b : _buildings)
{
if (b.status != BuildingStatus::UnderConstruction)
{
continue;
}
if (b.buildingUnit == nullptr || !b.buildingUnit->getType().isBuilding() || b.buildingUnit->getHitPoints() <= 0)
{
toRemove.push_back(b);
}
}
removeBuildings(toRemove);
}
// STEP 2: ASSIGN WORKERS TO BUILDINGS WITHOUT THEM
void BuildingManager::assignWorkersToUnassignedBuildings()
{
// for each building that doesn't have a builder, assign one
for (Building & b : _buildings)
{
if (b.status != BuildingStatus::Unassigned)
{
continue;
}
if (_debugMode) { BWAPI::Broodwar->printf("Assigning Worker To: %s", b.type.getName().c_str()); }
// grab a worker unit from WorkerManager which is closest to this final position
BWAPI::Unit workerToAssign = WorkerManager::Instance().getBuilder(b);
if (workerToAssign)
{
//BWAPI::Broodwar->printf("VALID WORKER BEING ASSIGNED: %d", workerToAssign->getID());
// TODO: special case of terran building whose worker died mid construction
// send the right click command to the buildingUnit to resume construction
// skip the buildingsAssigned step and push it back into buildingsUnderConstruction
b.builderUnit = workerToAssign;
BWAPI::TilePosition testLocation = getBuildingLocation(b);
if (!testLocation.isValid())
{
continue;
}
b.finalPosition = testLocation;
// reserve this building's space
BuildingPlacer::Instance().reserveTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight());
b.status = BuildingStatus::Assigned;
}
}
}
// STEP 3: ISSUE CONSTRUCTION ORDERS TO ASSIGN BUILDINGS AS NEEDED
void BuildingManager::constructAssignedBuildings()
{
for (auto & b : _buildings)
{
if (b.status != BuildingStatus::Assigned)
{
continue;
}
// if that worker is not currently constructing
if (!b.builderUnit->isConstructing())
{
// if we haven't explored the build position, go there
if (!isBuildingPositionExplored(b))
{
Micro::SmartMove(b.builderUnit, BWAPI::Position(b.finalPosition));
}
// if this is not the first time we've sent this guy to build this
// it must be the case that something was in the way of building
else if (b.buildCommandGiven)
{
// tell worker manager the unit we had is not needed now, since we might not be able
// to get a valid location soon enough
WorkerManager::Instance().finishedWithWorker(b.builderUnit);
// free the previous location in reserved
BuildingPlacer::Instance().freeTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight());
// nullify its current builder unit
b.builderUnit = nullptr;
// reset the build command given flag
b.buildCommandGiven = false;
// add the building back to be assigned
b.status = BuildingStatus::Unassigned;
}
else
{
// issue the build order!
if (b.type == BWAPI::UnitTypes::Zerg_Hatchery)
{
if (isBaseLocation(b.finalPosition))
{
baseCount++;
createdBaseVector.push_back(b.finalPosition);
}
if (std::find(createdHatcheriesVector.begin(), createdHatcheriesVector.end(), b.finalPosition) == createdHatcheriesVector.end())
{
createdHatcheriesSet.insert(b.finalPosition);
createdHatcheriesVector.push_back(b.finalPosition);
}
//firstHatcheryPosition = BWAPI::Position(b.finalPosition);
}
else if (b.type == BWAPI::UnitTypes::Zerg_Extractor)
{
b.finalPosition = getExtractorPosition(b.finalPosition);
}
//|| b.type == 146 is sunken
else if (b.type == BWAPI::UnitTypes::Zerg_Creep_Colony)
{
BWAPI::TilePosition sunkPos = getSunkenPosition();
//b.finalPosition = sunkPos;
if (sunkPos != BWAPI::TilePositions::None)
{
b.finalPosition = sunkPos;
buildableSunkenTilePositions.erase(sunkPos);
createdSunkenSet.insert(b.finalPosition);
createdSunkenVector.push_back(b.finalPosition);
//BWTA::getStartLocation(BWAPI::Broodwar->self())->getNearestChokePoint();
/*
const std::set<BWTA::BaseLocation*, std::less<BWTA::BaseLocation*>> locations = BWTA::getBaseLocations();
BWAPI::Unit myHatch;
BWAPI::Unit myExpansion;
for (BWAPI::BaseLocation *p : BWAPI::Bro)
{
if (p->getTilePosition() == BWAPI::Broodwar->self()->getStartLocation())
{
myHatch = p;
}
else if (p->getTilePosition() == createdHatcheriesVector[0])
{
myExpansion = p;
}
}
*/
//BWAPI::Broodwar->printf("Making sunken at %d %d. Main base is %d %d, Expansion is %d %d, Nearest ChokePoint is %d %d", sunkPos.x, sunkPos.y, BWTA::getStartLocation(BWAPI::Broodwar->self())->getTilePosition().x, BWTA::getStartLocation(BWAPI::Broodwar->self())->getTilePosition().y, createdHatcheriesVector[0].x, createdHatcheriesVector[0].y, baseChoke.x, baseChoke.y);
/*
for (BWAPI::Unit p : BWAPI::Broodwar->self()->getUnits())
{
if (p->getType() == BWAPI::UnitTypes::Zerg_Overlord)
{
p->move(rampPosition);
break;
}
}
*/
//BWAPI::Broodwar->printf("Making sunken at %d %d. Main base is %d %d, Expansion is %d %d, Nearest ChokePoint is %d %d", sunkPos.x, sunkPos.y, BWTA::getStartLocation(BWAPI::Broodwar->self())->getTilePosition().x, BWTA::getStartLocation(BWAPI::Broodwar->self())->getTilePosition().y, createdHatcheriesVector[0].x, createdHatcheriesVector[0].y, baseChoke.x, baseChoke.y);
}
/*
if (p->getType() == BWAPI::UnitTypes::Zerg_Overlord)
{
p->move(BWAPI::Position(baseChoke));
break;
}
*/
else
{
BWAPI::Broodwar->printf("Could not find a suitable location. Using %d %d\n", b.finalPosition.x, b.finalPosition.y);
}
}
else if (b.type == BWAPI::UnitTypes::Zerg_Evolution_Chamber || b.type == BWAPI::UnitTypes::Zerg_Hydralisk_Den)
{
const std::vector<BWAPI::TilePosition> tempTiles = MapTools::Instance().getClosestTilesTo(BWAPI::Position(createdHatcheriesVector[1]));
BWAPI::Broodwar->printf("%d %d VS %d %d\n", createdHatcheriesVector[1].x, createdHatcheriesVector[1].y, createdHatcheriesVector[0].x, createdHatcheriesVector[0].y);
for (auto myTile : tempTiles)
{
if (buildable2(myTile.x, myTile.y, myTile))
{
b.finalPosition = myTile;
break;
}
}
}
b.builderUnit->build(b.type, b.finalPosition);
createdBuilding.insert(b.finalPosition);
// set the flag to true
b.buildCommandGiven = true;
}
}
}
}
// STEP 4: UPDATE DATA STRUCTURES FOR BUILDINGS STARTING CONSTRUCTION
void BuildingManager::checkForStartedConstruction()
{
// for each building unit which is being constructed
for (auto & buildingStarted : BWAPI::Broodwar->self()->getUnits())
{
/*if (buildingStarted->getType() == BWAPI::UnitTypes::Zerg_Creep_Colony && !buildingStarted->isBeingConstructed())
{
//b.buildingUnit->morph(BWAPI::UnitTypes::Zerg_Creep_Colony);
MetaType type(BWAPI::UnitTypes::Zerg_Creep_Colony);
ProductionManager::Instance()._queue.queueAsHighestPriority(type, true);
}
*/
// filter out units which aren't buildings under construction
if (!buildingStarted->getType().isBuilding() || !buildingStarted->isBeingConstructed())
{
continue;
}
// check all our building status objects to see if we have a match and if we do, update it
for (auto & b : _buildings)
{
if (b.status != BuildingStatus::Assigned)
{
continue;
}
// check if the positions match
if (b.finalPosition == buildingStarted->getTilePosition())
{
// the resources should now be spent, so unreserve them
_reservedMinerals -= buildingStarted->getType().mineralPrice();
_reservedGas -= buildingStarted->getType().gasPrice();
// flag it as started and set the buildingUnit
b.underConstruction = true;
b.buildingUnit = buildingStarted;
// if we are zerg, the buildingUnit now becomes nullptr since it's destroyed
if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Zerg)
{
b.builderUnit = nullptr;
// if we are protoss, give the worker back to worker manager
}
else if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Protoss)
{
// if this was the gas steal unit then it's the scout worker so give it back to the scout manager
if (b.isGasSteal)
{
ScoutManager::Instance().setWorkerScout(b.builderUnit);
}
// otherwise tell the worker manager we're finished with this unit
else
{
WorkerManager::Instance().finishedWithWorker(b.builderUnit);
}
b.builderUnit = nullptr;
}
// put it in the under construction vector
b.status = BuildingStatus::UnderConstruction;
// free this space
BuildingPlacer::Instance().freeTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight());
// only one building will match
break;
}
}
}
}
// STEP 5: IF WE ARE TERRAN, THIS MATTERS, SO: LOL
void BuildingManager::checkForDeadTerranBuilders() {}
// STEP 6: CHECK FOR COMPLETED BUILDINGS
void BuildingManager::checkForCompletedBuildings()
{
std::vector<Building> toRemove;
// for each of our buildings under construction
for (auto & b : _buildings)
{
if (b.status != BuildingStatus::UnderConstruction)
{
continue;
}
// if the unit has completed
if (b.buildingUnit->isCompleted())
{
if (b.buildingUnit->getType() == BWAPI::UnitTypes::Zerg_Creep_Colony && canSunken)
{
int myID = b.buildingUnit->getID();
if (sentSunkenCommand.find(myID) != sentSunkenCommand.end())
{
continue;
}
MetaType type(BWAPI::UnitTypes::Zerg_Sunken_Colony);
ProductionManager::Instance()._queue.queueAsHighestPriority(type, true);
canSunken = false;
sentSunkenCommand.insert(myID);
}
if (b.buildingUnit->getType() == BWAPI::UnitTypes::Zerg_Evolution_Chamber)
{
if (evoCompleted.find(b.buildingUnit) == evoCompleted.end())
{
if (evoCompleted.size() == 0)
{
firstEvoChamber = b.buildingUnit->getID();
}
evoCompleted.insert(b.buildingUnit);
if (upgradeEvo.find(BWAPI::UpgradeTypes::Zerg_Missile_Attacks) == upgradeEvo.end())
{
MetaType type(BWAPI::UpgradeTypes::Zerg_Missile_Attacks);
upgradeEvo.insert(BWAPI::UpgradeTypes::Zerg_Missile_Attacks);
ProductionManager::Instance()._queue.queueAsHighestPriority(type, true);
}
else if (upgradeEvo.find(BWAPI::UpgradeTypes::Zerg_Carapace) == upgradeEvo.end())
{
MetaType type(BWAPI::UpgradeTypes::Zerg_Carapace);
upgradeEvo.insert(BWAPI::UpgradeTypes::Zerg_Carapace);
ProductionManager::Instance()._queue.queueAsHighestPriority(type, true);
}
}
}
if (b.buildingUnit->getType() == BWAPI::UnitTypes::Zerg_Hatchery && b.finalPosition == createdHatcheriesVector[0] && canBuildTrigger)
{
hatcheryUnit = b.buildingUnit;
canBuild = true;
canBuildTrigger = false;
sunkenBuildTimer = BWAPI::Broodwar->getFrameCount() + 8 * 25;
std::set<BWTA::Chokepoint *> chokePoints = BWTA::getChokepoints();
double lowestDistance = 999999.0;
BWAPI::Position ourRampPosition;
for (auto x : chokePoints)
{
double distance1 = BWTA::getGroundDistance(createdHatcheriesVector[0], BWAPI::TilePosition(x->getCenter()));
double distance2 = BWTA::getGroundDistance(BWAPI::Broodwar->self()->getStartLocation(), BWAPI::TilePosition(x->getCenter()));
double sum = distance1 + distance2;
if (sum < lowestDistance)
{
lowestDistance = sum;
ourRampPosition = x->getCenter();
mainToRampDistance = distance2;
}
}
}
// if we are terran, give the worker back to worker manager
if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Terran)
{
if (b.isGasSteal)
{
ScoutManager::Instance().setWorkerScout(b.builderUnit);
}
// otherwise tell the worker manager we're finished with this unit
else
{
WorkerManager::Instance().finishedWithWorker(b.builderUnit);
}
}
// remove this unit from the under construction vector
toRemove.push_back(b);
}
else if (b.buildingUnit->getType() == BWAPI::UnitTypes::Zerg_Creep_Colony && b.buildingUnit->getHitPoints() < 400 && b.buildingUnit->getHitPoints() >= 1)
{
canSunken = true;
}
/*
else if (b.buildingUnit->getType() == BWAPI::UnitTypes::Zerg_Evolution_Chamber && b.buildingUnit->getHitPoints() >= 1 && notEvoChecked)
{
evoTimer = BWAPI::Broodwar->getFrameCount() + 100;
notEvoChecked = false;
}
*/
}
removeBuildings(toRemove);
}
// COMPLETED
bool BuildingManager::isEvolvedBuilding(BWAPI::UnitType type)
{
if (type == BWAPI::UnitTypes::Zerg_Sunken_Colony ||
type == BWAPI::UnitTypes::Zerg_Spore_Colony ||
type == BWAPI::UnitTypes::Zerg_Lair ||
type == BWAPI::UnitTypes::Zerg_Hive ||
type == BWAPI::UnitTypes::Zerg_Greater_Spire)
{
return true;
}
return false;
}
// add a new building to be constructed
void BuildingManager::addBuildingTask(BWAPI::UnitType type, BWAPI::TilePosition desiredLocation, bool isGasSteal)
{
_reservedMinerals += type.mineralPrice();
_reservedGas += type.gasPrice();
Building b(type, desiredLocation);
b.isGasSteal = isGasSteal;
b.status = BuildingStatus::Unassigned;
_buildings.push_back(b);
}
bool BuildingManager::isBuildingPositionExplored(const Building & b) const
{
BWAPI::TilePosition tile = b.finalPosition;
// for each tile where the building will be built
for (int x = 0; x<b.type.tileWidth(); ++x)
{
for (int y = 0; y<b.type.tileHeight(); ++y)
{
if (!BWAPI::Broodwar->isExplored(tile.x + x, tile.y + y))
{
return false;
}
}
}
return true;
}
char BuildingManager::getBuildingWorkerCode(const Building & b) const
{
return b.builderUnit == nullptr ? 'X' : 'W';
}
int BuildingManager::getReservedMinerals()
{
return _reservedMinerals;
}
int BuildingManager::getReservedGas()
{
return _reservedGas;
}
void BuildingManager::drawBuildingInformation(int x, int y)
{
if (!Config::Debug::DrawBuildingInfo)
{
return;
}
for (auto & unit : BWAPI::Broodwar->self()->getUnits())
{
BWAPI::Broodwar->drawTextMap(unit->getPosition().x, unit->getPosition().y + 5, "\x07%d", unit->getID());
}
BWAPI::Broodwar->drawTextScreen(x, y, "\x04 Building Information:");
BWAPI::Broodwar->drawTextScreen(x, y + 20, "\x04 Name");
BWAPI::Broodwar->drawTextScreen(x + 150, y + 20, "\x04 State");
int yspace = 0;
for (const auto & b : _buildings)
{
if (b.status == BuildingStatus::Unassigned)
{
BWAPI::Broodwar->drawTextScreen(x, y + 40 + ((yspace)* 10), "\x03 %s", b.type.getName().c_str());
BWAPI::Broodwar->drawTextScreen(x + 150, y + 40 + ((yspace++) * 10), "\x03 Need %c", getBuildingWorkerCode(b));
}
else if (b.status == BuildingStatus::Assigned)
{
BWAPI::Broodwar->drawTextScreen(x, y + 40 + ((yspace)* 10), "\x03 %s %d", b.type.getName().c_str(), b.builderUnit->getID());
BWAPI::Broodwar->drawTextScreen(x + 150, y + 40 + ((yspace++) * 10), "\x03 A %c (%d,%d)", getBuildingWorkerCode(b), b.finalPosition.x, b.finalPosition.y);
int x1 = b.finalPosition.x * 32;
int y1 = b.finalPosition.y * 32;
int x2 = (b.finalPosition.x + b.type.tileWidth()) * 32;
int y2 = (b.finalPosition.y + b.type.tileHeight()) * 32;
BWAPI::Broodwar->drawLineMap(b.builderUnit->getPosition().x, b.builderUnit->getPosition().y, (x1 + x2) / 2, (y1 + y2) / 2, BWAPI::Colors::Orange);
BWAPI::Broodwar->drawBoxMap(x1, y1, x2, y2, BWAPI::Colors::Red, false);
}
else if (b.status == BuildingStatus::UnderConstruction)
{
BWAPI::Broodwar->drawTextScreen(x, y + 40 + ((yspace)* 10), "\x03 %s %d", b.type.getName().c_str(), b.buildingUnit->getID());
BWAPI::Broodwar->drawTextScreen(x + 150, y + 40 + ((yspace++) * 10), "\x03 Const %c", getBuildingWorkerCode(b));
}
}
}
BuildingManager & BuildingManager::Instance()
{
static BuildingManager instance;
return instance;
}
std::vector<BWAPI::UnitType> BuildingManager::buildingsQueued()
{
std::vector<BWAPI::UnitType> buildingsQueued;
for (const auto & b : _buildings)
{
if (b.status == BuildingStatus::Unassigned || b.status == BuildingStatus::Assigned)
{
buildingsQueued.push_back(b.type);
}
}
return buildingsQueued;
}
BWAPI::TilePosition BuildingManager::getBuildingLocation(const Building & b)
{
int numPylons = BWAPI::Broodwar->self()->completedUnitCount(BWAPI::UnitTypes::Protoss_Pylon);
if (b.isGasSteal)
{
BWTA::BaseLocation * enemyBaseLocation = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy());
UAB_ASSERT(enemyBaseLocation, "Should have enemy base location before attempting gas steal");
UAB_ASSERT(enemyBaseLocation->getGeysers().size() > 0, "Should have spotted an enemy geyser");
for (auto & unit : enemyBaseLocation->getGeysers())
{
BWAPI::TilePosition tp(unit->getInitialTilePosition());
return tp;
}
}
if (b.type.requiresPsi() && numPylons == 0)
{
return BWAPI::TilePositions::None;
}
if (b.type.isRefinery())
{
return BuildingPlacer::Instance().getRefineryPosition();
}
if (b.type.isResourceDepot() && createdHatcheriesVector.size() == 0)
{
// get the location
BWAPI::TilePosition tile = MapTools::Instance().getNextExpansion();
return tile;
}
// set the building padding specifically
int distance = b.type == BWAPI::UnitTypes::Protoss_Photon_Cannon ? 0 : Config::Macro::BuildingSpacing;
if (b.type == BWAPI::UnitTypes::Protoss_Pylon && (numPylons < 3))
{
distance = Config::Macro::PylonSpacing;
}
// get a position within our region
if (b.type == BWAPI::UnitTypes::Zerg_Creep_Colony)
{
return BuildingPlacer::Instance().getBuildLocationNear(b, 0, false);
}
return BuildingPlacer::Instance().getBuildLocationNear(b, distance, false);
}
void BuildingManager::removeBuildings(const std::vector<Building> & toRemove)
{
for (auto & b : toRemove)
{
auto & it = std::find(_buildings.begin(), _buildings.end(), b);
if (it != _buildings.end())
{
_buildings.erase(it);
}
}
}
bool BuildingManager::sunkenIntersection(BWAPI::TilePosition mySunkPosition) const
{
/*
std::set<BWAPI::Unit> sunkens;
for (BWAPI::Unit p : BWAPI::Broodwar->self()->getUnits())
{
if (p->getType() == BWAPI::UnitTypes::Zerg_Creep_Colony)
{
sunkens.insert(p);
}
}
*/
for (auto x : createdSunkenSet)
{
if ((int) x.getDistance(mySunkPosition) < (int) 2)
{
return true;
}
}
return false;
/*
for (auto x : sunkens)
{
if (x->getDistance(BWAPI::Position(mySunkPosition)) < 16)
{
return true;
}
}
return false;
*/
}
bool BuildingManager::buildable(int x, int y, BWAPI::TilePosition mySunkPosition) const
{
//returns true if this tile is currently buildable, takes into account units on tile
if (!BWAPI::Broodwar->isBuildable(x, y) || !BWAPI::Broodwar->hasCreep(x, y) || createdBuilding.find(mySunkPosition) != createdBuilding.end() || BWTA::getGroundDistance(BWAPI::Broodwar->self()->getStartLocation(), mySunkPosition) < mainToRampDistance) // &&|| b.type == BWAPI::UnitTypes::Zerg_Hatchery
{
return false;
}
return true;
}
bool BuildingManager::buildable2(int x, int y, BWAPI::TilePosition mySunkPosition) const
{
//returns true if this tile is currently buildable, takes into account units on tile
if (!BWAPI::Broodwar->isBuildable(x, y) || !BWAPI::Broodwar->hasCreep(x, y) || createdBuilding.find(mySunkPosition) != createdBuilding.end() || BWTA::getGroundDistance(BWAPI::Broodwar->self()->getStartLocation(), mySunkPosition) >= mainToRampDistance) // &&|| b.type == BWAPI::UnitTypes::Zerg_Hatchery
{
return false;
}
return true;
}
bool BuildingManager::isBaseLocation(BWAPI::TilePosition myPosition)
{
const std::set<BWTA::BaseLocation*, std::less<BWTA::BaseLocation*>> locations = BWTA::getBaseLocations();
for (auto x : locations)
{
if (x->getTilePosition() == myPosition)
{
return true;
}
}
return false;
}
/*
//BWAPI::Broodwar->printf("Creep Position %d %d Distance is : %f\n", x->getTilePosition().x, x->getTilePosition().y, tempDist);
double BuildingManager::Euclidean_Distance(int x1, int x2, int y1, int y2)
{
BWAPI::Broodwar->printf("Received request for x1 : %d x2 : %d y1 : %dy2 : %d\n", x1, x2, y1, y1);
double testValue = sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
BWAPI::Broodwar->printf("Returning Euc distance of %f\n", testValue);
return testValue;
}
*/<file_sep>
#include "Common.h"
#include "BuildingManager.h"
#include "Micro.h"
#include "ScoutManager.h"
#include "ProductionManager.h"
using namespace UAlbertaBot;
BuildingManager::BuildingManager()
: _debugMode(false)
, _reservedMinerals(0)
, _reservedGas(0)
{
}
// Get a sunken position depending on whether or not we have an expansion.
BWAPI::TilePosition BuildingManager::getSunkenPosition()
{
// Always make sunkens at natural expansion if you can.
if (createdHatcheriesSet.size() >= 1)
{
BWAPI::TilePosition hatchPosition = createdHatcheriesVector[0];
//BWAPI::Position hatchPositionBWP = BWAPI::Position(hatchPosition);
BWAPI::TilePosition sunkPosition;
const std::set<BWTA::BaseLocation*, std::less<BWTA::BaseLocation*>> locations = BWTA::getBaseLocations();
BWTA::BaseLocation *myLocation;
for (BWTA::BaseLocation *p : locations) {
BWAPI::TilePosition z = p->getTilePosition();
if (z == hatchPosition){
// This is the BWTA::Location of the first hatchery.
myLocation = p;
}
}
// Get the set of mineral patches closest to BWTA::Location of the hatchery(it will return like 8 mineral patches usually in the set)
const BWAPI::Unitset mineralSet = myLocation->getMinerals();
//const std::set<BWAPI::Unit*> mineralSet = myLocation->getMinerals();
int counter3 = 0;
int theX = 0;
int theY = 0;
for (BWAPI::Unit p : mineralSet)
{
// Calculate the difference between LeftMostMineralPatch.x - ExpansionHatchery.x and store it in theX
theX = p->getTilePosition().x - hatchPosition.x;
// Calculate the difference between LeftMostMineralPatch.y - ExpansionHatchery.y and store it in theY
theY = p->getTilePosition().y - hatchPosition.y;
break;
}
int gasX = 0;
int gasY = 0;
int counter4 = 0;
//Get all geysers near the expansion -- it should only return 1 for every map we play..
const BWAPI::Unitset gasSet = myLocation->getGeysers();
for (BWAPI::Unit p : gasSet)
{
// Calculate the difference between Geyser.x- ExpansionHatchery.x and store it in gasX
gasX = p->getTilePosition().x - hatchPosition.x;
// Calculate the difference between Geyser.y- ExpansionHatchery.y and store it in gasY
gasY = p->getTilePosition().y - hatchPosition.y;
break;
}
std::vector<bool> incrementDecrement(8);
bool useGasX = false;
bool useGasY = false;
bool useMinX = false;
bool useMinY = false;
if (abs(gasX) > abs(gasY))
{
useGasX = true;
}
else
{
useGasY = true;
}
if (abs(theX) > abs(theY))
{
useMinX = true;
}
else
{
useMinY = true;
}
// Gas differences is probably more reliable than mineral differences.
if (useGasX && useMinX)
{
useMinX = false;
useMinY = true;
}
// Gas differences is probably more reliable than mineral differences.
if (useGasY && useMinY)
{
useMinY = false;
useMinX = true;
}
// This is where we decide which directions we can make sunkens in
// It is based on X and Y differences in LeftMostMineral - Hatchery and Geyser - Hatchery
// It is not very good right now because we only use two variables. We should use four variables for better dection : theX, theY, gasX, gasY
// If the difference between LeftMostMineral.y - Hatchery.y is negative : It means the mierals are North of the hatchery
// If the difference between Geyser.X - Hatchery.X is negative : It means that the geyser is Left of the Hatchery
if (useMinY && useGasX)
{
if (theY < 0 && gasX < 0)
{
/* Allow the following directions for sunken to be built :
Increase X & Keep Y the same (East)
Increase X & Increase Y (Go South East)
Decrease X & Increase Y (Go South West)
Keep X Same, Increase Y (Go South)
Go NORTHEAST **Test**
*/
incrementDecrement = { true, true, true, true, false, false, true, false };
}
// If the difference between LeftMostMineral.y - Hatchery.y is positive : It means the mierals are South of the hatchery
// If the difference between Geyser.X - Hatchery.X is negative : It means that the geyser is Left of the Hatchery
else if (gasX < 0 && theY > 0)
{
/* Allow the following directions for sunken to be built :
Increase X & Keep Y the same (East)
Increase X & Decrease Y (Go North East)
Decrease X & Decrease Y (Go North West)
Keep X Same, Decrease Y (Go North)
GO SOUTHEAST --> Test
*/
incrementDecrement = { true, true, true, false, true, false, false, true };
}
// If the difference between LeftMostMineral.y - Hatchery.y is negative : It means the mierals are North of the hatchery
// If the difference between Geyser.X - Hatchery.X is positive : It means that the geyser is Right or East of the Hatchery
else if (gasX > 0 && theY < 0)
{
/* Allow the following directions for sunken to be built :
Decrease X & Keep Y the same (West)
Decrease X & Increase Y (Go South West)
Increase X & Increase Y (Go South East)
Keep X Same, Increase Y (Go South)
Go Northwest
*/
incrementDecrement = { true, false, false, true, true, true, true, false };
}
// If the difference between LeftMostMineral.y - Hatchery.y is positive : It means the mierals are South of the hatchery
// If the difference between Geyser.X - Hatchery.X is positive : It means that the geyser is Right or East of the Hatchery
else if (theY > 0 && gasX > 0)
{
/* Decrease X & Keep Y the same (West)
Decrease X & Decrease Y (Go North West)
Increase X & Decrease Y (Go North East)
Don't change X Decrease y (Go North)
Go Southwest
*/
incrementDecrement = { false, true, false, true, true, true, false, true };
}
}
else if (useMinX && useGasY)
{
// If the difference between LeftMostMineral.x - Hatchery.x is positive : It means the mierals are East of the hatchery
// If the difference between Geyser.Y - Hatchery.Y is negative : It means that the geyser is North of the Hatchery
if (gasY < 0 && theX > 0)
{
/* Decrease X(Go West)
Increase Y(Go South)
Decrease X, Increase Y(Go South West)
Decrease X, Decrease Y(Go North West)
I think can try SouthEast ? */
incrementDecrement = { true, false, false, true, true, true, true, false };
}
// If the difference between LeftMostMineral.x - Hatchery.x is positive : It means the mierals are East of the hatchery
// If the difference between Geyser.Y - Hatchery.Y is positive : It means that the geyser is South of the Hatchery
else if (theX > 0 && gasY > 0)
{
/* Decrease X(Go West)
Decrease Y(Go North)
Decrease X, INcrease Y(Go SOuth West)
Decrease X, Decrease Y(Go North West)
I think can try NOrthEast?
*/
incrementDecrement = { false, true, false, true, true, true, false, true };
}
// If the difference between LeftMostMineral.x - Hatchery.x is negative : It means the minerals are West of the hatchery
// If the difference between Geyser.Y - Hatchery.Y is negative : It means that the geyser is North of the Hatchery
else if (gasY < 0 && theX < 0)
{
/* Increase X(Go East)
Increase Y(Go South)
Increase X, Increase Y(Go South East)
Increase X, Decrease Y(Go North East)
I think maybe Southwest is okay?.. Even NW might be okay */
incrementDecrement = { true, true, true, true, false, false, true, false };
}
// If the difference between LeftMostMineral.x - Hatchery.x is negative : It means the minerals are West of the hatchery
// If the difference between Geyser.Y - Hatchery.Y is positive : It means that the geyser is South of the Hatchery
else if (gasY > 0 && theX < 0)
{
/* Increase X(Go East)
Decrease Y(Go North)
Increase X, Increase Y(Go South East)
Increase X, Decrease Y(Go North East)
I think maybe Northwest is okay? */
incrementDecrement = { true, true, true, false, true, false, false, true };
}
}
BWAPI::Unit pExpansion = BWAPI::Broodwar->getClosestUnit(BWAPI::Position(hatchPosition), BWAPI::Filter::IsResourceDepot);
BWAPI::Unitset myUnits = pExpansion->getUnitsInRadius(200);
BWAPI::UnitType larva = BWAPI::UnitTypes::Zerg_Larva;
BWAPI::UnitType egg = BWAPI::UnitTypes::Zerg_Egg;
std::set<BWAPI::TilePosition> stuffBlocking;
for (BWAPI::Unit p : myUnits)
{
if (p->getType() == larva || p->getType() == egg)
{
stuffBlocking.insert(p->getTilePosition());
}
}
int newx, newy;
int outercounter = 0;
int counter = 0;
newx = hatchPosition.x;
newy = hatchPosition.y;
int beginX = hatchPosition.x;
int beginY = hatchPosition.y;
BWAPI::UnitType sunk = BWAPI::UnitTypes::Zerg_Creep_Colony;
Building b(sunk, sunkPosition);
//test4 = BuildingPlacer::Instance().canBuildHere(sunkPosition, b);
// Form a new sunken position that starts at the hatchery positive.
sunkPosition = BWAPI::TilePosition(newx, newy);
/* We check the following conditions :
Do we not have creep at the sunken position?
Can we not build at the sunken position?
Have we built at this position before?
If any of these are true and counter <= 7 --> Remain in loop
Is the counter <= 7 --> Makes sure not to go out of bounds for the incrementDecrement vector
*/
while ((!BWAPI::Broodwar->hasCreep(sunkPosition) || !BuildingPlacer::Instance().canBuildHere(sunkPosition, b) || stuffBlocking.find(sunkPosition)!= stuffBlocking.end() || createdBuilding.find(sunkPosition) != createdBuilding.end()) && counter <= 7)
{
if (counter == 8)
{
break;
}
// If the boolean is true for incrementDecrement and we have checked 15 x+0..x+15 / y+0..y+15 positions in this direction
if (incrementDecrement[counter] && outercounter <= 30)
{
//Increase x Increase y (Try to make sunken in South East direction)
if (counter == 0)
{
beginX += 1;
beginY += 1;
}
//Increase x Decrease y (Try to make sunken in North East)
else if (counter == 1)
{
beginX += 1;
beginY -= 1;
}
//Increase x Don't Change y (Try to make sunken East)
else if (counter == 2)
{
beginX += 1;
}
//Decrease x Increase y (Try to make sunken South West)
else if (counter == 3)
{
beginX -= 1;
beginY += 1;
}
//Decrease x Decrease y (Try to make sunken North West)
else if (counter == 4)
{
beginX -= 1;
beginY -= 1;
}
//Decrease x Dont Change y (Try to make sunken (West) )
else if (counter == 5)
{
beginX -= 1;
}
//Don't change X Increase y Try to make sunken South
else if (counter == 6)
{
beginY += 1;
}
//Don't change X Decrease y Try to make sunken North
else if (counter == 7)
{
beginY -= 1;
}
}
else
{
// Since this direction is set to false in incremenetDecrement OR we tried 15 possibile steps, then :
//Reset X direction to hatcheryX
beginX = newx;
//Reset Y direction hatcheryY
beginY = newy;
//Reset outerCounter to -1(Becomes 0)
outercounter = -1;
//Increment counter to traverse incrementDecrement vector
counter++;
}
// Increment steps taken +1
outercounter += 1;
// Try to make a sunken at the given X and Y value
sunkPosition = BWAPI::TilePosition(beginX, beginY);
//b.desiredPosition.x = sunkPosition.x;
//b.desiredPosition.y = sunkPosition.y;
}
// Now that we are out of the while loop --> If counter doesnt equal 8, it means that we got a success from one of the 8 directions so return the last sunkPosition that resulted in this.
if (counter != 8)
{
return sunkPosition;
}
// Since counter == 8, it means we tried all 8 directions and couldnt find a sunken position, so return None(sunken will be made in main base)
else
{
return BWAPI::TilePositions::None;
}
}
return BWAPI::TilePositions::None;
}
// gets called every frasme from GameCommander
void BuildingManager::update()
{
validateWorkersAndBuildings(); // check to see if assigned workers have died en route or while constructing
assignWorkersToUnassignedBuildings(); // assign workers to the unassigned buildings and label them 'planned'
constructAssignedBuildings(); // for each planned building, if the worker isn't constructing, send the command
checkForStartedConstruction(); // check to see if any buildings have started construction and update data structures
checkForDeadTerranBuilders(); // if we are terran and a building is under construction without a worker, assign a new one
checkForCompletedBuildings(); // check to see if any buildings have completed and update data structures
}
bool BuildingManager::isBeingBuilt(BWAPI::UnitType type)
{
for (auto & b : _buildings)
{
if (b.type == type)
{
return true;
}
}
return false;
}
// STEP 1: DO BOOK KEEPING ON WORKERS WHICH MAY HAVE DIED
void BuildingManager::validateWorkersAndBuildings()
{
// TODO: if a terran worker dies while constructing and its building
// is under construction, place unit back into buildingsNeedingBuilders
std::vector<Building> toRemove;
// find any buildings which have become obsolete
for (auto & b : _buildings)
{
if (b.status != BuildingStatus::UnderConstruction)
{
continue;
}
if (b.buildingUnit == nullptr || !b.buildingUnit->getType().isBuilding() || b.buildingUnit->getHitPoints() <= 0)
{
toRemove.push_back(b);
}
}
removeBuildings(toRemove);
}
// STEP 2: ASSIGN WORKERS TO BUILDINGS WITHOUT THEM
void BuildingManager::assignWorkersToUnassignedBuildings()
{
// for each building that doesn't have a builder, assign one
for (Building & b : _buildings)
{
if (b.status != BuildingStatus::Unassigned)
{
continue;
}
if (_debugMode) { BWAPI::Broodwar->printf("Assigning Worker To: %s", b.type.getName().c_str()); }
// grab a worker unit from WorkerManager which is closest to this final position
BWAPI::Unit workerToAssign = WorkerManager::Instance().getBuilder(b);
if (workerToAssign)
{
//BWAPI::Broodwar->printf("VALID WORKER BEING ASSIGNED: %d", workerToAssign->getID());
// TODO: special case of terran building whose worker died mid construction
// send the right click command to the buildingUnit to resume construction
// skip the buildingsAssigned step and push it back into buildingsUnderConstruction
b.builderUnit = workerToAssign;
BWAPI::TilePosition testLocation = getBuildingLocation(b);
if (!testLocation.isValid())
{
continue;
}
b.finalPosition = testLocation;
// reserve this building's space
BuildingPlacer::Instance().reserveTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight());
b.status = BuildingStatus::Assigned;
}
}
}
// STEP 3: ISSUE CONSTRUCTION ORDERS TO ASSIGN BUILDINGS AS NEEDED
void BuildingManager::constructAssignedBuildings()
{
for (auto & b : _buildings)
{
if (b.status != BuildingStatus::Assigned)
{
continue;
}
// if that worker is not currently constructing
if (!b.builderUnit->isConstructing())
{
// if we haven't explored the build position, go there
if (!isBuildingPositionExplored(b))
{
Micro::SmartMove(b.builderUnit, BWAPI::Position(b.finalPosition));
}
// if this is not the first time we've sent this guy to build this
// it must be the case that something was in the way of building
else if (b.buildCommandGiven)
{
// tell worker manager the unit we had is not needed now, since we might not be able
// to get a valid location soon enough
WorkerManager::Instance().finishedWithWorker(b.builderUnit);
// free the previous location in reserved
BuildingPlacer::Instance().freeTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight());
// nullify its current builder unit
b.builderUnit = nullptr;
// reset the build command given flag
b.buildCommandGiven = false;
// add the building back to be assigned
b.status = BuildingStatus::Unassigned;
}
else
{
// issue the build order!
if (b.type == 131)
{
createdHatcheriesSet.insert(b.finalPosition);
createdHatcheriesVector.push_back(b.finalPosition);
firstHatcheryPosition = BWAPI::Position(b.finalPosition);
}
//|| b.type == 146 is sunken
else if (b.type == 143)
{
BWAPI::TilePosition sunkPos = getSunkenPosition();
//b.finalPosition = sunkPos;
if (sunkPos != BWAPI::TilePositions::None)
{
b.finalPosition = sunkPos;
}
else if (sunkPos == BWAPI::TilePositions::None)
{
//BWAPI::Position myPos = b.builderUnit->getPosition();
//myPos.x += 5;
//myPos.y += 5;
//b.builderUnit->move(myPos);
BWAPI::TilePosition sunkPos = getSunkenPosition();
if (sunkPos != BWAPI::TilePositions::None)
{
b.finalPosition = sunkPos;
}
else
{
//_reservedMinerals -= 75;
//_reservedMinerals -= b.buildingUnit->getType().mineralPrice();
//_reservedGas -= b.buildingUnit->getType().gasPrice();
//b.buildCommandGiven = true;
//std::vector<Building> toRemove;
//toRemove.push_back(b);
//removeBuildings(toRemove);
//MetaType type(BWAPI::UnitTypes::Zerg_Creep_Colony);
//ProductionManager::Instance()._queue.queueAsHighestPriority(type, true);
/*
//removeBuildings(b.buildingUnit);
MetaType type(BWAPI::UnitTypes::Zerg_Creep_Colony);
ProductionManager::Instance()._queue.queueAsHighestPriority(type, true);
b.buildCommandGiven = true;
b.underConstruction = true;
//b.builderUnit = nullptr;
b.status = BuildingStatus::UnderConstruction;
//std::vector<Building> toRemove;
//toRemove.push_back(b);
//BuildingPlacer::Instance().freeTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight());
//removeBuildings(toRemove);
return;
*/
}
}
createdSunkenSet.insert(b.finalPosition);
createdSunkenVector.push_back(b.finalPosition);
}
b.builderUnit->build(b.type, b.finalPosition);
createdBuilding.insert(b.finalPosition);
// set the flag to true
b.buildCommandGiven = true;
}
}
}
}
// STEP 4: UPDATE DATA STRUCTURES FOR BUILDINGS STARTING CONSTRUCTION
void BuildingManager::checkForStartedConstruction()
{
// for each building unit which is being constructed
for (auto & buildingStarted : BWAPI::Broodwar->self()->getUnits())
{
// filter out units which aren't buildings under construction
if (!buildingStarted->getType().isBuilding() || !buildingStarted->isBeingConstructed())
{
continue;
}
// check all our building status objects to see if we have a match and if we do, update it
for (auto & b : _buildings)
{
if (b.status != BuildingStatus::Assigned)
{
continue;
}
// check if the positions match
if (b.finalPosition == buildingStarted->getTilePosition())
{
// the resources should now be spent, so unreserve them
_reservedMinerals -= buildingStarted->getType().mineralPrice();
_reservedGas -= buildingStarted->getType().gasPrice();
// flag it as started and set the buildingUnit
b.underConstruction = true;
b.buildingUnit = buildingStarted;
// if we are zerg, the buildingUnit now becomes nullptr since it's destroyed
if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Zerg)
{
b.builderUnit = nullptr;
// if we are protoss, give the worker back to worker manager
}
else if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Protoss)
{
// if this was the gas steal unit then it's the scout worker so give it back to the scout manager
if (b.isGasSteal)
{
ScoutManager::Instance().setWorkerScout(b.builderUnit);
}
// otherwise tell the worker manager we're finished with this unit
else
{
WorkerManager::Instance().finishedWithWorker(b.builderUnit);
}
b.builderUnit = nullptr;
}
// put it in the under construction vector
b.status = BuildingStatus::UnderConstruction;
// free this space
BuildingPlacer::Instance().freeTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight());
// only one building will match
break;
}
}
}
}
// STEP 5: IF WE ARE TERRAN, THIS MATTERS, SO: LOL
void BuildingManager::checkForDeadTerranBuilders() {}
// STEP 6: CHECK FOR COMPLETED BUILDINGS
void BuildingManager::checkForCompletedBuildings()
{
std::vector<Building> toRemove;
// for each of our buildings under construction
for (auto & b : _buildings)
{
if (b.status != BuildingStatus::UnderConstruction)
{
continue;
}
// if the unit has completed
if (b.buildingUnit->isCompleted())
{
if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Zerg)
{
if (b.buildingUnit->getType() == BWAPI::UnitTypes::Zerg_Creep_Colony)
{
//b.buildingUnit->upgrade(b.buildingUnit->getUpgrade());
//b.buildingUnit->buildAddon(BWAPI::UnitTypes::Zerg_Sunken_Colony);
// MAKE SUNKEN
//b.buildingUnit->morph(BWAPI::UnitTypes::Zerg_Sunken_Colony);
MetaType type(BWAPI::UnitTypes::Zerg_Sunken_Colony);
ProductionManager::Instance()._queue.queueAsHighestPriority(type, true);
}
/*
if (b.buildingUnit->getType() == BWAPI::UnitTypes::Zerg_Hatchery)
{
for (BWAPI::Unit p : BWAPI::Broodwar->self()->getUnits())
{
if (!madeFirstSunken && p->getType().isWorker() && p->getPosition() == firstHatcheryPosition)
{
//BWAPI::Position tempPosition;
//tempPosition.x = b.finalPosition.x + 3;
//tempPosition.y = b.finalPosition.y + 3;
MetaType type(BWAPI::UnitTypes::Zerg_Creep_Colony);
ProductionManager::Instance()._queue.queueAsHighestPriority(type, true);
/*
BWAPI::TilePosition sunkPos = getSunkenPosition();
createdSunkenSet.insert(sunkPos);
createdSunkenVector.push_back(sunkPos);
createdBuilding.insert(sunkPos);
p->build(BWAPI::UnitTypes::Zerg_Hatchery, sunkPos);
madeFirstSunken = true;
BWAPI::TilePosition sunkPos2 = getSunkenPosition();
createdSunkenSet.insert(sunkPos2);
createdSunkenVector.push_back(sunkPos2);
createdBuilding.insert(sunkPos2);
p->build(BWAPI::UnitTypes::Zerg_Hatchery, sunkPos2);
//b.builderUnit->build(b.type, b.finalPosition);
break;
//candidateProducers.insert(p);
}
}
}
*/
}
// if we are terran, give the worker back to worker manager
if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Terran)
{
if (b.isGasSteal)
{
ScoutManager::Instance().setWorkerScout(b.builderUnit);
}
// otherwise tell the worker manager we're finished with this unit
else
{
WorkerManager::Instance().finishedWithWorker(b.builderUnit);
}
}
// remove this unit from the under construction vector
toRemove.push_back(b);
}
else
{
/*
if (b.type == 131 && b.buildingUnit->getHitPoints() >= 1050 && !sentFirstDroneForSunken)
{
BWAPI::Broodwar->printf("Send Drone");
BWAPI::Unitset candidateProducers;
for (BWAPI::Unit p : BWAPI::Broodwar->self()->getUnits())
{
if (p->getType().isWorker())
{
//BWAPI::Position tempPosition;
//tempPosition.x = b.finalPosition.x + 3;
//tempPosition.y = b.finalPosition.y + 3;
p->move(BWAPI::Position(b.finalPosition));
break;
//candidateProducers.insert(p);
}
}
//BWAPI::Unit myUnit = ProductionManager::Instance().getClosestUnitToPosition(candidateProducers, BWAPI::Position(b.finalPosition));
/*
BWAPI::Unit closestUnit = nullptr;
double minDist(1000000);
for (auto & unit : candidateProducers)
{
UAB_ASSERT(unit != nullptr, "Unit was null");
double distance = unit->getDistance(BWAPI::Position(b.finalPosition));
if (!closestUnit || distance < minDist)
{
closestUnit = unit;
minDist = distance;
}
}
//MetaType m = MetaType(b.buildingUnit->getType());
//MetaType m = MetaType(BWAPI::UnitTypes::Zerg_Drone);
//BWAPI::Unit myUnit = .getProducer(m, BWAPI::Position(b.finalPosition));
closestUnit->move(BWAPI::Position(b.finalPosition));
sentFirstDroneForSunken = true;
}
int x = 0;
*/
}
}
removeBuildings(toRemove);
}
// COMPLETED
bool BuildingManager::isEvolvedBuilding(BWAPI::UnitType type)
{
if (type == BWAPI::UnitTypes::Zerg_Sunken_Colony ||
type == BWAPI::UnitTypes::Zerg_Spore_Colony ||
type == BWAPI::UnitTypes::Zerg_Lair ||
type == BWAPI::UnitTypes::Zerg_Hive ||
type == BWAPI::UnitTypes::Zerg_Greater_Spire)
{
return true;
}
return false;
}
// add a new building to be constructed
void BuildingManager::addBuildingTask(BWAPI::UnitType type, BWAPI::TilePosition desiredLocation, bool isGasSteal)
{
_reservedMinerals += type.mineralPrice();
_reservedGas += type.gasPrice();
Building b(type, desiredLocation);
b.isGasSteal = isGasSteal;
b.status = BuildingStatus::Unassigned;
_buildings.push_back(b);
}
bool BuildingManager::isBuildingPositionExplored(const Building & b) const
{
BWAPI::TilePosition tile = b.finalPosition;
// for each tile where the building will be built
for (int x = 0; x<b.type.tileWidth(); ++x)
{
for (int y = 0; y<b.type.tileHeight(); ++y)
{
if (!BWAPI::Broodwar->isExplored(tile.x + x, tile.y + y))
{
return false;
}
}
}
return true;
}
char BuildingManager::getBuildingWorkerCode(const Building & b) const
{
return b.builderUnit == nullptr ? 'X' : 'W';
}
int BuildingManager::getReservedMinerals()
{
return _reservedMinerals;
}
int BuildingManager::getReservedGas()
{
return _reservedGas;
}
void BuildingManager::drawBuildingInformation(int x, int y)
{
if (!Config::Debug::DrawBuildingInfo)
{
return;
}
for (auto & unit : BWAPI::Broodwar->self()->getUnits())
{
BWAPI::Broodwar->drawTextMap(unit->getPosition().x, unit->getPosition().y + 5, "\x07%d", unit->getID());
}
BWAPI::Broodwar->drawTextScreen(x, y, "\x04 Building Information:");
BWAPI::Broodwar->drawTextScreen(x, y + 20, "\x04 Name");
BWAPI::Broodwar->drawTextScreen(x + 150, y + 20, "\x04 State");
int yspace = 0;
for (const auto & b : _buildings)
{
if (b.status == BuildingStatus::Unassigned)
{
BWAPI::Broodwar->drawTextScreen(x, y + 40 + ((yspace)* 10), "\x03 %s", b.type.getName().c_str());
BWAPI::Broodwar->drawTextScreen(x + 150, y + 40 + ((yspace++) * 10), "\x03 Need %c", getBuildingWorkerCode(b));
}
else if (b.status == BuildingStatus::Assigned)
{
BWAPI::Broodwar->drawTextScreen(x, y + 40 + ((yspace)* 10), "\x03 %s %d", b.type.getName().c_str(), b.builderUnit->getID());
BWAPI::Broodwar->drawTextScreen(x + 150, y + 40 + ((yspace++) * 10), "\x03 A %c (%d,%d)", getBuildingWorkerCode(b), b.finalPosition.x, b.finalPosition.y);
int x1 = b.finalPosition.x * 32;
int y1 = b.finalPosition.y * 32;
int x2 = (b.finalPosition.x + b.type.tileWidth()) * 32;
int y2 = (b.finalPosition.y + b.type.tileHeight()) * 32;
BWAPI::Broodwar->drawLineMap(b.builderUnit->getPosition().x, b.builderUnit->getPosition().y, (x1 + x2) / 2, (y1 + y2) / 2, BWAPI::Colors::Orange);
BWAPI::Broodwar->drawBoxMap(x1, y1, x2, y2, BWAPI::Colors::Red, false);
}
else if (b.status == BuildingStatus::UnderConstruction)
{
BWAPI::Broodwar->drawTextScreen(x, y + 40 + ((yspace)* 10), "\x03 %s %d", b.type.getName().c_str(), b.buildingUnit->getID());
BWAPI::Broodwar->drawTextScreen(x + 150, y + 40 + ((yspace++) * 10), "\x03 Const %c", getBuildingWorkerCode(b));
}
}
}
BuildingManager & BuildingManager::Instance()
{
static BuildingManager instance;
return instance;
}
std::vector<BWAPI::UnitType> BuildingManager::buildingsQueued()
{
std::vector<BWAPI::UnitType> buildingsQueued;
for (const auto & b : _buildings)
{
if (b.status == BuildingStatus::Unassigned || b.status == BuildingStatus::Assigned)
{
buildingsQueued.push_back(b.type);
}
}
return buildingsQueued;
}
BWAPI::TilePosition BuildingManager::getBuildingLocation(const Building & b)
{
int numPylons = BWAPI::Broodwar->self()->completedUnitCount(BWAPI::UnitTypes::Protoss_Pylon);
if (b.isGasSteal)
{
BWTA::BaseLocation * enemyBaseLocation = InformationManager::Instance().getMainBaseLocation(BWAPI::Broodwar->enemy());
UAB_ASSERT(enemyBaseLocation, "Should have enemy base location before attempting gas steal");
UAB_ASSERT(enemyBaseLocation->getGeysers().size() > 0, "Should have spotted an enemy geyser");
for (auto & unit : enemyBaseLocation->getGeysers())
{
BWAPI::TilePosition tp(unit->getInitialTilePosition());
return tp;
}
}
if (b.type.requiresPsi() && numPylons == 0)
{
return BWAPI::TilePositions::None;
}
if (b.type.isRefinery())
{
return BuildingPlacer::Instance().getRefineryPosition();
}
if (b.type.isResourceDepot())
{
// get the location
BWAPI::TilePosition tile = MapTools::Instance().getNextExpansion();
return tile;
}
// set the building padding specifically
int distance = b.type == BWAPI::UnitTypes::Protoss_Photon_Cannon ? 0 : Config::Macro::BuildingSpacing;
if (b.type == BWAPI::UnitTypes::Protoss_Pylon && (numPylons < 3))
{
distance = Config::Macro::PylonSpacing;
}
// get a position within our region
return BuildingPlacer::Instance().getBuildLocationNear(b, distance, false);
}
void BuildingManager::removeBuildings(const std::vector<Building> & toRemove)
{
for (auto & b : toRemove)
{
auto & it = std::find(_buildings.begin(), _buildings.end(), b);
if (it != _buildings.end())
{
_buildings.erase(it);
}
}
}
<file_sep>#pragma once
#include <Common.h>
#include <BWAPI.h>
namespace UAlbertaBot
{
namespace Micro
{
void SmartAttackUnit(BWAPI::Unit attacker, BWAPI::Unit target);
void SmartAttackMove(BWAPI::Unit attacker, const BWAPI::Position & targetPosition);
void SmartMove(BWAPI::Unit attacker, const BWAPI::Position & targetPosition);
void SmartRightClick(BWAPI::Unit unit, BWAPI::Unit target);
void SmartLaySpiderMine(BWAPI::Unit unit, BWAPI::Position pos);
void SmartRepair(BWAPI::Unit unit, BWAPI::Unit target);
void SmartKiteTarget(BWAPI::Unit rangedUnit, BWAPI::Unit target);
void MutaDanceTarget(BWAPI::Unit muta, BWAPI::Unit target);
BWAPI::Position GetKiteVector(BWAPI::Unit unit, BWAPI::Unit target);
void Rotate(double &x, double &y, double angle);
void Normalize(double &x, double &y);
void drawAPM(int x, int y);
//TOMMY
void StormDodge(BWAPI::Unit unit); // TO BE IMPLEMENTED. the given unit moves away from the nearest templar. move away for 2 seconds and come back as the storm ends
BWAPI::Position GetNearbyPos(BWAPI::Position pos); //TO BE IMPLEMENTED. helper function in the case that you move to an unwalkable tile
int CalcDistance(BWAPI::Unit unit, int time); // TO BE IMPLEMENTED. helper function that gets a distance a unit will travel
// in the given time
BWAPI::Position GetFleeVector(BWAPI::Unit unit, BWAPI::Unit enemy); // TO BE IMPLEMENTED. helper function that gets the direction
// of movement to flee directly away a given enemy
};
}<file_sep>#pragma once
#include "Common.h"
#include "BWTA.h"
#include "BuildOrderQueue.h"
#include "InformationManager.h"
#include "WorkerManager.h"
#include "BuildOrder.h"
namespace UAlbertaBot
{
typedef std::pair<MetaType, size_t> MetaPair;
typedef std::vector<MetaPair> MetaPairVector;
struct Strategy
{
std::string _name;
BWAPI::Race _race;
int _wins;
int _losses;
BuildOrder _buildOrder;
Strategy()
: _name("None")
, _race(BWAPI::Races::None)
, _wins(0)
, _losses(0)
{
}
Strategy(const std::string & name, const BWAPI::Race & race, const BuildOrder & buildOrder)
: _name(name)
, _race(race)
, _wins(0)
, _losses(0)
, _buildOrder(buildOrder)
{
}
};
class StrategyManager
{
StrategyManager();
BWAPI::Race _selfRace;
BWAPI::Race _enemyRace;
std::map<std::string, Strategy> _strategies; // contains strategies parsed from Config.txt. seems only to be used
// for getOpeningBookBuildOrder()
int _totalGamesPlayed;
const BuildOrder _emptyBuildOrder;
void writeResults();
const int getScore(BWAPI::Player player) const;
const double getUCBValue(const size_t & strategy) const;
const bool shouldExpandNow() const; // could be modified to give more precise expansions
const MetaPairVector getProtossBuildOrderGoal() const;
const MetaPairVector getTerranBuildOrderGoal() const;
const MetaPairVector getZergBuildOrderGoal() const; // uses the strategy in Config.cpp to decide what units to make
// independent of Config.txt. this build order seems to be looped
//NEW
public:
static StrategyManager & Instance();
void onEnd(const bool isWinner);
void addStrategy(const std::string & name, Strategy & strategy); // currently only used by the parser
void setLearnedStrategy();
void readResults();
const bool regroup(int numInRadius); // not implemented
const bool rushDetected(); // not implemented
const int defendWithWorkers(); // not implemented
const MetaPairVector getBuildOrderGoal(); // called by performBuildOrderSearch in ProdManager
// passes build order goals to BOSS through ProdManager
// called in an update loop
const BuildOrder & getOpeningBookBuildOrder() const; // use strat in Config.cpp. only called once
// theory: since ProdManager's _queue is not updated until
// its current units are completed, openingBookBO builds all
// its items, then you use getBOGoal to continue production
const bool shouldBuildSunkens() const; // TO-DO: needs to account for enemy unit production
const bool shouldMakeMacroHatchery() const; // TO-DO: needs to replace shouldExpand() at >3000 minerals
};
}<file_sep>// STEP 6: CHECK FOR COMPLETED BUILDINGS
void BuildingManager::checkForCompletedBuildings()
{
std::vector<Building> toRemove;
// for each of our buildings under construction
for (auto & b : _buildings)
{
if (b.status != BuildingStatus::UnderConstruction)
{
continue;
}
// if the unit has completed
if (b.buildingUnit->isCompleted())
{
if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Zerg)
{
if (b.buildingUnit->getType() == BWAPI::UnitTypes::Zerg_Creep_Colony)
{
//b.buildingUnit->upgrade(b.buildingUnit->getUpgrade());
//b.buildingUnit->buildAddon(BWAPI::UnitTypes::Zerg_Sunken_Colony);
// MAKE SUNKEN
//b.buildingUnit->morph(BWAPI::UnitTypes::Zerg_Sunken_Colony);
MetaType type(BWAPI::UnitTypes::Zerg_Sunken_Colony);
ProductionManager::Instance()._queue.queueAsHighestPriority(type, true);
}
if (b.buildingUnit->getType() == BWAPI::UnitTypes::Zerg_Hatchery)
{
createdHatchery = true;
}
}
if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Terran)
{
if (b.isGasSteal)
{
ScoutManager::Instance().setWorkerScout(b.builderUnit);
}
// otherwise tell the worker manager we're finished with this unit
else
{
WorkerManager::Instance().finishedWithWorker(b.builderUnit);
}
}
// remove this unit from the under construction vector
toRemove.push_back(b);
/*
for (BWAPI::Unit p : BWAPI::Broodwar->self()->getUnits())
{
if (!madeFirstSunken && p->getType().isWorker() && p->getPosition() == firstHatcheryPosition)
{
//BWAPI::Position tempPosition;
//tempPosition.x = b.finalPosition.x + 3;
//tempPosition.y = b.finalPosition.y + 3;
MetaType type(BWAPI::UnitTypes::Zerg_Creep_Colony);
ProductionManager::Instance()._queue.queueAsHighestPriority(type, true);
/*
BWAPI::TilePosition sunkPos = getSunkenPosition();
createdSunkenSet.insert(sunkPos);
createdSunkenVector.push_back(sunkPos);
createdBuilding.insert(sunkPos);
p->build(BWAPI::UnitTypes::Zerg_Hatchery, sunkPos);
madeFirstSunken = true;
BWAPI::TilePosition sunkPos2 = getSunkenPosition();
createdSunkenSet.insert(sunkPos2);
createdSunkenVector.push_back(sunkPos2);
createdBuilding.insert(sunkPos2);
p->build(BWAPI::UnitTypes::Zerg_Hatchery, sunkPos2);
//b.builderUnit->build(b.type, b.finalPosition);
break;
//candidateProducers.insert(p);
}
}
}
*/
}
else
{
if (b.type == 131 && b.buildingUnit->getHitPoints() >= 1050 && !sentFirstDroneForSunken)
{
//BWAPI::Broodwar->printf("Send Drone");
//BWAPI::Unitset candidateProducers;
for (BWAPI::Unit p : BWAPI::Broodwar->self()->getUnits())
{
if (p->getType().isWorker())
{
//BWAPI::Position tempPosition;
//tempPosition.x = b.finalPosition.x + 3;
//tempPosition.y = b.finalPosition.y + 3;
p->move(BWAPI::Position(b.finalPosition));
break;
//candidateProducers.insert(p);
}
}
sentFirstDroneForSunken = true;
}
}
// if we are terran, give the worker back to worker manager
}
}
}
removeBuildings(toRemove);
} | 0a793ea3e39550b65b132a97ec17b12a2df8db64 | [
"C++"
]
| 15 | C++ | 0x4849/c350 | ec9ddcf6b970a85f2fa1b9d7c540aeabd2fdaae6 | 671b4c8090339360d555f72d4d4855941d18a821 |
refs/heads/upload-protfolio | <repo_name>chenghsj/Web_Insta_Profile_clone<file_sep>/src/Profile/Carousel.js
import React from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import SwiperCore, { Navigation, Pagination } from "swiper";
import "swiper/swiper.scss";
import "swiper/components/navigation/navigation.scss";
import "swiper/components/pagination/pagination.scss";
SwiperCore.use([Navigation, Pagination]);
function Carousel(props) {
return (
<Swiper
navigation
pagination={{
clickable: true,
}}
slidesPerView={1}
speed={700}
>
{props.imgList.map((img, i) => (
<SwiperSlide key={`slide-${i}`}>
<img
style={{ width: "100%", height: "95%", objectFit: "contain" }}
src={img}
alt={`Slide ${i}`}
/>
</SwiperSlide>
))}
</Swiper>
);
}
export default Carousel;
<file_sep>/src/Profile/styles/SignModalStyle.js
import { makeStyles } from "@material-ui/core/styles";
import { paperStyle, buttonStyle } from "./reuseableStyle";
export const useStyles = makeStyles((theme) => ({
paper: paperStyle(theme),
loginContainer: {
height: "1.5rem",
display: "flex",
justifyContent: "flex-end",
boxSizing: "border-box",
[theme.breakpoints.down("xs")]: {
transform: "scale(0.9)",
height: "auto",
display: "flex",
flexDirection: "column",
alignItems: "end",
},
},
button: (isDark) => buttonStyle(theme, isDark),
}));
<file_sep>/src/Profile/PhotoList.js
import React, { useState, useEffect } from "react";
import Photo from "./Photo";
import { makeStyles } from "@material-ui/core/styles";
import { db } from "../config/firebase.config";
import { useAuthContext } from "./contexts/Auth.context";
function PhotoList() {
const [posts, setPosts] = useState([]);
const [{ user }] = useAuthContext();
const classes = useStyles(!!user);
useEffect(() => {
if (user?.displayName) {
db.collection(user.displayName)
.doc(user.uid)
.collection("posts")
.orderBy("timestamp", "desc")
.onSnapshot((snapshot) => {
setPosts(
snapshot.docs.map((doc) => ({
id: doc.id,
post: doc.data(),
}))
);
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [user]);
return (
<div className={classes.root}>
{user ? (
posts.map(({ post, id }, i) => (
<Photo
index={i}
coverImage={post.coverImage}
images={post.images}
title={post.title}
desc={post.description}
key={id}
id={id}
/>
))
) : (
<div className={classes.intro}>
<h2>Sign Up and Upload Something</h2>
<p>
( or try sign in with email: <strong><EMAIL></strong> with
password: <strong><PASSWORD></strong> )
</p>
<p>This web is for testing. Do not use any real email.</p>
</div>
)}
</div>
);
}
export default PhotoList;
const useStyles = makeStyles((theme) => ({
root: {
position: "relative",
display: "flex",
flexWrap: "wrap",
justifyContent: (user) => (user ? "flex-start" : "center"),
width: "100%",
left: (user) => (user ? "5%" : "5px"),
[theme.breakpoints.down("xs")]: {
left: "0 !important",
justifyContent: "flex-start !important",
padding: "0 3.3%",
},
},
intro: {
color: "#b2b2b2",
position: "relative",
left: "-5px",
margin: "0 1rem",
},
}));
<file_sep>/src/Profile/ImageUpload.js
import React, { useState } from "react";
import { getModalStyle } from "./styles/reuseableStyle";
import { useStyles } from "./styles/ImageUploadStyle";
import { storage, db } from "../config/firebase.config";
import { useAuthContext } from "./contexts/Auth.context";
import firebase from "firebase";
import {
Button,
Grid,
Modal,
TextField,
LinearProgress,
} from "@material-ui/core";
export default function ImageUpload(props) {
const [{ user, isDark }] = useAuthContext();
const [modalStyle] = useState(getModalStyle);
const classes = useStyles();
const [title, setTitle] = useState("");
const [desc, setDesc] = useState("");
const [images, setImages] = useState([]);
const [progress, setProgress] = useState(null);
const handleImages = (e) => {
for (let file of e.target.files) {
setImages((prev) => [...prev, file]);
}
};
const handleUpload = (e) => {
e.preventDefault();
const promises = [];
for (let image of images) {
const uploadTask = storage
.ref(`images/${user.displayName}/${user.uid}/${title}/${image.name}`)
.put(image);
promises.push(uploadTask);
uploadTask.on(
firebase.storage.TaskEvent.STATE_CHANGED,
(snapshot) => {
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(progress);
// eslint-disable-next-line default-case
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log("Upload paused");
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log("Uploading...");
break;
}
},
(error) => console.log(error.message)
);
}
Promise.all(promises)
.then(async (res) => {
const promises = [];
for (let i = 0; i < res.length; i++) {
const imageURL = await res[i].ref.getDownloadURL();
promises.push(imageURL);
}
const imagesURL = await Promise.all(promises);
await db
.collection(user.displayName)
.doc(user.uid)
.collection("posts")
.doc()
.set({
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
username: user.displayName,
title: title,
description: desc,
coverImage: imagesURL[0],
images: imagesURL,
});
})
.then(() => {
console.log("Upload finished");
handleModalClose();
})
.catch((error) => console.log(error.message));
};
const handleModalClose = () => {
setTitle("");
setDesc("");
setImages([]);
setProgress(null);
props.setOpenUpload(false);
};
return (
<div>
<button
onClick={() => props.setOpenUpload(true)}
className={classes.button}
style={{
background: isDark && "white",
color: isDark && "black",
}}
>
Upload
</button>
<Modal
style={{ cursor: !!progress && "progress" }}
open={props.openUpload}
onClose={() => {
if (!progress) {
handleModalClose();
}
}}
>
<div style={modalStyle} className={classes.paper}>
<form>
<Grid container direction="column" spacing={2}>
<Grid item>
<TextField
disabled={!!progress}
fullWidth
required
type="text"
id="title-required"
label="Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</Grid>
<Grid item>
<TextField
disabled={!!progress}
fullWidth
type="text"
id="description-required"
label="Description"
value={desc}
onChange={(e) => setDesc(e.target.value)}
/>
</Grid>
<Grid item>
<TextField
disabled={!!progress}
variant="outlined"
size="small"
fullWidth
required
type="file"
id="file-required"
inputProps={{
multiple: true,
}}
InputProps={{
classes: { inputMarginDense: classes.fileInput },
}}
onChange={handleImages}
/>
</Grid>
{!!progress && (
<Grid item>
<LinearProgress
classes={{
root: classes.progressBar,
colorPrimary: classes.colorPrimary,
barColorPrimary: classes.barColorPrimary,
bar1Determinate: classes.bar1Determinate,
}}
variant="determinate"
value={progress}
/>
</Grid>
)}
<Grid item>
<Button
disabled={!!progress || !!!title || !!!images[0]}
fullWidth
color={!!!progress ? "primary" : "default"}
variant="contained"
disableElevation
onClick={(e) => {
if (title && images[0]) handleUpload(e);
}}
>
{progress ? "Uploading..." : "Upload"}
</Button>
</Grid>
</Grid>
</form>
</div>
</Modal>
</div>
);
}
<file_sep>/README.md
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
[Website](https://portfolio-b2f11.web.app/)
try sign in with:
email: <EMAIL>
password: <PASSWORD>
<file_sep>/src/Profile/styles/reuseableStyle.js
export const paperStyle = (theme) => ({
outline: "none",
borderRadius: "10px",
display: "flex",
flexDirection: "column",
position: "absolute",
width: "30%",
[theme.breakpoints.down("xs")]: {
width: "50%",
},
backgroundColor: theme.palette.background.paper,
boxShadow: theme.shadows[5],
padding: theme.spacing(2, 4, 3),
opacity: 1,
visibility: "visible",
});
export const buttonStyle = (theme, isDark) => ({
background: isDark ? "white" : " #191919",
color: isDark ? "black" : "white",
height: "100%",
width: "max-content",
borderRadius: "5px",
border: "none",
outline: "none",
padding: "0.2rem 0.5rem",
cursor: "pointer",
transition: "all 0.2s ease",
"&:hover": {
transform: "scale(1.1)",
},
"&:active": {
boxShadow: "none",
top: "calc(6vh + 1px)",
right: "calc(11vw - 1px)",
},
[theme.breakpoints.down("xs")]: {
transform: "scale(0.85)",
marginRight: 0,
},
});
export const getModalStyle = () => {
return {
top: `50%`,
left: `50%`,
transform: `translate(-50%, -50%)`,
};
};
<file_sep>/src/Profile/styles/InstaStyle.js
import { makeStyles } from "@material-ui/core/styles";
export const useStyles = makeStyles((theme) => ({
container: {
position: "relative",
width: "80vw",
height: "80vh",
background: (isDark) => (isDark ? "#393939" : "#FAFAFA"),
boxShadow: "10px 10px 20px rgba(0, 0, 0, 0.7)",
borderRadius: "5px",
overflowY: "scroll",
overflowX: "hidden",
"&::-webkit-scrollbar": {
width: "10px",
[theme.breakpoints.down("xs")]: {
width: 0,
},
},
"&::-webkit-scrollbar-thumb": {
background: (isDark) =>
isDark
? "linear-gradient(0deg, #ee0979 0%,#ff6a00 100% )"
: "linear-gradient(180deg, #36d1dc 0%,#5b86e5 100% )",
height: "33%",
margin: "5px",
borderRadius: "0px 5px 5px 0px",
[theme.breakpoints.down("xs")]: {
borderRadius: 0,
},
},
"&::-webkit-scrollbar-track": {
borderLeft: (isDark) => `1px solid
${isDark ? "#2a2a2a" : "#d6d6d7"}`,
borderRadius: "0px 5px 5px 0px",
[theme.breakpoints.down("xs")]: {
borderRadius: 0,
},
},
[theme.breakpoints.down("md")]: {
width: "80vw",
},
[theme.breakpoints.down("xs")]: {
width: "90vw",
height: "90vh",
borderRadius: 0,
},
},
divider: {
margin: "2%",
background: (isDark) => isDark && "#888888",
},
toggle: {
position: "absolute",
top: "5vh",
[theme.breakpoints.down("xs")]: {
top: "0",
transform: "scale(0.8)",
left: "4vw",
},
},
}));
<file_sep>/src/Profile/Photo.js
import React, { useState, useEffect, useRef } from "react";
import { useStyles } from "./styles/PhotoStyle";
import { useColor } from "color-thief-react";
import { db } from "../config/firebase.config";
import Carousel from "./Carousel";
import { useAuthContext } from "./contexts/Auth.context";
import {
FilterNone as FilterNoneIcon,
HighlightOff as HighlightOffIcon,
} from "@material-ui/icons";
const Photo = (props) => {
const [{ user, isDark }] = useAuthContext();
const classes = useStyles(isDark);
const [open, setOpen] = useState(false);
const iconColor = useRef("");
const { data } = useColor(props.coverImage, "rgbArray", {
crossOrigin: "anonymous",
});
const setColorContrast = (color) => {
if (color) {
const brightness = Math.round(
(parseInt(color[0]) * 299 +
parseInt(color[1]) * 587 +
parseInt(color[2]) * 114) /
1000
);
return brightness > 125 ? "black" : "white";
}
return;
};
useEffect(() => {
iconColor.current.style.color = setColorContrast(data);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleClick = () => {
setOpen(true);
};
const handleClose = (e) => {
if (e.target !== e.currentTarget) return;
setOpen(false);
};
const handleDelete = (e) => {
e.stopPropagation();
// eslint-disable-next-line no-restricted-globals
const del = confirm("Are you sure to delete the post?");
if (del) {
db.collection(user.displayName)
.doc(user.uid)
.collection("posts")
.doc(props.id)
.delete()
.then(() => {
console.log("Successfully deleted");
})
.catch((error) => error.message);
}
return;
};
return (
<>
<div
onContextMenu={(e) => e.preventDefault()}
onClick={handleClick}
className={classes.root}
style={{
backgroundImage: `url(${props.coverImage})`,
}}
>
<i
ref={iconColor}
className={classes.filterNoneIcon}
style={{
display: `${props.images.length === 1 && "none"}`,
color: iconColor,
}}
>
<FilterNoneIcon />
</i>
<div className={classes.mask}>
<HighlightOffIcon
className={classes.highlightOffIcon}
onClick={handleDelete}
/>
</div>
</div>
<div
onClick={handleClose}
className={
open ? `${classes.lightBox} ${classes.active}` : `${classes.lightBox}`
}
>
<div className={classes.lightBoxContainer}>
<Carousel imgList={props.images} />
<h3 className={classes.lightBoxTitle}>{props.title}</h3>
<p className={classes.lightBoxDesc}>{props.desc}</p>
</div>
</div>
</>
);
};
export default Photo;
<file_sep>/src/Profile/PageBackground.js
import React from "react";
import { useAuthContext } from "./contexts/Auth.context";
export default function PageBackground(props) {
const [{ isDark }] = useAuthContext();
const dark = "linear-gradient(to right bottom,#ff6a00 0%, #ee0979 100%)";
const light = "linear-gradient(to right bottom, #89f7fe 0%, #66a6ff 100%)";
return (
<div
style={{
position: "absolute",
top: 0,
bottom: 0,
left: 0,
right: 0,
background: isDark ? dark : light,
display: "flex",
justifyContent: "center",
alignItems: "center",
overflowY: "hidden",
}}
></div>
);
}
<file_sep>/src/Profile/Insta.js
/* eslint-disable react-hooks/exhaustive-deps */
import React from "react";
import Navbar from "./Navbar";
import Info from "./Info";
import PhotoList from "./PhotoList";
import { Divider, Switch } from "@material-ui/core";
import { useStyles } from "./styles/InstaStyle";
import { useAuthContext } from "./contexts/Auth.context";
import { db } from "../config/firebase.config";
// import { AuthContext } from "./contexts/Auth.context";
function Insta() {
const [{ user, isDark }, dispatch] = useAuthContext();
const classes = useStyles(isDark);
return (
<>
<Switch
checked={!!isDark}
onChange={() => {
dispatch({ type: "SET_THEME", isDark: !isDark });
if (user) {
db.collection(user?.displayName)
.doc(user.uid)
.update({ isDark: !isDark });
}
}}
color="default"
inputProps={{ "aria-label": "default checkbox" }}
className={classes.toggle}
/>
<div className={classes.container}>
<Navbar />
<Info />
<Divider className={classes.divider} />
<PhotoList Num={18} />
</div>
</>
);
}
export default Insta;
<file_sep>/src/Profile/styles/InfoStyle.js
import { makeStyles } from "@material-ui/core/styles";
import { paperStyle } from "./reuseableStyle";
export const useStyles = makeStyles((theme) => ({
container: {
marginTop: "1%",
display: "flex",
justifyContent: "space-around",
alignItems: "center",
[theme.breakpoints.down("xs")]: {
display: "flex",
flexDirection: "column",
justifyContent: "center",
marginTop: "7%",
},
},
avatarContainer: {
position: "relative",
width: "120px",
height: "120px",
marginLeft: "7%",
},
offCircle: {
position: "absolute",
width: "100%",
height: "100%",
background: "linear-gradient(90deg, #ee0979 0%,#ff6a00 100% )",
borderRadius: "50%",
display: "flex",
justifyContent: "center",
alignItems: "center",
animation: "$rotate 2s linear infinite",
[theme.breakpoints.down("xs")]: {
margin: "0",
},
},
innerCircle: {
position: "absolute",
top: "3.5%",
left: "3.5%",
width: "93%",
height: "93%",
borderRadius: "50%",
backgroundColor: (isDark) => (isDark ? "#474747" : "#FAFAFA"),
display: "flex",
justifyContent: "center",
alignItems: "center",
},
avatarRoot: {
border: (isDark) => `1px solid ${isDark ? "#d3d3d3" : "#71716f"}`,
},
info: {
wordBreak: "break-word",
whiteSpace: "pre-wrap",
display: "flex",
flexDirection: "column",
justifyContent: "space-around",
position: "relative",
width: "50%",
marginLeft: "-10%",
color: (isDark) => isDark && "white",
[theme.breakpoints.down("xs")]: {
margin: "0",
width: "85%",
},
},
"@keyframes rotate": {
"0%": {
transform: "rotate(0deg)",
},
"25%": {
transform: "rotate(90deg)",
},
"50%": {
transform: "rotate(180deg)",
},
"75%": {
transform: "rotate(270deg)",
},
"100%": {
transform: "rotate(360deg)",
},
},
profileIcon: {
borderRadius: "20%",
margin: "0.2rem",
border: (isDark) => `1px solid ${isDark ? "white" : "black"}`,
color: (isDark) => isDark && "white",
},
editIcon: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
},
nameInputRoot: {
width: "80% !important",
fontSize: "1.5rem !important",
color: (isDark) => `${isDark ? "lightgray" : "gray"} !important`,
},
infoInputRoot: {
fontSize: "1rem !important",
color: (isDark) => `${isDark ? "lightgray" : "gray"} !important`,
},
inputMultiline: {
padding: "10px 0 2px !important",
color: (isDark) => `${isDark ? "lightgray" : "gray"} !important`,
},
fileInput: {
paddingBottom: "18.5px !important",
},
inputUnderline: {
borderBottom: "thin solid #e7e7e7 !important",
},
paper: paperStyle(theme),
}));
<file_sep>/src/Profile/styles/NavbarStyle.js
import { makeStyles } from "@material-ui/core/styles";
export const useStyles = makeStyles((theme) => ({
container: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
// backgroundColor: (isDark) => isDark && "#2a2a2a",
position: "sticky",
top: 0,
left: 0,
width: "calc(100%-5px)",
height: "6%",
borderRadius: 0,
padding: "10px 20px",
zIndex: 20,
[theme.breakpoints.down("xs")]: {
padding: "10px",
},
},
icon: {
fontSize: "1.5rem",
cursor: "pointer",
color: (isDark) => (isDark ? "white" : "black"),
},
Brand: {
height: "100%",
display: "flex",
alignItems: "center",
width: "33%",
color: (isDark) => (isDark ? "white" : "black"),
"& $divider": {
width: 0,
height: "80%",
margin: "0.5rem",
// border: (isDark) => `0.5px solid ${isDark ? "#fff" : "#565656"}`,
},
},
divider: {},
logo: {
height: "2rem",
},
title: {
fontFamily: "Grand Hotel",
fontSize: "1.5rem",
fontWeight: (isDark) => isDark && 400,
color: (isDark) => isDark && "white",
},
iconContainer: {
display: "flex",
justifyContent: "flex-end",
alignItems: "center",
width: "33%",
"& a": {
marginRight: "10px",
[theme.breakpoints.down("xs")]: {
marginRight: "7px",
},
},
},
}));
<file_sep>/src/Profile/styles/PhotoStyle.js
import { makeStyles } from "@material-ui/core/styles";
export const useStyles = makeStyles((theme) => ({
root: {
position: "relative",
width: "29%",
margin: "0.3rem",
borderRadius: "7px",
transition: "transform 0.3s",
backgroundSize: "cover",
backgroundRepeat: "no-repeat",
backgroundPosition: "50% 50%",
"&:after": {
content: '""',
display: "block",
paddingBottom: "100%",
},
"&:hover": {
transform: "scale(0.95)",
},
[theme.breakpoints.down("xs")]: {
width: "44%",
},
},
filterNoneIcon: {
position: "absolute",
right: 0,
margin: "0.5rem",
opacity: 0.5,
},
mask: {
position: "absolute",
width: "100%",
height: "100%",
fontSize: "1rem",
backgroundColor: "black",
borderRadius: "7px",
opacity: 0,
transition: "opacity 0.3s",
"&:hover": {
opacity: 0.5,
},
"&:active": {
opacity: 0.5,
},
},
highlightOffIcon: {
color: "white",
margin: "0.5rem",
fontSize: "1.5rem",
position: "absolute",
left: 0,
top: 0,
transition: "all 0.3s",
"&:hover": {
transform: "scale(1.4)",
},
},
lightBox: {
display: "flex",
justifyContent: "center",
alignItems: "center",
position: "fixed",
top: 0,
left: 0,
width: "100%",
height: "100%",
backgroundColor: "rgba(0,0,0,0.5)",
opacity: 0,
zIndex: -1,
// opacity: 1,
// zIndex: 100,
transition: "opacity 0.3s",
"&$active": {
opacity: 1,
zIndex: 20,
},
},
active: {},
lightBoxContainer: {
display: "inline-block",
position: "relative",
width: "40%",
height: "85%",
backgroundColor: (isDark) => (isDark ? "#393939" : "white"),
borderRadius: "5px",
color: "black",
overflowY: "auto",
"&::-webkit-scrollbar": {
width: "10px",
},
"&::-webkit-scrollbar-thumb": {
background: (isDark) =>
isDark
? "linear-gradient(0deg, #ee0979 0%,#ff6a00 100% )"
: "linear-gradient(180deg, #36d1dc 0%,#5b86e5 100% )",
borderRadius: "0px 5px 5px 0px",
margin: "5px",
},
"&::-webkit-scrollbar-track": {
borderLeft: (isDark) => `1px solid ${isDark ? "#2a2a2a" : "#d6d6d7"}`,
borderRadius: "0px 5px 5px 0px",
},
[theme.breakpoints.down("md")]: {
width: "50%",
},
[theme.breakpoints.down("sm")]: {
width: "60%",
},
[theme.breakpoints.down("xs")]: {
width: "70%",
},
},
lightBoxImg: {
position: "relative",
top: 0,
width: "100%",
backgroundSize: "contain",
"&:after": {
content: '""',
display: "block",
paddingBottom: "100%",
},
},
lightBoxTitle: {
margin: "1rem",
color: (isDark) => isDark && "white",
},
lightBoxDesc: {
margin: "1rem",
color: (isDark) => isDark && "white",
},
}));
<file_sep>/src/Profile/styles/ImageUploadStyle.js
import { makeStyles } from "@material-ui/core/styles";
import { paperStyle, buttonStyle } from "./reuseableStyle";
export const useStyles = makeStyles((theme) => ({
paper: paperStyle(theme),
button: {
...buttonStyle(theme),
marginRight: "0.5rem",
},
fileInput: {
paddingBottom: "18.5px",
},
progressBar: {
height: "0.4rem",
borderRadius: "0.4rem",
},
colorPrimary: {
backgroundColor: "#e0e0e0",
},
barColorPrimary: {
backgroundColor: theme.palette.primary,
},
bar1Determinate: {
borderRadius: "0.4rem",
},
}));
<file_sep>/src/Profile/Navbar.js
import React from "react";
import Logo from "../Image/logo.js";
import { useStyles } from "./styles/NavbarStyle";
import SignModal from "./SignModal";
import { Paper } from "@material-ui/core";
import {
GitHub as GitHubIcon,
Email as EmailIcon,
Facebook as FacebookIcon,
} from "@material-ui/icons";
import { useAuthContext } from "./contexts/Auth.context";
// import classes from "./Nav.module.css";
function Navbar() {
const [{ isDark }] = useAuthContext();
const classes = useStyles(isDark);
return (
<Paper
square={true}
style={{ background: isDark && "#2a2a2a" }}
className={classes.container}
>
<div className={classes.Brand}>
<Logo height="2rem" color={isDark ? "white" : "black"} />
<div
style={{
borderLeft: `1px solid ${isDark ? "white" : "#565656"}`,
}}
className={classes.divider}
/>
<h3 className={classes.title}>Cheng</h3>
</div>
<div className={classes.iconContainer}>
<div
style={{
display: "flex",
alignItems: "center",
position: "relative",
top: "2px",
}}
>
<a
href="https://www.facebook.com/"
target="_blank"
rel="noopener noreferrer"
>
<FacebookIcon
className={classes.icon}
style={{ fontSize: "1.75rem" }}
/>
</a>
<a
href="https://github.com/chenghsj"
className={classes.icon}
target="_blank"
rel="noopener noreferrer"
>
<GitHubIcon
className={classes.icon}
style={{ fontSize: "1.45rem" }}
/>
</a>
<a href="mailto:<EMAIL>">
<EmailIcon
className={classes.icon}
style={{ fontSize: "1.65rem" }}
/>
</a>
</div>
<SignModal />
</div>
</Paper>
);
}
export default Navbar;
| 70ce250cabeb103ceeeaeb86553f976df1b96acf | [
"JavaScript",
"Markdown"
]
| 15 | JavaScript | chenghsj/Web_Insta_Profile_clone | 526455a4bc1d0686fe94b9a47e7102ba93d36a93 | a9e99277e8fac17f988c78dc033ff7b4b7bdea14 |
refs/heads/master | <file_sep>package com.juttec.goldmetal.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
/**
* Created by Administrator on 2015/9/24.
*
* 关于图片的工具类
*/
public class ImgUtil {
// 根据路径获取图片 并进行缩放
public static Bitmap getBitmap(String path, int reqWidth, int reqHeight) {
// 先解析图片边框的大小
BitmapFactory.Options ops = new BitmapFactory.Options();
ops.inJustDecodeBounds = true;
Bitmap bm = BitmapFactory.decodeFile(path, ops);
ops.inSampleSize = 1;
int height = ops.outHeight;
int width = ops.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// 计算出实际宽高和目标宽高的比率
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
// 一定都会大于等于目标的宽和高。
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
ops.inSampleSize = inSampleSize;
ops.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, ops);
return bm;
}
}<file_sep>package com.juttec.goldmetal.utils;
import android.content.Context;
import android.widget.Toast;
/**
* Created by Administrator on 2015/9/21.
*/
public class ToastUtil {
public static boolean isShow = true;
public static void showShort(Context context,String msg){
if(isShow)
Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
}
public static void showLong(Context context,String msg){
if(isShow)
Toast.makeText(context,msg,Toast.LENGTH_LONG).show();
}
}
| 85b33351adb22d6016a3d1732efebeb6c117d4f7 | [
"Java"
]
| 2 | Java | treejames/GoldMetal | 257d8caeafcb03a8a1962a76f2fd8e0a6277e10a | 1158b3577c5bb357b8d9b7315ac31ab17ff6cdc1 |
refs/heads/master | <file_sep># Tool for creating 10m buffers around collection points
# Developed by <NAME>
import arcpy
import ramm
arcpy.env.overwriteOutput = True
try:
# Get inputs
points_table = arcpy.GetParameterAsText(0)
x_field = arcpy.GetParameterAsText(1)
y_field = arcpy.GetParameterAsText(2)
buffer_dist = arcpy.GetParameterAsText(3)
boundary = arcpy.GetParameterAsText(4)
output_location = arcpy.GetParameterAsText(5)
filename = arcpy.GetParameterAsText(6)
# Set the workspace
arcpy.env.workspace = output_location
logger = ramm.defineLogger(output_location)
def log(message):
ramm.showPyMessage(message, logger)
# convert table to points layer
log("\t - Beginning Process.")
arcpy.MakeXYEventLayer_management(
points_table, x_field, y_field, "lyr_col_points")
arcpy.CopyFeatures_management("lyr_col_points", "points.shp")
arcpy.MakeFeatureLayer_management("points.shp", "lyr_points")
#arcpy.XYTableToPoint_management(points_table, "col_points.shp", x_field, y_field)
# Use the boundary dataset to clip the relevant features
log("\t --- Clipping Features.")
arcpy.MakeFeatureLayer_management(boundary, "lyr_boundary")
arcpy.Clip_analysis("lyr_points", "lyr_boundary", "col_points_clipped.shp")
# Repair the geometry
log("\t --- Repairing Geometry.")
arcpy.MakeFeatureLayer_management(
"col_points_clipped.shp", "lyr_col_points_clipped")
arcpy.CheckGeometry_management(
"lyr_col_points_clipped", "geomErrorReport.dbf")
no_of_errors = int(arcpy.GetCount_management(
"geomErrorReport.dbf").getOutput(0))
arcpy.RepairGeometry_management("lyr_col_points_clipped")
log(
"\t ----- {} geometry errors were found and repaired. Check geomErrorReport.dbf for details.".format(no_of_errors))
# Create Buffers
log("\t --- Creating Buffers")
buffer_dist_wunits = buffer_dist + " Meters"
arcpy.Buffer_analysis("lyr_col_points_clipped", "col_points_buffered.shp",
buffer_dist_wunits, "FULL", "ROUND", "ALL")
log("\t --- Deagreggating Buffers")
arcpy.MultipartToSinglepart_management(
"col_points_buffered.shp", "col_points_buffered_split.shp")
no_of_buffers = int(arcpy.GetCount_management(
"col_points_buffered_split.shp").getOutput(0))
arcpy.Rename_management("col_points_buffered_split.shp",
"{}.shp".format(filename))
arcpy.Delete_management("col_points_buffered.shp")
log(
"\t - Process Complete. {} buffers were created.".format(no_of_buffers))
except Exception as e:
ramm.handleExcept(logger)
<file_sep>import arcpy
import ramm
input_data = arcpy.GetParameterAsText(0)
output_location = arcpy.GetParameterAsText(1)
# Prepare environment
arcpy.env.overwriteOutput = True
arcpy.env.workspace = output_location
# initialize logger
logger = ramm.defineLogger(output_location)
# Simplify message generator
def log(message, messageType="Message"):
ramm.showPyMessage(message, logger, messageType)
log("\t Starting Process")
log("\t Preparing Intemediates")
arcpy.CreateFileGDB_management(
output_location, "Extract_Overlapping_Polygons_Results.gdb")
arcpy.MakeFeatureLayer_management(input_data, "input_data")
arcpy.FeatureClassToGeodatabase_conversion(
["input_data"], "Extract_Overlapping_Polygons_Results.gdb")
arcpy.MakeFeatureLayer_management(
"Extract_Overlapping_Polygons_Results.gdb/input_data", "lyr_input_data")
arcpy.CreateFeatureclass_management("Extract_Overlapping_Polygons_Results.gdb", "Remaining_Polygons", "POLYGON", "lyr_input_data",
"DISABLED", "DISABLED", arcpy.Describe("lyr_input_data").spatialReference)
arcpy.MakeFeatureLayer_management(
"Extract_Overlapping_Polygons_Results.gdb/Overlapping_Polygons", "lyr_Remaining_Polygons")
arcpy.CreateFeatureclass_management("Extract_Overlapping_Polygons_Results.gdb", "row", "POLYGON", "lyr_input_data",
"DISABLED", "DISABLED", arcpy.Describe("lyr_input_data").spatialReference)
arcpy.MakeFeatureLayer_management(
"Extract_Overlapping_Polygons_Results.gdb/row", "lyr_row")
arcpy.CreateFeatureclass_management("Extract_Overlapping_Polygons_Results.gdb", "parent", "POLYGON", "lyr_input_data",
"DISABLED", "DISABLED", arcpy.Describe("lyr_input_data").spatialReference)
arcpy.MakeFeatureLayer_management(
"Extract_Overlapping_Polygons_Results.gdb/parent", "lyr_parent")
arcpy.CreateFeatureclass_management("Extract_Overlapping_Polygons_Results.gdb", "children", "POLYGON", "lyr_input_data",
"DISABLED", "DISABLED", arcpy.Describe("lyr_input_data").spatialReference)
arcpy.MakeFeatureLayer_management(
"Extract_Overlapping_Polygons_Results.gdb/children", "lyr_children")
arcpy.AddSpatialIndex_management("lyr_input_data")
log("\t Cleaning overlapping polygons")
with arcpy.da.SearchCursor("lyr_input_data", ["OBJECTID", "FEAT_SEQ", "SL_LAND_PR", "Total_BillCount", "LU_LGL_STS"]) as search_cursor:
for row in search_cursor:
log("\t {}".format(row[0]))
# Get the OBJECTID of row and use it to select row
arcpy.SelectLayerByAttribute_management("lyr_input_data", "NEW_SELECTION",
"\"OBJECTID\" = " + str(row[0]))
# Copy row into a new feature class called row
arcpy.Append_management(
"lyr_input_data", "lyr_parent", "NO_TEST")
# Remove row from the input
arcpy.DeleteFeatures_management("lyr_input_data")
# Select all features that intersect with row and copy them into the row feature class
arcpy.SelectLayerByLocation_management(
"lyr_input_data", "COMPLETELY_WITHIN", "lyr_row", selection_type="NEW_SELECTION")
arcpy.Append_management(
"lyr_input_data", "lyr_children", "NO_TEST")
# If there is more than one feature in the row feature class
# meaning there was something else in addition to row then delete those overlaps
# from the input and append everything in row into the output feature class
if (int(arcpy.GetCount_management("lyr_children").getOutput(0)) > 0):
arcpy.DeleteFeatures_management("lyr_input_data")
# Check if the billings in the children are all the same
arcpy.FindIdentical_management("lyr_children", "results.gdb/Identical_billings_Report",
["Total_BillCount"], "", "0", "ONLY_DUPLICATES")
if (int(arcpy.GetCount_management("lyr_children").getOutput(0)) != int(arcpy.GetCount_management("results.gdb/Identical_billings_Report").getOutput(0))):
arcpy.Append_management(
"lyr_row", "lyr_Remaining_Polygons", "NO_TEST")
else:
arcpy.Append_management(
"lyr_parent", "lyr_Remaining_Polygons", "NO_TEST")
arcpy.TruncateTable_management("lyr_parent")
arcpy.TruncateTable_management("lyr_children")
del search_cursor
# Count the number of features in the overlapping polygons feature class and report
overlapping_polygons_num = int(arcpy.GetCount_management(
"lyr_Remaining_Polygons").getOutput(0))
if (overlapping_polygons_num > 0):
log("\t Found {} features that overlap with other features.".format(
overlapping_polygons_num))
else:
arcpy.Delete_management(
"Extract_Overlapping_Polygons_Results.gdb/Remaining_Polygons")
log("\t No overlapping features were found")
arcpy.Delete_management(
"Extract_Overlapping_Polygons_Results.gdb/input_data")
arcpy.Delete_management(
"Extract_Overlapping_Polygons_Results.gdb/row")
log("\t Process Complete")
<file_sep># Arcpy Tools
GIS processing scripts written using the arcpy python library.
<file_sep>import arcpy
import time
import logging
import traceback
import os
import sys
rec = 0
def defineLogger(log_location=""):
logger = logging.getLogger(__name__)
x = list(logger.handlers)
for i in x:
logger.removeHandler(i)
i.flush()
i.close()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s : %(message)s')
file_handler = logging.FileHandler(log_location + '/log.log')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.debug(
"\n \n ********************** {} ************************\n \n".format(str(time.ctime())))
return logger
def populateCPID(id_start):
pinterval = 1
pStart = int(id_start)
global rec
if rec == 0:
rec = id_start
else:
rec += pinterval
ans = str(rec)
finans = ans.rjust(8, '0')
return 'CP' + finans
def populateRecNo(recno_prefix, startNumber):
pinterval = 1
pStart = int(startNumber)
global rec
if rec == 0:
rec = pStart
else:
rec += pinterval
ans = str(rec)
finans = ans.rjust(11, '0')
return recno_prefix + finans
def populateEkhayaID(cent_x, cent_y, recno):
lat = int(cent_x * 1100000)
lon = int(cent_y * 1100000)
rec_string = recno[:4]
finlat = hex(lat)[2:].rjust(8, '0')
finlon = hex(lon)[2:].rjust(8, '0')
return rec_string.upper() + finlat.upper() + finlon.upper()
def populateNewEkhayaID(cent_x, cent_y, recno):
lat = int(cent_x * 1100000)
lon = int(cent_y * 1100000)
rec_string1 = recno[:9]
rec_string2 = int(recno[-11:])
finlat = hex(lat)[2:].rjust(8, '0')
finlon = hex(lon)[2:].rjust(8, '0')
finrec_string2 = hex(rec_string2)[2:].rjust(10, '0')
return rec_string1.upper() + finrec_string2.upper() + finlat.upper() + finlon.upper()
def populateUsingSpatialJoin(input_dataset, spatialjoin_dataset, update_field, source_field, spatialjoin_type):
arcpy.MakeFeatureLayer_management(
spatialjoin_dataset, "lyr_spatialjoin_dataset")
search_cursor = arcpy.SearchCursor("lyr_spatialjoin_dataset")
for row in search_cursor:
arcpy.SelectLayerByAttribute_management("lyr_spatialjoin_dataset", "NEW_SELECTION",
"\"FID\" = " + str(row.getValue("FID")))
arcpy.SelectLayerByLocation_management(input_dataset, spatialjoin_type, "lyr_spatialjoin_dataset", "",
"NEW_SELECTION")
arcpy.CalculateField_management(input_dataset, update_field,
"'{0}'".format(str(row.getValue(source_field))), "PYTHON_9.3", "")
del search_cursor
def populateUsingSpatialJoinFC(input_dataset, spatialjoin_dataset, update_field, source_field, spatialjoin_type):
arcpy.MakeFeatureLayer_management(
spatialjoin_dataset, "lyr_spatialjoin_dataset")
search_cursor = arcpy.SearchCursor("lyr_spatialjoin_dataset")
for row in search_cursor:
arcpy.SelectLayerByAttribute_management("lyr_spatialjoin_dataset", "NEW_SELECTION",
"\"OBJECTID\" = " + str(row.getValue("OBJECTID")))
arcpy.SelectLayerByLocation_management(input_dataset, spatialjoin_type, "lyr_spatialjoin_dataset", "",
"NEW_SELECTION")
arcpy.CalculateField_management(input_dataset, update_field,
"'{0}'".format(str(row.getValue(source_field))), "PYTHON_9.3", "")
del search_cursor
def mapFields(input_dataset, output_dataset, field_map_table):
# list the fields which contain the field map info.
fields = ["SourceFieldname", "DestinationFieldName"]
# define function to get unique field values from a table
def GetUniqueFieldValues(table, field):
"""
Retrieves and prints a list of unique values in a user-specified field
Args:
table (str): path or name of a feature class, layer, table, or table view
field (str): name of the field for which the user wants unique values
Returns:
uniqueValues (list): a list of the unique values in the field
"""
# get the values
with arcpy.da.SearchCursor(table, [field]) as cursor:
return sorted({row[0] for row in cursor})
# get a list of unique output fields
output_fields = GetUniqueFieldValues(
field_map_table, "DestinationFieldName")
# create an empty field mappings object
fm = arcpy.FieldMappings()
# build the field mappings object
for f in output_fields:
# create a field map object
fMap = arcpy.FieldMap()
with arcpy.da.SearchCursor(field_map_table, fields,
"""{0} = '{1}'""".format("DestinationFieldName", f)) as cursor:
for row in cursor:
# add the input field to the field map
fMap.addInputField(input_dataset, row[0])
# set the output name
output_field_name = fMap.outputField
output_field_name.name = f
fMap.outputField = output_field_name
# add the field map to the field mappings object
fm.addFieldMap(fMap)
# perform the append
arcpy.Append_management(input_dataset, output_dataset, "NO_TEST", fm)
def decodeCitySG26Code(citySG26Code_field):
townshipCode_field = citySG26Code_field[:4]
extentCode_field = citySG26Code_field[4:8]
erfNumber_field = citySG26Code_field[8:16].lstrip('0')
portionNumber_field = citySG26Code_field[16:21]
remainder_field = citySG26Code_field[24:]
return [townshipCode_field, extentCode_field, erfNumber_field, portionNumber_field, remainder_field]
def prepareOutput(gdbFeatureClass, outputLocation, shapefileName):
arcpy.FeatureClassToShapefile_conversion(gdbFeatureClass, outputLocation)
arcpy.DeleteField_management(gdbFeatureClass, "SHAPE_Leng")
arcpy.DeleteField_management(gdbFeatureClass, "Shape_Area")
arcpy.DeleteField_management(gdbFeatureClass, "OBJECTID")
arcpy.Rename_management(gdbFeatureClass + ".shp",
shapefileName + "_{}.shp".format(time.strftime("%Y%m%d")))
def showPyMessage(message, logger, messageType="Message"):
if (messageType == "Message"):
arcpy.AddMessage(str(time.ctime()) + " - " + message)
logger.debug(message)
if (messageType == "Warning"):
arcpy.AddWarning(str(time.ctime()) + " - " + message)
logger.warning(message)
if (messageType == "Error"):
arcpy.AddError(str(time.ctime()) + " - " + message)
logger.error(message)
def handleExcept(logger):
message = "\n*** PYTHON ERRORS *** "
showPyMessage(message, logger, "Error")
message = "Python Traceback Info: " + \
traceback.format_tb(sys.exc_info()[2])[0]
showPyMessage(message, logger, "Error")
message = "Python Error Info: " + \
str(sys.exc_type) + ": " + str(sys.exc_value) + "\n"
showPyMessage(message, logger, "Error")
<file_sep>"""-----------------------------------------------------------------------------
Script Name: Generate CP IDs
Version: 1.1
Description: This tool will create a field called CPID and populate it
with the CPIDs in the format CPXXXXXXXXX whete XXXXXXXXX is
a 9 digit number starting from the start number given as input.
Created By: <NAME>
Date: 2018-06-29
Last Revision: 2018-10-31
-----------------------------------------------------------------------------"""
import arcpy
import ramm
arcpy.env.overwriteOutput = True
try:
input_data = arcpy.GetParameterAsText(0)
startNumber = arcpy.GetParameterAsText(1)
output_location = arcpy.GetParameterAsText(3)
rec = 0
# initialize logger
logger = ramm.defineLogger(output_location)
# simplify messege generator
def log(message):
ramm.showPyMessage(message, logger)
log("- Starting Process")
arcpy.MakeFeatureLayer_management(input_data, "lyr_input_data")
arcpy.AddField_management("lyr_input_data", "CPID", "TEXT")
with arcpy.da.UpdateCursor("lyr_input_data", 'CPID') as update_cursor:
for x in update_cursor:
# generate CPID
x[0] = ramm.populateCPID(startNumber)
update_cursor.updateRow(x)
del update_cursor
log("- Process Complete")
except:
ramm.handleExcept(logger)
<file_sep>import arcpy
import logging
arcpy.env.overwriteOutput = True
# Get inputs
col_points = arcpy.GetParameterAsText(0)
grid = arcpy.GetParameterAsText(1)
output_location = arcpy.GetParameterAsText(2)
logger = ramm.defineLogger(output_location)
def log(message):
ramm.showPyMessage(message, logger)
# Set the workspace
arcpy.env.workspace = output_location
# Make feature layers from the input datasets
log("\t --- Beginning Process")
arcpy.MakeFeatureLayer_management(col_points, "lyr_col_points")
arcpy.MakeFeatureLayer_management(grid, "lyr_grid")
search_cursor = arcpy.SearchCursor("lyr_grid")
for row in search_cursor:
arcpy.SelectLayerByAttribute_management("lyr_grid", "NEW_SELECTION",
"\"FID\" = " + str(row.getValue("FID")))
arcpy.SelectLayerByLocation_management("lyr_col_points", "INTERSECT", "lyr_grid", "",
"NEW_SELECTION")
arcpy.CopyFeatures_management("lyr_col_points", "points_grid.shp")
arcpy.MakeFeatureLayer_management("points_grid.shp", "lyr_pointsGrid")
arcpy.Buffer_analysis("lyr_pointsGrid", "points_grid_buffered.shp",
"10 Meters", "FULL", "ROUND", "ALL")
arcpy.MultipartToSinglepart_management(
"points_grid_buffered.shp", "points_grid_buffered_Split.shp")
arcpy.AddField_management("points_grid_buffered_Split.shp", "SPID", "LONG")
arcpy.Rename_management("points_grid_buffered_Split.shp",
"PointsFromGrid_FID{}.shp".format(str(row.getValue("FID"))))
log(
"\t --- Completed Grid FID = {}".format(str(row.getValue("FID"))))
del search_cursor
log("\t --- Process Complete")
<file_sep># """-----------------------------------------------------------------------------
# Script Name: Generate Ekhaya ID
# Description: Generates a unique ID called the EkhayaID based on the
# CENT_X, CENT_Y and whole RECNO field
# Created By: <NAME>
# Date: 2018-06-21
# Last Revision: 2018-10-19
# -----------------------------------------------------------------------------"""
import arcpy
import ramm
try:
input_data = arcpy.GetParameterAsText(0)
log_output = arcpy.GetParameterAsText(1)
logger = ramm.defineLogger(log_output)
def log(message):
ramm.showPyMessage(message, logger)
log("\t Starting Process")
fields = ['CENT_X', 'CENT_Y', 'RECNO', 'EKHAYAID']
for data in input_data.split(';'):
log("Generating EkhayaIDs for {}".format(data))
with arcpy.da.UpdateCursor(data, fields) as update_cursor:
for x in update_cursor:
x[3] = ramm.populateEkhayaID(x[0], x[1], x[2])
update_cursor.updateRow(x)
del update_cursor
log("New EkhayaIDs Generated Successfully!")
except:
ramm.handleExcept(logger)
<file_sep>""" -----------------------------------------------------------------------------
Tool Name: Service Layer Cleanup
Version: 1.0
Description: Put description here
Author: <NAME>
Date: 2019-01-15
Last Revision: 2019-01-15
------------------------------------------------------------------------------ """
import arcpy
import time
import ramm
try:
# get inputs
existing_dataset = arcpy.GetParameterAsText(0)
update_dataset = arcpy.GetParameterAsText(1)
current_master_cad = arcpy.GetParameterAsText(2)
output_location = arcpy.GetParameterAsText(3)
roads_dataset = arcpy.GetParameterAsText(4)
cad_schema_template = arcpy.GetParameterAsText(5)
fieldMap = arcpy.GetParameterAsText(6)
spatial_lmun = arcpy.GetParameterAsText(7)
spatial_dmun = arcpy.GetParameterAsText(8)
spatial_prov = arcpy.GetParameterAsText(9)
city_name = arcpy.GetParameterAsText(10)
provcode = arcpy.GetParameterAsText(11)
country = arcpy.GetParameterAsText(12)
arcpy.env.overwriteOutput = True
rec = 0
# initialize logger
logger = ramm.defineLogger(output_location)
# simplify messege generator
def log(message):
ramm.showPyMessage(message, logger)
# set the workspace
log("\t Step 1 - Finding changes")
log("\t ...Setting the workspace and generating intemediary datasets")
arcpy.env.workspace = output_location
# create temporary geodatabase for temporary geoprocessing tasks
log("\t ...Creating the results geodatabase")
arcpy.CreateFileGDB_management(output_location, "results.gdb")
# make feature layer from the existing dataset
arcpy.MakeFeatureLayer_management(existing_dataset, "existing_dataset")
arcpy.MakeFeatureLayer_management(update_dataset, "update_dataset")
# add the datasets to the geodatabase
log("\t ...Adding the existing and update datasets into the geodatabase")
arcpy.FeatureClassToGeodatabase_conversion(["existing_dataset", "update_dataset"],
"results.gdb")
# make feature layer from the existing dataset
arcpy.MakeFeatureLayer_management(
"results.gdb/existing_dataset", "lyr_existing_gp")
arcpy.MakeFeatureLayer_management(
"results.gdb/update_dataset", "lyr_update_gp")
arcpy.AddSpatialIndex_management("lyr_update_gp")
arcpy.AddIndex_management(
"lyr_update_gp", "SL_LAND_PR", "UlkIndex", "UNIQUE")
arcpy.AddSpatialIndex_management("lyr_existing_gp")
arcpy.AddIndex_management(
"lyr_existing_gp", "SL_LAND_PR", "ElkIndex", "UNIQUE")
# create an empty feature class in the temporary geodatabase
arcpy.CreateFeatureclass_management("results.gdb", "changes_formated", "POLYGON", cad_schema_template,
"DISABLED", "DISABLED", arcpy.Describe(cad_schema_template).spatialReference)
# join existing_data's data into update_data's data using the LISKEY field
log("\t ...Joining the existing and update datasets based on the LIS Key")
arcpy.JoinField_management("lyr_update_gp", "SL_LAND_PR", "lyr_existing_gp",
"SL_LAND_PR", ["SL_LAND_PR"])
# select from the feature layer the features where the LISKEY is null
log("\t ...Selecting the records from the joined layer where the existing LIS Key is null")
arcpy.SelectLayerByAttribute_management(
"lyr_update_gp", "NEW_SELECTION", "\"SL_LAND_PR_1\" IS NULL")
# save selection to new feature class
log("\t ...Saving the selection to a new feature class called changes")
arcpy.CopyFeatures_management(
"lyr_update_gp", "results.gdb/changes_unformated")
# make layer from the changes_unformated feature class
arcpy.MakeFeatureLayer_management(
"results.gdb/changes_unformated", "lyr_changes_unformated")
arcpy.MakeFeatureLayer_management(
"results.gdb/changes_formated", "lyr_changes_formated")
arcpy.AddSpatialIndex_management("lyr_changes_unformated")
arcpy.AddSpatialIndex_management("lyr_changes_formated")
# count the number of records in changes_unformated
no_of_records = int(arcpy.GetCount_management(
"lyr_changes_unformated").getOutput(0))
# only continue if the number of records in changes is greater than 0
if no_of_records == 0:
arcpy.ClearWorkspaceCache_management()
arcpy.Delete_management("results.gdb")
log("\t Process completed. No changes were found")
else:
log("\t Step 1 completed successfully. {} changes found.".format(no_of_records))
log("\t Step 2 - Processing Changes.")
identicalLIS = False
identicalGeom = False
# check the geometry of the changes_unformated feature class
log("\t ...Checking and repairing the geometry")
arcpy.CheckGeometry_management(
"lyr_changes_unformated", "results.gdb/geomErrorReport")
# get the number of records in the geometry errors report and if there are no features then delete the report
no_of_geom_errors = int(arcpy.GetCount_management(
"results.gdb/geomErrorReport").getOutput(0))
if no_of_geom_errors == 0:
# delete the empty report
arcpy.Delete_management("results.gdb/geomErrorReport")
else:
# repair geometry errors on the changes_unformated feature class
arcpy.RepairGeometry_management("lyr_changes_unformated")
# find any records that have the same LISKEY, SG26CODE and geometry
log("\t ...Identifying and removing duplicates")
arcpy.FindIdentical_management("lyr_changes_unformated", "results.gdb/identicalGeomLISSG26Report",
["SHAPE", "SL_LAND_PR", "SG26_CODE"], "", "0", "ONLY_DUPLICATES")
# get the number of records in the identical features report and if there are no features then delete the report
no_of_identical_records_geomLISSG26 = int(arcpy.GetCount_management(
"results.gdb/identicalGeomLISSG26Report").getOutput(0))
if no_of_identical_records_geomLISSG26 == 0:
# delete empty report
arcpy.Delete_management("results.gdb/identicalGeomLISSG26Report")
else:
# delete the duplicates
arcpy.DeleteIdentical_management("lyr_changes_unformated", [
"SHAPE", "SL_LAND_PR", "SG26_CODE"], "", "0")
# find any records that have the same LISKEY and geometry
arcpy.FindIdentical_management("lyr_changes_unformated", "results.gdb/identicalGeomLISReport",
["SHAPE", "SL_LAND_PR"], "", "0", "ONLY_DUPLICATES")
# get the number of records in the identical features report and if there are no features then delete the report
no_of_identical_records_geomLIS = int(arcpy.GetCount_management(
"results.gdb/identicalGeomLISReport").getOutput(0))
if no_of_identical_records_geomLIS == 0:
# delete empty report
arcpy.Delete_management("results.gdb/identicalGeomLISReport")
else:
# delete the duplicates
arcpy.DeleteIdentical_management("lyr_changes_unformated", [
"SHAPE", "SL_LAND_PR"], "", "0")
# find any records that have the same LISKEY
arcpy.FindIdentical_management("lyr_changes_unformated", "results.gdb/identicalLISReport",
["SL_LAND_PR"], "", "0", "ONLY_DUPLICATES")
# get the number of records in the identical features report and if there are no features then delete the report
no_of_identical_records_LIS = int(arcpy.GetCount_management(
"results.gdb/identicalLISReport").getOutput(0))
if no_of_identical_records_LIS == 0:
# delete empty report
arcpy.Delete_management("results.gdb/identicalLISReport")
else:
identicalLIS = True
arcpy.FindIdentical_management("lyr_changes_unformated", "results.gdb/identicalGeomReport",
["SHAPE"], "", "0", "ONLY_DUPLICATES")
# get the number of records in the identical features report and if there are no features then delete the report
no_of_identical_records_geom = int(arcpy.GetCount_management(
"results.gdb/identicalGeomReport").getOutput(0))
if no_of_identical_records_geom == 0:
# delete empty report
arcpy.Delete_management("results.gdb/identicalGeomReport")
else:
identicalGeom = True
# build field mappings and append the data into lyr_changes_formated
log(
"\t ...Creating field mappings and formating table")
ramm.mapFields("lyr_changes_unformated",
"lyr_changes_formated", fieldMap)
arcpy.AddSpatialIndex_management("lyr_changes_formated")
# count the number of records in changes_formated
no_of_records_formated = int(arcpy.GetCount_management(
"lyr_changes_formated").getOutput(0))
# capitalise the Street Suffix data
arcpy.CalculateField_management(
"lyr_changes_formated", "STREETSUFF", "!STREETSUFF!.upper()", "PYTHON_9.3")
# polulate fields using spatial joins
log("\t ...Populating the Local Municipality, District "
"Municipality, Admin District Code and Province fields based on a spatial join.")
ramm.populateUsingSpatialJoin(
"lyr_changes_formated", spatial_lmun, "LOCALMUN", "FULLNAME", "INTERSECT")
ramm.populateUsingSpatialJoin(
"lyr_changes_formated", spatial_dmun, "DISTRICTMU", "FULLNAME", "INTERSECT")
ramm.populateUsingSpatialJoin(
"lyr_changes_formated", spatial_dmun, "ADMINDISCO", "DISTRICTCO", "INTERSECT")
ramm.populateUsingSpatialJoin(
"lyr_changes_formated", spatial_prov, "PROVINCE", "PROVNAME", "INTERSECT")
# generate calculated fields, ie Area, Perimeter, Cent_x and Cent_y
log(
"\t ...Calculating the Area, Perimeter, Centroid X and Centroid Y fields")
arcpy.CalculateField_management(
"lyr_changes_formated", 'AREA', "!SHAPE.AREA@SQUAREMETERS!", "PYTHON_9.3")
arcpy.CalculateField_management(
"lyr_changes_formated", 'PERIMETER', "!SHAPE.LENGTH@METERS!", "PYTHON_9.3")
arcpy.CalculateField_management(
"lyr_changes_formated", 'CENT_X', "!SHAPE.CENTROID.X!", "PYTHON_9.3")
arcpy.CalculateField_management(
"lyr_changes_formated", 'CENT_Y', "!SHAPE.CENTROID.Y!", "PYTHON_9.3")
# fields for the update cursor
log("\t ...Populating the DESC_, TOWNSHIPCO, COUNTRY, PROVINCECO, EXTENTCO, ERFNO, "
"PORTIONNO, REMAINDER and CITYNAME fields")
fields = ['DESC_', 'TOWNSHIPCO', 'EXTENTCO', 'ERFNO',
'PORTIONNO', 'REMAINDER', 'CITYSG26CO',
'STREETNO', 'STREETNAME', 'STREETSUFF',
'SUBURBNAME', 'CENT_X', 'CENT_Y',
'COUNTRY', 'PROVINCECO', 'CITYNAME']
# main code
with arcpy.da.UpdateCursor("lyr_changes_formated", fields) as update_cursor:
for x in update_cursor:
# description
x[0] = x[7] + ', ' + x[8] + ', ' + x[9] + ', ' + x[10]
# decoding the SG26 Code
[x[1], x[2], x[3], x[4], x[5]] = ramm.decodeCitySG26Code(x[6])
x[13] = country
x[14] = provcode
x[15] = city_name
update_cursor.updateRow(x)
del update_cursor
# select all the polygons that intersect with roads and save them into a new feature class called changes_rr
log(
"\t ...Selecting all the polygons that intersection with roads and saving them into a new feature class called changes_rr")
arcpy.MakeFeatureLayer_management(roads_dataset, "lyr_roads_dataset")
arcpy.AddSpatialIndex_management("lyr_roads_dataset")
arcpy.SelectLayerByLocation_management(
"lyr_changes_formated", "INTERSECT", "lyr_roads_dataset", selection_type="NEW_SELECTION")
arcpy.CopyFeatures_management(
"lyr_changes_formated", "results.gdb/changes_rr")
arcpy.AddSpatialIndex_management("results.gdb/changes_rr")
no_of_records_changes_rr = int(arcpy.GetCount_management(
"results.gdb/changes_rr").getOutput(0))
# save the remaining polygons into a new feature class called changes_xrr
arcpy.SelectLayerByLocation_management(
"lyr_changes_formated", "INTERSECT", "lyr_roads_dataset", "", "NEW_SELECTION", "INVERT")
arcpy.CopyFeatures_management(
"lyr_changes_formated", "results.gdb/changes_xrr")
# select from the feature layer the features where the Area < 3 and save this to a new feature class called changes_xrr_area3
log(
"\t ...Selecting the records from the joined layer where the Area < 3")
arcpy.MakeFeatureLayer_management(
"results.gdb/changes_xrr", "lyr_changes_xrr")
arcpy.AddSpatialIndex_management("lyr_changes_xrr")
arcpy.AddIndex_management("lyr_changes_xrr", "AREA", "aIndex")
arcpy.SelectLayerByAttribute_management(
"lyr_changes_xrr", "NEW_SELECTION", "\"AREA\" < 3")
log(
"\t ...Saving the selection to a new feature class called changes_xrr_area3")
arcpy.CopyFeatures_management(
"lyr_changes_xrr", "results.gdb/changes_xrr_area3")
arcpy.AddSpatialIndex_management("results.gdb/changes_xrr_area3")
no_of_records_changes_xrr_area3 = int(arcpy.GetCount_management(
"results.gdb/changes_xrr_area3").getOutput(0))
# save the remaining polygons into a new feature class called changes_xrr_xarea3
arcpy.SelectLayerByAttribute_management(
"lyr_changes_xrr", "SWITCH_SELECTION")
arcpy.CopyFeatures_management(
"lyr_changes_formated", "results.gdb/changes_xrr_xarea3")
arcpy.MakeFeatureLayer_management(
"results.gdb/changes_xrr_xarea3", "lyr_changes_xrr_xarea3")
arcpy.AddSpatialIndex_management("lyr_changes_xrr_xarea3")
# get polygons that intersect the current master and save them into a new feature class called changes_overlap
arcpy.MakeFeatureLayer_management(
current_master_cad, "lyr_current_master_cad")
arcpy.AddSpatialIndex_management("lyr_current_master_cad")
arcpy.SelectLayerByLocation_management(
"lyr_changes_xrr_xarea3", "INTERSECT", "lyr_current_master_cad", selection_type="NEW_SELECTION")
arcpy.CopyFeatures_management(
"lyr_changes_xrr_xarea3", "results.gdb/changes_overlap")
arcpy.MakeFeatureLayer_management(
"results.gdb/changes_overlap", "lyr_changes_overlap")
arcpy.AddSpatialIndex_management("lyr_changes_overlap")
no_of_records_changes_overlap = int(arcpy.GetCount_management(
"lyr_changes_overlap").getOutput(0))
arcpy.SelectLayerByAttribute_management(
"lyr_changes_xrr_xarea3", "SWITCH_SELECTION")
arcpy.CopyFeatures_management(
"lyr_changes_xrr_xarea3", "results.gdb/changes_xrr_xarea3_xoverlap")
arcpy.MakeFeatureLayer_management(
"results.gdb/changes_xrr_xarea3_xoverlap", "lyr_changes_xrr_xarea3_xoverlap")
arcpy.AddSpatialIndex_management("lyr_changes_xrr_xarea3_xoverlap")
no_of_records_changes_xrr_xarea3_xoverlap = int(arcpy.GetCount_management(
"lyr_changes_xrr_xarea3_xoverlap").getOutput(0))
log(
"\t Step 2 completed successfully.")
log("\t Step 3 - Preparing Outputs.")
# delete intermetiate files and prepare output files and give them meaningful names
log("\t ...Deleting intermediary files")
arcpy.Delete_management("results.gdb/changes_formated")
arcpy.Delete_management("results.gdb/changes_unformated")
arcpy.Delete_management("results.gdb/changes_xrr")
arcpy.Delete_management("results.gdb/changes_xrr_xarea3")
arcpy.Delete_management("results.gdb/existing_dataset")
arcpy.Delete_management("results.gdb/update_dataset")
log("\t Step 3 completed successfully.")
log("\t Process completed successfully! \n \n{} changes were found and are summarised as follows:".format(
no_of_records))
if no_of_records_changes_rr == 0:
arcpy.Delete_management("results.gdb/changes_rr")
else:
log("-- {} features intersect with roads and are therefore most likely road reserves, verify whether each of these is indeed a road reserve if so delete them.".format(no_of_records_changes_rr))
arcpy.Rename_management("results.gdb/changes_rr",
"Changes_roadreserves_{}".format(time.strftime("%Y%m%d", time.gmtime())))
if no_of_records_changes_xrr_area3 == 0:
arcpy.Delete_management("results.gdb/changes_xrr_area3")
else:
log("-- {} features were found to have areas less than 3 sqrmetres so they are most likely slivers or other errors, verify whether each of these are suppose to be part of the dataset, if not proceede to delete.".format(no_of_records_changes_xrr_area3))
arcpy.Rename_management("results.gdb/changes_xrr_area3",
"Changes_arealessthan3_{}".format(time.strftime("%Y%m%d", time.gmtime())))
if no_of_records_changes_overlap == 0:
arcpy.Delete_management("results.gdb/changes_overlap")
else:
log("-- {} features overlap with the Current Master Cadastre and need to be investigated.".format(
no_of_records_changes_overlap))
arcpy.Rename_management("results.gdb/changes_overlap",
"Changes_overlap_{}".format(time.strftime("%Y%m%d", time.gmtime())))
if no_of_records_changes_xrr_xarea3_xoverlap == 0:
arcpy.Delete_management("results.gdb/changes_xrr_xarea3_xoverlap")
else:
log("-- {} features are most likely legitimate changes, proceed with the rest of the checks on these before appending them to the master cadastre".format(
no_of_records_changes_xrr_xarea3_xoverlap))
arcpy.Rename_management("results.gdb/changes_xrr_xarea3_xoverlap",
"Changes_{}".format(time.strftime("%Y%m%d", time.gmtime())))
log("\n \n The following reports were generated: ")
if identicalLIS:
log("-- {} features were found with identical LIS Keys. Run the Find Identicals tool to regenerate this report for each of the output datasets and use the OBJECTID to create a relationship between the report and the dataset to locate the identicals and rectify them. ".format(no_of_identical_records_LIS))
if identicalGeom:
log("-- {} features were found with identical Geometry. Run the Find Identicals tool to regenerate this report for each of the output datasets and use the OBJECTID to create a relationship between the report and the dataset to locate the identicals and rectify them.".format(no_of_identical_records_geom))
arcpy.ClearWorkspaceCache_management()
except:
ramm.handleExcept(logger)
<file_sep>""" -----------------------------------------------------------------------------
Tool Name: Service Layer Cleanup
Version: 1.0
Description: Tool used to clean up the cadastre in order to create a service
layer.
Author: <NAME>
Date: 2019-01-15
Last Revision: 2019-01-28
------------------------------------------------------------------------------ """
import arcpy
import time
import ramm
try:
# Get inputs
existing_cadastre = arcpy.GetParameterAsText(0)
billing_data = arcpy.GetParameterAsText(1)
roads = arcpy.GetParameterAsText(2)
output_location = arcpy.GetParameterAsText(3)
# Prepare environment
arcpy.env.overwriteOutput = True
arcpy.env.workspace = output_location
arcpy.env.parallelProcessingFactor = "100%"
# initialize logger
logger = ramm.defineLogger(output_location)
# Simplify message generator
def log(message, messageType="Message"):
ramm.showPyMessage(message, logger, messageType)
log("\n \t \t \t Starting Process")
log("\n \n \t \t Step 1 - Preparing the inputs")
# Generating intemediary datasets
log("\t Creating the results geodatabase")
arcpy.CreateFileGDB_management(output_location, "results.gdb")
# Add inputs into the geodatabase
log("\t Adding inputs into the geodatabase")
arcpy.MakeFeatureLayer_management(existing_cadastre,
"existing_cadastre_mp")
arcpy.MakeFeatureLayer_management(roads,
"roads")
arcpy.FeatureClassToGeodatabase_conversion(
["existing_cadastre_mp", "roads"], "results.gdb")
arcpy.MultipartToSinglepart_management(
"results.gdb/existing_cadastre_mp", "results.gdb/existing_cadastre_sp")
arcpy.MakeFeatureLayer_management(
"results.gdb/existing_cadastre_sp", "lyr_existing_cadastre")
arcpy.MakeFeatureLayer_management("results.gdb/roads", "lyr_roads")
arcpy.AddSpatialIndex_management("lyr_existing_cadastre")
arcpy.AddSpatialIndex_management("lyr_roads")
arcpy.AddIndex_management("lyr_existing_cadastre",
"SL_LAND_PR", "UlKIndex", "UNIQUE")
# Count the number of records in the new dataset
no_existing_cadastre = int(arcpy.GetCount_management(
"lyr_existing_cadastre").getOutput(0))
log("\t Input cadastral dataset has {} records".format(
no_existing_cadastre), "Warning")
# Join the cadastre to the billing using the LISKEY field
log("\t Joining the cadastre and billing datasets")
arcpy.CopyRows_management(billing_data, "results.gdb/billing_data")
arcpy.JoinField_management(
"lyr_existing_cadastre", "SL_LAND_PR", "results.gdb/billing_data", "LISKEY", ["Total_BillCount"])
log("\n \n \t \t Step 2 - Repairing Geometry")
# Check and repair geometry errors if found
arcpy.CheckGeometry_management(
"lyr_existing_cadastre", "results.gdb/Geometry_Errors_Report")
geometry_errors_num = int(arcpy.GetCount_management(
"results.gdb/Geometry_Errors_Report").getOutput(0))
if geometry_errors_num == 0:
arcpy.Delete_management("results.gdb/Geometry_Errors_Report")
log("\t ---No geometry errors were found")
else:
arcpy.RepairGeometry_management("lyr_existing_cadastre")
log("\t ---{} geometry errors were found and repaired. See Geometry_Errors_Report for more information".format(
geometry_errors_num), "Warning")
log("\n \n \t \t Step 3 - Removing Road Reserves")
# remove all the polygons that intersect with roads and being billed
arcpy.SelectLayerByLocation_management(
"lyr_existing_cadastre", "INTERSECT", "lyr_roads", selection_type="NEW_SELECTION")
arcpy.CopyFeatures_management(
"lyr_existing_cadastre", "results.gdb/Road_Reserves_Intermediate")
arcpy.MakeFeatureLayer_management(
"results.gdb/Road_Reserves_Intermediate", "lyr_road_reserves")
arcpy.AddSpatialIndex_management("lyr_road_reserves")
arcpy.SelectLayerByAttribute_management(
"lyr_road_reserves", "NEW_SELECTION", "\"Total_BillCount\" IS NULL")
arcpy.DeleteFeatures_management("lyr_road_reserves")
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
arcpy.Append_management("lyr_road_reserves", "lyr_existing_cadastre")
arcpy.Delete_management("results.gdb/Road_Reserves_Intermediate")
log("\n \n \t \t Step 4 - Removing Sliver Polygons")
# remove from the feature layer the features where the Area < 15
arcpy.AddField_management("lyr_existing_cadastre", "AREA", "DOUBLE")
arcpy.CalculateField_management(
"lyr_existing_cadastre", 'AREA', "!SHAPE.AREA@SQUAREMETERS!", "PYTHON_9.3")
arcpy.AddIndex_management("lyr_existing_cadastre", "AREA", "aIndex")
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "NEW_SELECTION", "\"AREA\" < 15")
arcpy.CopyFeatures_management(
"lyr_existing_cadastre", "results.gdb/Sliver_Polygons_Intermediate")
arcpy.AddSpatialIndex_management(
"results.gdb/Sliver_Polygons_Intermediate")
arcpy.MakeFeatureLayer_management(
"results.gdb/Sliver_Polygons_Intermediate", "lyr_small_area")
arcpy.SelectLayerByAttribute_management(
"lyr_small_area", "NEW_SELECTION", "\"Total_BillCount\" IS NULL")
arcpy.DeleteFeatures_management("lyr_small_area")
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
arcpy.Append_management("lyr_small_area", "lyr_existing_cadastre")
arcpy.Delete_management("results.gdb/Sliver_Polygons_Intermediate")
log("\n \n \t \t Step 5 - Cleaning based on Vested Description")
# Remove from the feature layer the features where the VSTD_DECS is Substation, Waterway, Railway or Unset or Roadway that is also zoned as transport
log("\t Removing features where Vested Description is Substation, Waterway, Railway or Unset or Roadway that is also zoned as transport")
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "NEW_SELECTION", "\"VSTD_DESC\" = \'Substation\' OR \"VSTD_DESC\" = \'Waterway\' OR \"VSTD_DESC\" = \'Railway\' OR \"VSTD_DESC\" = \'Unset\' OR (\"VSTD_DESC\" = \'Roadway\' AND \"ZONING\" LIKE \'%Transport%\') OR (\"VSTD_DESC\" = \'Roadway\' AND \"ZONING\" = \'\')")
arcpy.CopyFeatures_management(
"lyr_existing_cadastre", "results.gdb/VD_Delete")
arcpy.AddSpatialIndex_management("results.gdb/VD_Delete")
vd_delete_num = int(arcpy.GetCount_management(
"results.gdb/VD_Delete").getOutput(0))
if vd_delete_num == 0:
arcpy.Delete_management("results.gdb/VD_Delete")
log("\t ---There are no features where Vested Description is Substation, Waterway, Railway or Unset or Roadway that is also zoned as transport")
else:
arcpy.Delete_management("results.gdb/VD_Delete")
log("\t ---Found and deleted {} features where Vested Description is Substation, Waterway, Railway or Unset or Roadway that is also zoned as transport.".format(
vd_delete_num), "Warning")
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
log("\n \n \t \t Step 6 - Removing unwanted zonings")
# Select from the feature layer the features where the zoning doesn't fall in the other categories but has Transport
log("\t Deleting zoning cases that contain \"Transport\" but don't fall in ZoningCaseA or ZoningCaseB.")
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "NEW_SELECTION", "\"ZONING\" LIKE \'% Transport %\'")
arcpy.DeleteFeatures_management(
"lyr_existing_cadastre")
arcpy.AddSpatialIndex_management("lyr_existing_cadastre")
log("\n \n \t \t Step 7 - Removing Duplicates")
# find any records that have the same LISKEY, SG26CODE and geometry
log("\t Features with identical geometry, LISKEY and SG26 Code")
arcpy.FindIdentical_management("lyr_existing_cadastre", "results.gdb/Identical_Geometry_LISKEY_And_SG26_Report",
["SHAPE", "SL_LAND_PR", "SG26_CODE"], "", "0", "ONLY_DUPLICATES")
identical_records_geomLISSG26_num = int(arcpy.GetCount_management(
"results.gdb/Identical_Geometry_LISKEY_And_SG26_Report").getOutput(0))
if identical_records_geomLISSG26_num == 0:
arcpy.Delete_management(
"results.gdb/Identical_Geometry_LISKEY_And_SG26_Report")
log("\t ---There are no features with identical geometry, LISKEY and SG26 Code.")
else:
arcpy.Delete_management(
"results.gdb/Identical_Geometry_LISKEY_And_SG26_Report")
arcpy.DeleteIdentical_management("lyr_existing_cadastre", [
"SHAPE", "SL_LAND_PR", "SG26_CODE"], "", "0")
log("\t ---Found {} features with identical geometry, LISKEY and SG26 Code and deleted duplicates.".format(
identical_records_geomLISSG26_num))
# find any records that have the same LISKEY and geometry
log("\t Features with identical geometry and LISKEY.")
arcpy.FindIdentical_management("lyr_existing_cadastre", "results.gdb/Identical_Geometry_And_LISKEY_Report", [
"SHAPE", "SL_LAND_PR"], "", "0", "ONLY_DUPLICATES")
identical_records_geomLIS_num = int(arcpy.GetCount_management(
"results.gdb/Identical_Geometry_And_LISKEY_Report").getOutput(0))
if identical_records_geomLIS_num == 0:
arcpy.Delete_management(
"results.gdb/Identical_Geometry_And_LISKEY_Report")
log("\t ---There are no features with identical geometry and LISKEY.")
else:
arcpy.Delete_management(
"results.gdb/Identical_Geometry_And_LISKEY_Report")
arcpy.DeleteIdentical_management("lyr_existing_cadastre", [
"SHAPE", "SL_LAND_PR"], "", "0")
log("\t ---Found {} features with identical geometry and LISKEY and deleted duplicates.".format(
identical_records_geomLIS_num))
# find any records that have the same LISKEY
log("\t Features with identical LISKEY.")
arcpy.FindIdentical_management(
"lyr_existing_cadastre", "results.gdb/Identical_LISKEY_Report", ["SL_LAND_PR"], "", "0", "ONLY_DUPLICATES")
identical_records_LIS_num = int(arcpy.GetCount_management(
"results.gdb/Identical_LISKEY_Report").getOutput(0))
if identical_records_LIS_num == 0:
arcpy.Delete_management("results.gdb/Identical_LISKEY_Report")
log("\t ---There are no features with identical LISKEY.")
else:
arcpy.JoinField_management("lyr_existing_cadastre", "OBJECTID",
"results.gdb/Identical_LISKEY_Report", "IN_FID", ["IN_FID", "FEAT_SEQ"])
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "NEW_SELECTION", "\"IN_FID\" IS NOT NULL")
arcpy.CopyFeatures_management(
"lyr_existing_cadastre", "results.gdb/Identical_LISKEY")
arcpy.Delete_management("results.gdb/Identical_LISKEY_Report")
log("\t ---Found {} features with identical LISKEY that need to be investigated. See Identical_LISKEY for details.".format(
identical_records_LIS_num), "Warning")
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
arcpy.DeleteField_management(
"lyr_existing_cadastre", ["IN_FID", "FEAT_SEQ"])
arcpy.MakeFeatureLayer_management(
"results.gdb/Identical_LISKEY", "lyr_identical_liskey")
# find any records that have the same geometry
log("\t Features with identical geometry.")
arcpy.FindIdentical_management("lyr_existing_cadastre", "results.gdb/Identical_geometry_Report",
["SHAPE"], "", "0", "ONLY_DUPLICATES")
identical_records_geom_num = int(arcpy.GetCount_management(
"results.gdb/Identical_geometry_Report").getOutput(0))
if identical_records_geom_num == 0:
arcpy.Delete_management("results.gdb/Identical_geometry_Report")
log("\t ---There are no features with identical geometry.")
else:
arcpy.JoinField_management("lyr_existing_cadastre", "OBJECTID",
"results.gdb/Identical_geometry_Report", "IN_FID", ["IN_FID", "FEAT_SEQ"])
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "NEW_SELECTION", "\"IN_FID\" IS NOT NULL")
arcpy.CopyFeatures_management(
"lyr_existing_cadastre", "results.gdb/Identical_Geometry")
arcpy.Delete_management("results.gdb/Identical_geometry_Report")
log("\t ---Found {} features with identical geometry that need to be investigated. See Identical_Geometry for details.".format(
identical_records_geom_num), "Warning")
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
arcpy.DeleteField_management(
"lyr_existing_cadastre", ["IN_FID", "FEAT_SEQ"])
arcpy.MakeFeatureLayer_management(
"results.gdb/Identical_Geometry", "lyr_identical_geometry")
log("\n \n \t \t Step 8 - Isolating remaining Road Reserves")
# select all the polygons that intersect with roads and being billed and save them into a new feature class
arcpy.SelectLayerByLocation_management(
"lyr_existing_cadastre", "INTERSECT", "lyr_roads", selection_type="NEW_SELECTION")
arcpy.CopyFeatures_management(
"lyr_existing_cadastre", "results.gdb/Road_Reserves")
arcpy.MakeFeatureLayer_management(
"results.gdb/Road_Reserves", "lyr_road_reserves")
arcpy.AddSpatialIndex_management("lyr_road_reserves")
road_reserves_num = int(arcpy.GetCount_management(
"lyr_road_reserves").getOutput(0))
if road_reserves_num == 0:
arcpy.Delete_management("results.gdb/Road_Reserves")
log("\t ---No road reserves were found.")
else:
log("\t ---Found {} features that are road reserves being billed that need to be investigated. See Road_Reserves for details.".format(
road_reserves_num), "Warning")
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
log("\n \n \t \t Step 9 - Isolating remaining Sliver Polygons")
# select from the feature layer the features where the Area < 4 and save this to a new feature class
arcpy.CalculateField_management(
"lyr_existing_cadastre", 'AREA', "!SHAPE.AREA@SQUAREMETERS!", "PYTHON_9.3")
arcpy.AddIndex_management("lyr_existing_cadastre", "AREA", "aIndex")
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "NEW_SELECTION", "\"AREA\" < 15")
arcpy.CopyFeatures_management(
"lyr_existing_cadastre", "results.gdb/Sliver_Polygons")
arcpy.AddSpatialIndex_management("results.gdb/Sliver_Polygons")
arcpy.MakeFeatureLayer_management(
"results.gdb/Sliver_Polygons", "lyr_small_area")
sliver_polygons_num = int(arcpy.GetCount_management(
"lyr_small_area").getOutput(0))
if sliver_polygons_num == 0:
arcpy.Delete_management("results.gdb/Sliver_Polygons")
log("\t ---No sliver polygons were found.")
else:
log("\t ---Found {} features that are sliver polygons being billed that need to be investigated. See Sliver_Polygons for details.".format(
sliver_polygons_num), "Warning")
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
log("\n \n \t \t Step 10 - Isolating unwanted zonings")
# Remove from the feature layer the features where the zoning starts with Transport
log("\t Zoning cases that start with \"Transport\" and is being billed")
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "NEW_SELECTION", "\"ZONING\" LIKE \'Transport%\'")
arcpy.CopyFeatures_management(
"lyr_existing_cadastre", "results.gdb/Zoning_Case_A")
if identical_records_LIS_num > 0:
arcpy.SelectLayerByAttribute_management(
"lyr_identical_liskey", "NEW_SELECTION", "\"ZONING\" LIKE \'Transport%\'")
arcpy.CopyFeatures_management(
"lyr_identical_liskey", "results.gdb/Zoning_Case_A_LISKEY")
arcpy.MakeFeatureLayer_management(
"results.gdb/Zoning_Case_A_LISKEY", "lyr_zoning_case_a_liskey")
arcpy.Append_management(
"lyr_zoning_case_a_liskey", "results.gdb/Zoning_Case_A", "NO_TEST")
arcpy.DeleteFeatures_management("lyr_identical_liskey")
arcpy.Delete_management("lyr_zoning_case_a_liskey")
if identical_records_geom_num > 0:
arcpy.SelectLayerByAttribute_management(
"lyr_identical_geometry", "NEW_SELECTION", "\"ZONING\" LIKE \'Transport%\'")
arcpy.CopyFeatures_management(
"lyr_identical_geometry", "results.gdb/Zoning_Case_A_Geometry")
arcpy.MakeFeatureLayer_management(
"results.gdb/Zoning_Case_A_Geometry", "lyr_zoning_case_a_geometry")
arcpy.Append_management(
"lyr_zoning_case_a_geometry", "results.gdb/Zoning_Case_A", "NO_TEST")
arcpy.DeleteFeatures_management("lyr_identical_geometry")
arcpy.Delete_management("lyr_zoning_case_a_geometry")
arcpy.AddSpatialIndex_management("results.gdb/Zoning_Case_A")
arcpy.MakeFeatureLayer_management(
"results.gdb/Zoning_Case_A", "lyr_zoning_case_a")
arcpy.SelectLayerByAttribute_management(
"lyr_zoning_case_a", "NEW_SELECTION", "\"Total_BillCount\" IS NULL")
arcpy.DeleteFeatures_management("lyr_zoning_case_a")
zoning_case_a_num = int(arcpy.GetCount_management(
"lyr_zoning_case_a").getOutput(0))
if zoning_case_a_num == 0:
arcpy.Delete_management("results.gdb/Zoning_Case_A")
log("\t ---There are no features that start with \"Transport\" and are being billed")
else:
log("\t ---Found {} features that start with \"Transport\" and are being billed. See Zoning_Case_A for more information".format(
zoning_case_a_num), "Warning")
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
# Select from the feature layer the features where the zoning contains Transport and any of community, mixed, residential, business, billing>1
log("\t Zoning cases that contain \"Transport\" and any of Community, Mixed Use, Residential, Business or billing is greater than one.")
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "NEW_SELECTION", "(\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Community%\' AND \"Total_BillCount\" IS NULL) OR (\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Mixed%\' AND \"Total_BillCount\" IS NULL) OR (\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Residential%\' AND \"Total_BillCount\" IS NULL) OR (\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Business%\' AND \"Total_BillCount\" IS NULL)")
arcpy.CopyFeatures_management(
"lyr_existing_cadastre", "results.gdb/Zoning_Case_B")
if identical_records_LIS_num > 0:
arcpy.SelectLayerByAttribute_management(
"lyr_identical_liskey", "NEW_SELECTION", "(\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Community%\' AND \"Total_BillCount\" IS NULL) OR (\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Mixed%\' AND \"Total_BillCount\" IS NULL) OR (\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Residential%\' AND \"Total_BillCount\" IS NULL) OR (\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Business%\' AND \"Total_BillCount\" IS NULL)")
arcpy.CopyFeatures_management(
"results.gdb/Identical_LISKEY", "results.gdb/Zoning_Case_B_LISKEY")
arcpy.MakeFeatureLayer_management(
"results.gdb/Zoning_Case_B_LISKEY", "lyr_zoning_case_b_liskey")
arcpy.Append_management(
"lyr_zoning_case_b_liskey", "results.gdb/Zoning_Case_B", "NO_TEST")
arcpy.DeleteFeatures_management("lyr_identical_liskey")
arcpy.Delete_management("lyr_zoning_case_b_liskey")
if identical_records_geom_num > 0:
arcpy.SelectLayerByAttribute_management(
"lyr_identical_geometry", "NEW_SELECTION", "(\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Community%\' AND \"Total_BillCount\" IS NULL) OR (\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Mixed%\' AND \"Total_BillCount\" IS NULL) OR (\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Residential%\' AND \"Total_BillCount\" IS NULL) OR (\"ZONING\" LIKE \'%Transport%\' AND \"ZONING\" LIKE \'%Business%\' AND \"Total_BillCount\" IS NULL)")
arcpy.CopyFeatures_management(
"results.gdb/Identical_Geometry", "results.gdb/Zoning_Case_B_Geometry")
arcpy.MakeFeatureLayer_management(
"results.gdb/Zoning_Case_B_Geometry", "lyr_zoning_case_b_geometry")
arcpy.Append_management(
"lyr_zoning_case_b_geometry", "results.gdb/Zoning_Case_B", "NO_TEST")
arcpy.DeleteFeatures_management("lyr_identical_geometry")
arcpy.Delete_management("lyr_zoning_case_b_geometry")
arcpy.AddSpatialIndex_management("results.gdb/Zoning_Case_B")
zoning_case_b_num = int(arcpy.GetCount_management(
"results.gdb/Zoning_Case_B").getOutput(0))
if zoning_case_b_num == 0:
arcpy.Delete_management("results.gdb/Zoning_Case_B")
log("\t ---There are no features that contain \"Transport\" and any of Community, Mixed Use, Residential, Business or billing is greater than one.")
else:
log("\t ---Found {} features that contain \"Transport\" and any of Community, Mixed Use, Residential, Business or billing is greater than one. See Zoning_Case_B for more information".format(
zoning_case_b_num), "Warning")
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
# Select from the feature layer the features where the zoning contains Transport
log("\t Zoning cases that contain \"Transport\".")
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "NEW_SELECTION", "\"ZONING\" LIKE \'%Transport%\'")
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
log("\n \n \t \t Step 11 - Cleaning the Identical Geometry layer")
arcpy.CreateFeatureclass_management("results.gdb", "identical_geometry_output", "POLYGON", "lyr_identical_geometry",
"DISABLED", "DISABLED", arcpy.Describe("lyr_identical_geometry").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/identical_geometry_output", "lyr_identical_geometry_output")
arcpy.CreateFeatureclass_management("results.gdb", "identicals_set", "POLYGON", "lyr_identical_geometry",
"DISABLED", "DISABLED", arcpy.Describe("lyr_identical_geometry").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/identicals_set", "lyr_identicals_set")
arcpy.CreateFeatureclass_management("results.gdb", "registered", "POLYGON", "lyr_identical_geometry",
"DISABLED", "DISABLED", arcpy.Describe("lyr_identical_geometry").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/registered", "lyr_registered")
arcpy.CreateFeatureclass_management("results.gdb", "confirmed", "POLYGON", "lyr_identical_geometry",
"DISABLED", "DISABLED", arcpy.Describe("lyr_identical_geometry").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/confirmed", "lyr_confirmed")
arcpy.CreateFeatureclass_management("results.gdb", "sg_approved", "POLYGON", "lyr_identical_geometry",
"DISABLED", "DISABLED", arcpy.Describe("lyr_identical_geometry").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/sg_approved", "lyr_sg_approved")
arcpy.CreateFeatureclass_management("results.gdb", "highest_liskey", "POLYGON", "lyr_identical_geometry",
"DISABLED", "DISABLED", arcpy.Describe("lyr_identical_geometry").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/highest_liskey", "lyr_highest_liskey")
with arcpy.da.UpdateCursor("lyr_identical_geometry", ["FEAT_SEQ", "SL_LAND_PR", "Total_BillCount", "LU_LGL_STS"]) as update_cursor:
for row in update_cursor:
# CHECK BILLING
# Select all features with a FEAT_SEQ of min_value and save them into a seperate layer
arcpy.SelectLayerByAttribute_management(
"lyr_identical_geometry", "NEW_SELECTION", "\"FEAT_SEQ\" = " + str(row[0]))
arcpy.Append_management(
"lyr_identical_geometry", "lyr_identicals_set", "NO_TEST")
arcpy.DeleteFeatures_management("lyr_identical_geometry")
# Check if all the billings are the same
arcpy.FindIdentical_management("lyr_identicals_set", "results.gdb/Identical_billings_Report",
["Total_BillCount"], "", "0", "ONLY_DUPLICATES")
# If billings are not the same and there is only one feature being billed keep the feature being billed
if (int(arcpy.GetCount_management("lyr_identicals_set").getOutput(0)) != int(arcpy.GetCount_management("results.gdb/Identical_billings_Report").getOutput(0))):
arcpy.Delete_management(
"results.gdb/Identical_billings_Report")
arcpy.SelectLayerByAttribute_management(
"lyr_identicals_set", "NEW_SELECTION", "\"Total_BillCount\" = 0")
arcpy.DeleteFeatures_management("lyr_identicals_set")
if (int(arcpy.GetCount_management("lyr_identicals_set").getOutput(0)) == 1):
arcpy.Append_management(
"lyr_identicals_set", "lyr_identical_geometry_output", "NO_TEST")
arcpy.DeleteFeatures_management("lyr_identicals_set")
continue
# CHECK LEGAL STATUS
# Check if the features all have the same legal status
arcpy.FindIdentical_management("lyr_identicals_set", "results.gdb/Identical_lgl_sts_Report",
["LU_LGL_STS"], "", "0", "ONLY_DUPLICATES")
# If the legal statuses are not the same then use the haerachy to select the one to keep
if (int(arcpy.GetCount_management("lyr_identicals_set").getOutput(0)) != int(arcpy.GetCount_management("results.gdb/Identical_lgl_sts_Report").getOutput(0))):
arcpy.Delete_management(
"results.gdb/Identical_lgl_sts_Report")
# Registered
arcpy.SelectLayerByAttribute_management(
"lyr_identicals_set", "NEW_SELECTION", "\"LU_LGL_STS\" = \'Registered\'")
arcpy.Append_management(
"lyr_identicals_set", "lyr_registered", "NO_TEST")
registered_num = int(arcpy.GetCount_management(
"lyr_registered").getOutput(0))
if (registered_num == 1):
arcpy.Append_management(
"lyr_registered", "lyr_identical_geometry_output", "NO_TEST")
arcpy.DeleteFeatures_management("lyr_registered")
continue
elif (registered_num == 0):
# Confirmed
arcpy.SelectLayerByAttribute_management(
"lyr_identicals_set", "NEW_SELECTION", "\"LU_LGL_STS\" = \'Confirmed\'")
arcpy.Append_management(
"lyr_identicals_set", "lyr_confirmed", "NO_TEST")
confirmed_num = int(arcpy.GetCount_management(
"lyr_confirmed").getOutput(0))
if (confirmed_num == 1):
arcpy.Append_management(
"lyr_confirmed", "lyr_identical_geometry_output", "NO_TEST")
arcpy.DeleteFeatures_management(
"lyr_confirmed")
continue
elif (confirmed_num == 0):
# SG Approved
arcpy.SelectLayerByAttribute_management(
"lyr_identicals_set", "NEW_SELECTION", "\"LU_LGL_STS\" = \'SG Approved\'")
arcpy.Append_management(
"lyr_identicals_set", "lyr_sg_approved", "NO_TEST")
sg_approved_num = int(arcpy.GetCount_management(
"lyr_sg_approved").getOutput(0))
if (sg_approved_num == 1):
arcpy.Append_management(
"lyr_sg_approved", "lyr_identical_geometry_output", "NO_TEST")
arcpy.DeleteFeatures_management(
"lyr_sg_approved")
continue
# CHECK LISKEY
max_value = arcpy.da.SearchCursor("lyr_identicals_set", "SL_LAND_PR", sql_clause=(
None, "ORDER BY SL_LAND_PR DESC")).next()[0]
arcpy.SelectLayerByAttribute_management(
"lyr_identicals_set", "NEW_SELECTION", "\"SL_LAND_PR\" = " + str(max_value))
arcpy.Append_management(
"lyr_identicals_set", "lyr_identical_geometry_output", "NO_TEST")
arcpy.DeleteFeatures_management(
"lyr_identicals_set")
arcpy.Delete_management(
"results.gdb/Identical_billings_Report")
arcpy.Delete_management(
"results.gdb/Identical_lgl_sts_Report")
del update_cursor
arcpy.Delete_management("results.gdb/identicals_set")
arcpy.Delete_management("results.gdb/identical_geometry")
arcpy.Delete_management("results.gdb/registered")
arcpy.Delete_management("results.gdb/confirmed")
arcpy.Delete_management("results.gdb/sg_approved")
arcpy.Delete_management("results.gdb/highest_liskey")
arcpy.Append_management(
"lyr_identical_geometry_output", "lyr_existing_cadastre", "NO_TEST")
arcpy.Delete_management("results.gdb/identical_geometry_output")
log("\n \n \t \t Step 12 - Isolating Overlapping Polygons")
arcpy.CreateFeatureclass_management("results.gdb", "Overlapping_Polygons", "POLYGON", "lyr_existing_cadastre",
"DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/Overlapping_Polygons", "lyr_Overlapping_Polygons")
arcpy.CreateFeatureclass_management("results.gdb", "Remaining_Polygons", "POLYGON", "lyr_existing_cadastre",
"DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/Remaining_Polygons", "lyr_Remaining_Polygons")
arcpy.CreateFeatureclass_management("results.gdb", "row", "POLYGON", "lyr_existing_cadastre",
"DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/row", "lyr_row")
arcpy.AddSpatialIndex_management("lyr_existing_cadastre")
with arcpy.da.SearchCursor("lyr_existing_cadastre", ["OBJECTID"]) as search_cursor:
for row in search_cursor:
log("\t {}".format(row[0]))
# Get the OBJECTID of row and use it to select row
arcpy.SelectLayerByAttribute_management("lyr_existing_cadastre", "NEW_SELECTION",
"\"OBJECTID\" = " + str(row[0]))
# Copy row into a new feature class called row
arcpy.Append_management(
"lyr_existing_cadastre", "lyr_row", "NO_TEST")
# Remove row from the input
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
# Select all features that intersect with row and copy them into the row feature class
arcpy.SelectLayerByLocation_management(
"lyr_existing_cadastre", "WITHIN", "lyr_row", selection_type="NEW_SELECTION")
arcpy.Append_management(
"lyr_existing_cadastre", "lyr_row", "NO_TEST")
# If there is more than one feature in the row feature class
# meaning there was something else in addition to row then delete those overlaps
# from the input and append everything in row into the output feature class
if (int(arcpy.GetCount_management("lyr_row").getOutput(0)) > 1):
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
arcpy.Append_management(
"lyr_row", "lyr_Overlapping_Polygons", "NO_TEST")
else:
arcpy.Append_management(
"lyr_row", "lyr_Remaining_Polygons", "NO_TEST")
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "CLEAR_SELECTION")
arcpy.TruncateTable_management("lyr_row")
del search_cursor
# Count the numver of features in the overlapping polygons feature class and report
overlapping_polygons_num = int(arcpy.GetCount_management(
"lyr_Overlapping_Polygons").getOutput(0))
if (overlapping_polygons_num > 0):
log("\t Found {} features that overlap with other features.".format(
overlapping_polygons_num))
else:
arcpy.Delete_management(
"results.gdb/Overlapping_Polygons")
log("\t No overlapping features were found")
arcpy.Delete_management(
"results.gdb/row")
arcpy.Delete_management(
"results.gdb/existing_cadastre_sp")
log("\n \n \t \t Step 13 - Final Service layer")
# count the number of records in final_service_layer
final_service_layer_num = int(arcpy.GetCount_management(
"lyr_Remaining_Polygons").getOutput(0))
if final_service_layer_num == 0:
arcpy.Delete_management("lyr_Remaining_Polygons")
log("\t ---No features left.")
else:
log("\t ---{} features left after all the steps. See Remaining_Features for details.".format(
final_service_layer_num), "Warning")
arcpy.Delete_management("results.gdb/billing_data")
arcpy.Delete_management("results.gdb/roads")
arcpy.Delete_management("results.gdb/existing_cadastre_mp")
arcpy.Delete_management("results.gdb/Zoning_Case_A_Geometry")
arcpy.Delete_management("results.gdb/Zoning_Case_A_LISKEY")
arcpy.Delete_management("results.gdb/Zoning_Case_B_Geometry")
arcpy.Delete_management("results.gdb/Zoning_Case_B_LISKEY")
log("\n \n \t \t \t Process Complete.")
except:
ramm.handleExcept(logger)
<file_sep>""" -----------------------------------------------------------------------------
Tool Name: Cadastre Identical Geometries Cleanup
Version: 1.0
Description: Tool used to clean up the identical geometries layer from the
cadastre layer.
Author: <NAME>
Date: 2019-01-28
Last Revision: 2019-01-28
------------------------------------------------------------------------------ """
import arcpy
import ramm
input_data = arcpy.GetParameterAsText(0)
output_location = arcpy.GetParameterAsText(1)
# Prepare environment
arcpy.env.overwriteOutput = True
arcpy.env.workspace = output_location
# initialize logger
logger = ramm.defineLogger(output_location)
# Simplify message generator
def log(message, messageType="Message"):
ramm.showPyMessage(message, logger, messageType)
log("\t Starting Process")
log("\t Preparing Intemediates")
arcpy.CreateFileGDB_management(
output_location, "Clean_Identical_Geometry_Results.gdb")
arcpy.MakeFeatureLayer_management(input_data, "input_data")
arcpy.FeatureClassToGeodatabase_conversion(
["input_data"], "Clean_Identical_Geometry_Results.gdb")
arcpy.MakeFeatureLayer_management(
"Clean_Identical_Geometry_Results.gdb/input_data", "lyr_input_data")
arcpy.CreateFeatureclass_management("Clean_Identical_Geometry_Results.gdb", "output_data", "POLYGON", "lyr_input_data",
"DISABLED", "DISABLED", arcpy.Describe("lyr_input_data").spatialReference)
arcpy.MakeFeatureLayer_management(
"Clean_Identical_Geometry_Results.gdb/output_data", "lyr_output_data")
arcpy.CreateFeatureclass_management("Clean_Identical_Geometry_Results.gdb", "identicals_set", "POLYGON", "lyr_input_data",
"DISABLED", "DISABLED", arcpy.Describe("lyr_input_data").spatialReference)
arcpy.MakeFeatureLayer_management(
"Clean_Identical_Geometry_Results.gdb/identicals_set", "lyr_identicals_set")
arcpy.CreateFeatureclass_management("Clean_Identical_Geometry_Results.gdb", "registered", "POLYGON", "lyr_input_data",
"DISABLED", "DISABLED", arcpy.Describe("lyr_input_data").spatialReference)
arcpy.MakeFeatureLayer_management(
"Clean_Identical_Geometry_Results.gdb/registered", "lyr_registered")
arcpy.CreateFeatureclass_management("Clean_Identical_Geometry_Results.gdb", "confirmed", "POLYGON", "lyr_input_data",
"DISABLED", "DISABLED", arcpy.Describe("lyr_input_data").spatialReference)
arcpy.MakeFeatureLayer_management(
"Clean_Identical_Geometry_Results.gdb/confirmed", "lyr_confirmed")
arcpy.CreateFeatureclass_management("Clean_Identical_Geometry_Results.gdb", "sg_approved", "POLYGON", "lyr_input_data",
"DISABLED", "DISABLED", arcpy.Describe("lyr_input_data").spatialReference)
arcpy.MakeFeatureLayer_management(
"Clean_Identical_Geometry_Results.gdb/sg_approved", "lyr_sg_approved")
arcpy.CreateFeatureclass_management("Clean_Identical_Geometry_Results.gdb", "highest_liskey", "POLYGON", "lyr_input_data",
"DISABLED", "DISABLED", arcpy.Describe("lyr_input_data").spatialReference)
arcpy.MakeFeatureLayer_management(
"Clean_Identical_Geometry_Results.gdb/highest_liskey", "lyr_highest_liskey")
with arcpy.da.UpdateCursor("lyr_input_data", ["FEAT_SEQ", "SL_LAND_PR", "Total_BillCount", "LU_LGL_STS"]) as update_cursor:
for row in update_cursor:
# Get the minimum value in the Feat_Seq field
# min_value = arcpy.da.SearchCursor("lyr_input_data", "FEAT_SEQ", sql_clause=(
# None, "ORDER BY FEAT_SEQ ASC")).next()[0]
log("\t Checking Billing for feature sequence {}".format(row[0]))
# CHECK BILLING
# Select all features with a FEAT_SEQ of min_value and save them into a seperate layer
arcpy.SelectLayerByAttribute_management(
"lyr_input_data", "NEW_SELECTION", "\"FEAT_SEQ\" = " + str(row[0]))
arcpy.Append_management(
"lyr_input_data", "lyr_identicals_set", "NO_TEST")
arcpy.DeleteFeatures_management("lyr_input_data")
# Check if all the billings are the same
arcpy.FindIdentical_management("lyr_identicals_set", "Clean_Identical_Geometry_Results.gdb/Identical_billings_Report",
["Total_BillCount"], "", "0", "ONLY_DUPLICATES")
# If billings are not the same and there is only one feature being billed keep the feature being billed
if (int(arcpy.GetCount_management("lyr_identicals_set").getOutput(0)) != int(arcpy.GetCount_management("Clean_Identical_Geometry_Results.gdb/Identical_billings_Report").getOutput(0))):
arcpy.Delete_management(
"Clean_Identical_Geometry_Results.gdb/Identical_billings_Report")
arcpy.SelectLayerByAttribute_management(
"lyr_identicals_set", "NEW_SELECTION", "\"Total_BillCount\" = 0")
arcpy.DeleteFeatures_management("lyr_identicals_set")
if (int(arcpy.GetCount_management("lyr_identicals_set").getOutput(0)) == 1):
arcpy.Append_management(
"lyr_identicals_set", "lyr_output_data", "NO_TEST")
arcpy.DeleteFeatures_management("lyr_identicals_set")
continue
log("\t Checking Legal Status for feature sequence {}".format(row[0]))
# CHECK LEGAL STATUS
# Check if the features all have the same legal status
arcpy.FindIdentical_management("lyr_identicals_set", "Clean_Identical_Geometry_Results.gdb/Identical_lgl_sts_Report",
["LU_LGL_STS"], "", "0", "ONLY_DUPLICATES")
# If the legal statuses are not the same then use the haerachy to select the one to keep
if (int(arcpy.GetCount_management("lyr_identicals_set").getOutput(0)) != int(arcpy.GetCount_management("Clean_Identical_Geometry_Results.gdb/Identical_lgl_sts_Report").getOutput(0))):
arcpy.Delete_management(
"Clean_Identical_Geometry_Results.gdb/Identical_lgl_sts_Report")
# Registered
arcpy.SelectLayerByAttribute_management(
"lyr_identicals_set", "NEW_SELECTION", "\"LU_LGL_STS\" = \'Registered\'")
arcpy.Append_management(
"lyr_identicals_set", "lyr_registered", "NO_TEST")
registered_num = int(arcpy.GetCount_management(
"lyr_registered").getOutput(0))
if (registered_num == 1):
arcpy.Append_management(
"lyr_registered", "lyr_output_data", "NO_TEST")
arcpy.DeleteFeatures_management("lyr_registered")
continue
elif (registered_num == 0):
# Confirmed
arcpy.SelectLayerByAttribute_management(
"lyr_identicals_set", "NEW_SELECTION", "\"LU_LGL_STS\" = \'Confirmed\'")
arcpy.Append_management(
"lyr_identicals_set", "lyr_confirmed", "NO_TEST")
confirmed_num = int(arcpy.GetCount_management(
"lyr_confirmed").getOutput(0))
if (confirmed_num == 1):
arcpy.Append_management(
"lyr_confirmed", "lyr_output_data", "NO_TEST")
arcpy.DeleteFeatures_management(
"lyr_confirmed")
continue
elif (confirmed_num == 0):
# SG Approved
arcpy.SelectLayerByAttribute_management(
"lyr_identicals_set", "NEW_SELECTION", "\"LU_LGL_STS\" = \'SG Approved\'")
arcpy.Append_management(
"lyr_identicals_set", "lyr_sg_approved", "NO_TEST")
sg_approved_num = int(arcpy.GetCount_management(
"lyr_sg_approved").getOutput(0))
if (sg_approved_num == 1):
arcpy.Append_management(
"lyr_sg_approved", "lyr_output_data", "NO_TEST")
arcpy.DeleteFeatures_management(
"lyr_sg_approved")
continue
log("\t Checking LISKEY for feature sequence {}".format(row[0]))
# CHECK LISKEY
max_value = arcpy.da.SearchCursor("lyr_identicals_set", "SL_LAND_PR", sql_clause=(
None, "ORDER BY SL_LAND_PR DESC")).next()[0]
arcpy.SelectLayerByAttribute_management(
"lyr_identicals_set", "NEW_SELECTION", "\"SL_LAND_PR\" = " + str(max_value))
arcpy.Append_management(
"lyr_identicals_set", "lyr_output_data", "NO_TEST")
arcpy.DeleteFeatures_management(
"lyr_identicals_set")
del update_cursor
arcpy.Delete_management("Clean_Identical_Geometry_Results.gdb/identicals_set")
arcpy.Delete_management("Clean_Identical_Geometry_Results.gdb/input_data")
arcpy.Delete_management("Clean_Identical_Geometry_Results.gdb/registered")
arcpy.Delete_management("Clean_Identical_Geometry_Results.gdb/confirmed")
arcpy.Delete_management("Clean_Identical_Geometry_Results.gdb/sg_approved")
arcpy.Delete_management("Clean_Identical_Geometry_Results.gdb/highest_liskey")
log("\t Process Complete")
<file_sep># Tool for creating 10m buffers around collection points
# Developed by <NAME>
import arcpy
import ramm
arcpy.env.overwriteOutput = True
try:
# Get inputs
col_points = arcpy.GetParameterAsText(0)
boundary = arcpy.GetParameterAsText(1)
buff_dist = arcpy.GetParameterAsText(2)
output_location = arcpy.GetParameterAsText(3)
filename = arcpy.GetParameterAsText(4)
# Set the workspace
arcpy.env.workspace = output_location
logger = ramm.defineLogger(output_location)
def log(message):
ramm.showPyMessage(message, logger)
# Make feature layers from the input datasets
log("\t - Beginning Process.")
arcpy.MakeFeatureLayer_management(col_points, "lyr_col_points")
# Use the boundary dataset to clip the relevant features
log("\t --- Clipping Features.")
arcpy.MakeFeatureLayer_management(boundary, "lyr_boundary")
arcpy.Clip_analysis("lyr_col_points", "lyr_boundary",
"col_points_clipped.shp")
# Repair the geometry
log("\t --- Repairing Geometry.")
arcpy.MakeFeatureLayer_management(
"col_points_clipped.shp", "lyr_col_points_clipped")
arcpy.CheckGeometry_management(
"lyr_col_points_clipped", "geomErrorReport.dbf")
no_of_errors = int(arcpy.GetCount_management(
"geomErrorReport.dbf").getOutput(0))
arcpy.RepairGeometry_management("lyr_col_points_clipped")
log(
"\t ----- {} geometry errors were found and repaired. Check geomErrorReport.dbf for details.".format(no_of_errors))
# Create Buffers
log("\t --- Creating Buffers")
buff_dist_wunits = buff_dist + " Meters"
arcpy.Buffer_analysis("lyr_col_points_clipped",
"col_points_buffered.shp", buff_dist_wunits, "FULL", "ROUND", "ALL")
log("\t --- Deagreggating Buffers")
arcpy.MultipartToSinglepart_management(
"col_points_buffered.shp", "col_points_buffered_split.shp")
no_of_buffers = int(arcpy.GetCount_management(
"col_points_buffered_split.shp").getOutput(0))
arcpy.Rename_management(
"col_points_buffered_split.shp", "{}.shp".format(filename))
arcpy.Delete_management("col_points_buffered.shp")
log(
"\t - Process Complete. {} buffers were created.".format(no_of_buffers))
except Exception as e:
ramm.handleExcept(logger)
<file_sep># """-----------------------------------------------------------------------------
# Script Name: Process Images
# Description: This tool will process the images for the mapsets by
# performing the following steps:
# 1. Mosaic to new raster
# 2. Resample from 8cm pixels to 16cm pixels
# 3. Reproject them to WGS84
# Created By: <NAME>
# Date: 2018-06-29
# Last Revision: 2018-09-12
# -----------------------------------------------------------------------------"""
# Import arcpy module
import arcpy
import time
import ramm
import os
arcpy.env.overwriteOutput = True
try:
# Load required toolboxes
# arcpy.ImportToolbox("Model Functions")
images_folder = arcpy.GetParameterAsText(0)
source_projection = arcpy.GetParameterAsText(1)
output_projection = arcpy.GetParameterAsText(2)
mosaic_location = arcpy.GetParameterAsText(3)
output_location = arcpy.GetParameterAsText(4)
arcpy.env.workspace = images_folder
logger = ramm.defineLogger(output_location)
def log(message):
ramm.showPyMessage(message, logger)
for_mosaic1 = arcpy.ListRasters()
log("Step 1: Mosaic To New Raster")
for x in for_mosaic1:
log("--- " + x)
arcpy.MosaicToNewRaster_management(x, mosaic_location, os.path.basename(x).rstrip(os.path.splitext(
x)[1]) + ".tif", source_projection, "8_BIT_UNSIGNED", "", "3", "LAST", "FIRST")
arcpy.AddMessage("-- done.")
arcpy.env.workspace = mosaic_location
for_resample = arcpy.ListRasters()
log("Step 2: Resampling ")
for x in for_resample:
log("--- " + x)
arcpy.Resample_management(
x, os.path.basename(x).rstrip(os.path.splitext(
x)[1]) + "_16cm.tif", "0.16 0.16", "NEAREST")
arcpy.Delete_management(x)
arcpy.AddMessage("-- done.")
arcpy.env.workspace = mosaic_location
for_mosaic2 = arcpy.ListRasters()
log("Step 3: Project to WGS84 ")
for x in for_mosaic2:
log("--- " + x)
# arcpy.ProjectRaster_management(x, os.path.basename(x).rstrip(os.path.splitext(
# x)[1]) + "_wgs84.tif", output_projection, "", "", "Hartebeesthoek94_To_WGS_1984", "", source_projection)
arcpy.MosaicToNewRaster_management(x, output_location, os.path.basename(x).rstrip(os.path.splitext(
x)[1]) + "_wgs84.tif", output_projection, "8_BIT_UNSIGNED", "", "3", "LAST", "FIRST")
arcpy.AddMessage("-- done.")
log("Image Processing Completed Successfully.")
except:
ramm.handleExcept(logger)
<file_sep># """-----------------------------------------------------------------------------
# Script Name: Generate Record Number
# Description: Generates the record number for any dataset given the prefix
# and the start number
# Created By: <NAME>
# Date: 2018-06-21
# Last Revision: 2018-09-13
# -----------------------------------------------------------------------------"""
import arcpy
import ramm
try:
# input data
input_data = arcpy.GetParameterAsText(0)
recno_prefix = arcpy.GetParameterAsText(1)
startNumber = arcpy.GetParameterAsText(2)
log_output = arcpy.GetParameterAsText(3)
# define the logger
logger = ramm.defineLogger(log_output)
def log(message):
ramm.showPyMessage(message, logger)
log("Starting Process")
arcpy.MakeFeatureLayer_management(input_data, "input_data")
with arcpy.da.UpdateCursor("input_data", 'RECNO') as update_cursor:
for x in update_cursor:
# generate record number
x[0] = ramm.populateRecNo(recno_prefix, startNumber)
update_cursor.updateRow(x)
del update_cursor
log("Record Numbers Generated Successfully!")
except:
ramm.handleExcept(logger)
<file_sep>""" -----------------------------------------------------------------------------
Tool Name: Transform Cadastral Dataset Schema
Version: 1.0
Description: This tool will change the schema of the cadastral dataset from
the city into the one used at RAMM
Author: <NAME>
Date: 2018-11-29
Last Revision: 2018-11-29
------------------------------------------------------------------------------ """
import arcpy
import time
import ramm
try:
# get inputs
input_dataset = arcpy.GetParameterAsText(0)
output_location = arcpy.GetParameterAsText(1)
cad_schema_template = arcpy.GetParameterAsText(2)
fieldMap = arcpy.GetParameterAsText(3)
spatial_lmun = arcpy.GetParameterAsText(4)
spatial_dmun = arcpy.GetParameterAsText(5)
spatial_prov = arcpy.GetParameterAsText(6)
city_name = arcpy.GetParameterAsText(7)
provcode = arcpy.GetParameterAsText(8)
country = arcpy.GetParameterAsText(9)
arcpy.env.overwriteOutput = True
rec = 0
# initialize logger
logger = ramm.defineLogger(output_location)
# simplify messege generator
def log(message):
ramm.showPyMessage(message, logger)
# set the workspace
log("\t Step 1 - Preparing Environment")
log("\t ...Setting the workspace and generating intemediary datasets")
arcpy.env.workspace = output_location
# create temporary geodatabase for temporary geoprocessing tasks
log("\t ...Creating the results geodatabase")
arcpy.CreateFileGDB_management(output_location, "results.gdb")
# make feature layer from the dataset
arcpy.MakeFeatureLayer_management(input_dataset, "input_dataset")
# add the dataset to the geodatabase
log("\t ...Adding the existing dataset into the geodatabase")
arcpy.FeatureClassToGeodatabase_conversion(
["input_dataset"], "results.gdb")
# make feature layer from the existing dataset
arcpy.MakeFeatureLayer_management(
"results.gdb/input_dataset", "lyr_input_dataset_gp")
arcpy.AddSpatialIndex_management("lyr_input_dataset_gp")
# create an empty feature class in the temporary geodatabase
arcpy.CreateFeatureclass_management("results.gdb", "formatted_input", "POLYGON", cad_schema_template,
"DISABLED", "DISABLED", arcpy.Describe(cad_schema_template).spatialReference)
# make layer from the formatted_input feature class
arcpy.MakeFeatureLayer_management(
"results.gdb/formatted_input", "lyr_formatted_input")
arcpy.AddSpatialIndex_management("lyr_formatted_input")
log("\t Step 2 - Reformatting Dataset")
# build field mappings and append the data into lyr_formatted_input
log("\t ...Creating field mappings and formating table")
ramm.mapFields("lyr_input_dataset_gp", "lyr_formatted_input", fieldMap)
arcpy.AddSpatialIndex_management("lyr_formatted_input")
# check the geometry of the formatted_input feature class
log("\t ...Checking and repairing the geometry")
arcpy.CheckGeometry_management(
"lyr_formatted_input", "results.gdb/geomErrorReport")
# get the number of records in the geometry errors report and if there are no features then delete the report
no_of_geom_errors = int(arcpy.GetCount_management(
"results.gdb/geomErrorReport").getOutput(0))
if no_of_geom_errors == 0:
# delete the empty report
arcpy.Delete_management("results.gdb/geomErrorReport")
else:
# repair geometry errors on the changes_unformated feature class
arcpy.RepairGeometry_management("lyr_formatted_input")
# count the number of records in formatted_input
no_of_records_formated = int(arcpy.GetCount_management(
"lyr_formatted_input").getOutput(0))
# capitalise the Street Suffix data
arcpy.CalculateField_management(
"lyr_formatted_input", "STREETSUFF", "!STREETSUFF!.upper()", "PYTHON_9.3")
# populate fields
log("\t ...Populating the Local Municipality, District "
"Municipality, Admin District Code and Province fields based on a spatial join.")
ramm.populateUsingSpatialJoin(
"lyr_formatted_input", spatial_lmun, "LOCALMUN", "FULLNAME", "INTERSECT")
ramm.populateUsingSpatialJoin(
"lyr_formatted_input", spatial_dmun, "DISTRICTMU", "FULLNAME", "INTERSECT")
ramm.populateUsingSpatialJoin(
"lyr_formatted_input", spatial_dmun, "ADMINDISCO", "DISTRICTCO", "INTERSECT")
ramm.populateUsingSpatialJoin(
"lyr_formatted_input", spatial_prov, "PROVINCE", "PROVNAME", "INTERSECT")
# generate calculated fields, ie Area, Perimeter, Cent_x and Cent_y
log(
"\t ...Calculating the Area, Perimeter, Centroid X and Centroid Y fields")
arcpy.CalculateField_management(
"lyr_formatted_input", 'AREA', "!SHAPE.AREA@SQUAREMETERS!", "PYTHON_9.3")
arcpy.CalculateField_management(
"lyr_formatted_input", 'PERIMETER', "!SHAPE.LENGTH@METERS!", "PYTHON_9.3")
arcpy.CalculateField_management(
"lyr_formatted_input", 'CENT_X', "!SHAPE.CENTROID.X!", "PYTHON_9.3")
arcpy.CalculateField_management(
"lyr_formatted_input", 'CENT_Y', "!SHAPE.CENTROID.Y!", "PYTHON_9.3")
# fields for the update cursor
log("\t ...Populating the DESC_, TOWNSHIPCO, COUNTRY, PROVINCECO, EXTENTCO, ERFNO, "
"PORTIONNO, REMAINDER and CITYNAME fields")
fields = ['DESC_', 'TOWNSHIPCO', 'EXTENTCO', 'ERFNO', 'PORTIONNO', 'REMAINDER', 'CITYSG26CO', 'STREETNO',
'STREETNAME', 'STREETSUFF', 'SUBURBNAME', 'CENT_X', 'CENT_Y', 'COUNTRY', 'PROVINCECO', 'CITYNAME']
# main code
with arcpy.da.UpdateCursor("lyr_formatted_input", fields) as update_cursor:
for x in update_cursor:
# description
x[0] = x[7] + ', ' + x[8] + ', ' + x[9] + ', ' + x[10]
# decoding the SG26 Code
[x[1], x[2], x[3], x[4], x[5]] = ramm.decodeCitySG26Code(x[6])
x[13] = country
x[14] = provcode
x[15] = city_name
update_cursor.updateRow(x)
del update_cursor
log(
"\t Step 2 completed successfully.")
log("\t Process completed successfully!")
arcpy.ClearWorkspaceCache_management()
except:
ramm.handleExcept(logger)
<file_sep>
arcpy.CreateFeatureclass_management("results.gdb", "Overlapping_Polygons", "POLYGON", "lyr_existing_cadastre",
"DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/Overlapping_Polygons", "lyr_Overlapping_Polygons")
arcpy.CreateFeatureclass_management("results.gdb", "Remaining_Polygons", "POLYGON", "lyr_existing_cadastre",
"DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/Remaining_Polygons", "lyr_Remaining_Polygons")
arcpy.CreateFeatureclass_management("results.gdb", "row", "POLYGON", "lyr_existing_cadastre",
"DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)
arcpy.MakeFeatureLayer_management(
"results.gdb/row", "lyr_row")
input_geometries = arcpy.CopyFeatures_management("lyr_existing_cadastre", arcpy.Geometry())
with arcpy.da.SearchCursor("lyr_existing_cadastre", ["OBJECTID"]) as search_cursor:
for row in search_cursor:
# Get the OBJECTID of row and use it to select row
arcpy.SelectLayerByAttribute_management("lyr_existing_cadastre", "NEW_SELECTION",
"\"OBJECTID\" = " + str(row[0]))
# Copy row into a new feature class called row
arcpy.Append_management(
"lyr_existing_cadastre", "lyr_row", "NO_TEST")
# Remove row from the input
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
# Select all features that intersect with row and copy them into the row feature class
arcpy.SelectLayerByLocation_management(
"lyr_existing_cadastre", "INTERSECT", "lyr_row", selection_type="NEW_SELECTION")
arcpy.Append_management(
"lyr_existing_cadastre", "lyr_row", "NO_TEST")
# If there is more than one feature in the row feature class
# meaning there was something else in addition to row then delete those overlaps
# from the input and append everything in row into the output feature class
if (int(arcpy.GetCount_management("lyr_row").getOutput(0)) > 1):
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
arcpy.Append_management(
"lyr_row", "lyr_Overlapping_Polygons", "NO_TEST")
else:
arcpy.Append_management(
"lyr_row", "lyr_Remaining_Polygons", "NO_TEST")
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "CLEAR_SELECTION")
arcpy.TruncateTable_management("lyr_row")
del search_cursor
# Count the numver of features in the overlapping polygons feature class and report
overlapping_polygons_num = int(arcpy.GetCount_management(
"lyr_Overlapping_Polygons").getOutput(0))
if (overlapping_polygons_num > 0):
log("\t Found {} features that overlap with other features.".format(
overlapping_polygons_num))
else:
arcpy.Delete_management(
"results.gdb/lyr_Overlapping_Polygons")
log("\t No overlapping features were found")
arcpy.Delete_management(
"results.gdb/row")
arcpy.CreateFeatureclass_management("results.gdb", "Overlapping_Polygons", "POLYGON", "lyr_existing_cadastre", "DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)
arcpy.MakeFeatureLayer_management("results.gdb/Overlapping_Polygons", "lyr_Overlapping_Polygons")
arcpy.CreateFeatureclass_management("results.gdb", "Remaining_Polygons", "POLYGON", "lyr_existing_cadastre", "DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)
arcpy.MakeFeatureLayer_management("results.gdb/Remaining_Polygons", "lyr_Remaining_Polygons")
arcpy.CreateFeatureclass_management("in_memory", "row", "POLYGON", "lyr_existing_cadastre", "DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference)
arcpy.MakeFeatureLayer_management("row", "lyr_row")
arcpy.AddSpatialIndex_management("lyr_existing_cadastre")
with arcpy.da.SearchCursor("lyr_existing_cadastre", ["OBJECTID"]) as search_cursor:
for row in search_cursor:
log("\t {}".format(row[0]))
# Get the OBJECTID of row and use it to select row
arcpy.SelectLayerByAttribute_management("lyr_existing_cadastre", "NEW_SELECTION",
"\"OBJECTID\" = " + str(row[0]))
# Copy row into a new feature class called row
arcpy.Append_management(
"lyr_existing_cadastre", "lyr_row", "NO_TEST")
# Remove row from the input
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
# Select all features that intersect with row and copy them into the row feature class
arcpy.SelectLayerByLocation_management(
"lyr_existing_cadastre", "WITHIN", "lyr_row", selection_type="NEW_SELECTION")
arcpy.Append_management(
"lyr_existing_cadastre", "lyr_row", "NO_TEST")
# If there is more than one feature in the row feature class
# meaning there was something else in addition to row then delete those overlaps
# from the input and append everything in row into the output feature class
if (int(arcpy.GetCount_management("lyr_row").getOutput(0)) > 1):
arcpy.DeleteFeatures_management("lyr_existing_cadastre")
arcpy.Append_management(
"lyr_row", "lyr_Overlapping_Polygons", "NO_TEST")
else:
arcpy.Append_management(
"lyr_row", "lyr_Remaining_Polygons", "NO_TEST")
arcpy.SelectLayerByAttribute_management(
"lyr_existing_cadastre", "CLEAR_SELECTION")
arcpy.TruncateTable_management("lyr_row")
del search_cursor | 4013b0fe05717005a08167cc2f5707390ea2780e | [
"Markdown",
"Python"
]
| 15 | Python | bhekanik/arcpyTools | 0c116e64afa475e501a929b629703d48174a1615 | 1613cb4278ab3a14cd2ff78bdb9aa73a9b399ef6 |
refs/heads/master | <file_sep>MyBlog::Application.routes.draw do
root 'home#index'
get 'tags/:tag', to: 'posts#index', as: :tag
get 'about' => 'home#about', :as => 'about'
resources :posts
resources :works
# 后台路由
namespace :admin do
root :to => 'home#index'
resources :posts
resources :works
#用户登录与注销
resources :sessions
get 'login' => 'sessions#new', :as => 'login'
post 'login' => 'sessions#create', :as => 'post_login'
get 'logout' => 'sessions#destroy', :as => 'logout'
end
end
<file_sep>class WorksController < ApplicationController
def index
@works = Work.order('id DESC')
end
end
<file_sep>class Admin::PostsController < Admin::ApplicationController
#Blog列表
def index
@posts = Post.order('id DESC').page(params[:page]).per(params[:per] || 8)
end
#新建Blog
def new
@post = Post.new
end
def create
@post = Post.new post_params
#@post.user = current_user
if @post.save
redirect_to admin_posts_path
else
render :new
end
end
#编辑Blog
def edit
@post = Post.find params[:id]
end
def update
@post = Post.find params[:id]
if @post.update post_params
redirect_to admin_posts_path
else
render :edit
end
end
#删除BLog
def destroy
@post = Post.find params[:id]
@post.destroy
redirect_to admin_posts_url
end
private
def post_params
params.require(:post).permit(:title, :content, :tag_list, :desc)
end
end
<file_sep>#source 'https://rubygems.org'
source 'http://ruby.taobao.org'
gem 'rails', '4.0.4'
gem 'mysql2'
gem 'sass-rails', '~> 4.0.2'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
group :doc do
gem 'sdoc', require: false
end
gem 'bootstrap-sass'
gem 'font-awesome-rails'
# 富文本编辑器 for RAILS 4 production: rake kindeditor:assets
gem 'rails_kindeditor'
#分页
gem 'kaminari'
#gem "will_paginate" # rails 2.x 之前的老版本
# Markdown Support
#gem 'redcarpet', '~> 2.0'
# Code highlight
#gem 'coderay'
#安全密码
gem 'bcrypt-ruby'
group :development do
gem 'pry'
gem 'better_errors'
gem 'binding_of_caller'
end
#标签
gem 'acts-as-taggable-on'<file_sep>class Admin::HomeController < Admin::ApplicationController
#后台首页
def index
end
end
<file_sep>class User < ActiveRecord::Base
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
def password
@password
end
def password=(pass)
return unless pass
@password = pass
generate_password(pass)
end
def self.authentication(email, password)
user = User.find_by_email(email)
if user && Digest::SHA256.hexdigest(password + user.salt) == user.hashed_password
return user
end
false
end
private
def generate_password(pass)
salt = Array.new(10){rand(1024).to_s(36)}.join
self.salt, self.hashed_password =
salt, Digest::SHA256.hexdigest(pass + salt)
end
end<file_sep>This app will be a formal production.<file_sep>class Admin::WorksController < Admin::ApplicationController
def index
@works = Work.order('id DESC').page(params[:page]).per(params[:per] || 8)
end
#新建work
def new
@work = Work.new
end
def create
@work = Work.new work_params
#<EMAIL> = current_<EMAIL>
if @work.save
redirect_to admin_works_path
else
render :new
end
end
#编辑work
def edit
@work = Work.find params[:id]
end
def update
@work = Work.find params[:id]
if @work.update work_params
redirect_to admin_works_path
else
render :edit
end
end
#删除work
def destroy
@work = Work.find params[:id]
@work.destroy
redirect_to admin_works_url
end
private
def work_params
params.require(:work).permit(:title, :content, :fromdate, :todate, :desc)
end
end
<file_sep>class Post < ActiveRecord::Base
#validates_presence_of :title, :content
acts_as_taggable
validates :title, :presence => true, :length => { :minimum => 4 }
validates :content, :desc, :presence => true
end
| 34fb30abcaf42beb6864625b27c801c916e50c5a | [
"Markdown",
"Ruby"
]
| 9 | Ruby | ShayneChow/MyBlog | 3c70983a18f20933bca9cbde15f5576729cd9457 | 8aa2ff6f888d19075df0f051960e12797e9536b3 |
refs/heads/master | <file_sep>import { Module } from '@nestjs/common';
import { ControllerController } from './controller/controller.controller';
@Module({
controllers: [ControllerController]
})
export class UserModule {}
| c34c45b504c874e59bcbdf0d4fc6376065427376 | [
"TypeScript"
]
| 1 | TypeScript | sirojamuniro/Latihan-NestJS-REST-API-FoodApp | 41b5be23c27c5863725645c23cade6a0ad357f99 | 7658d139b94d0f9a0e7517663ebb74cac2c8f72b |
refs/heads/master | <file_sep>pkgname=mediathek
pkgver=9
pkgrel=1
pkgdesc="Offers access to the Mediathek of different tv stations (ARD, ZDF, Arte, etc.)"
arch=(x86_64)
url="http://zdfmediathk.sourceforge.net"
license=('custom')
depends=('java-runtime' 'mplayer' 'vlc' 'flvstreamer' )
options=(!strip !zipman)
source=(http://downloads.sourceforge.net/zdfmediathk/MediathekView_${pkgver}.zip
$pkgname
$pkgname.desktop)
md5sums=('bc0db2078982b04a9686ad19f0bc9dab'
'e52a61eabb6a5931dc2a1fe261bc7d95'
'adadcd222c4edd30c3241d67d0e09202')
package() {
install -d $pkgdir/{opt/$pkgname/{lib,bin},usr/{bin,share/{{doc,licenses}/$pkgname,applications,pixmaps}}}
install -m755 $pkgname $pkgdir/usr/bin/
install -m644 MediathekView.jar $pkgdir/opt/$pkgname/
install -m644 -t $pkgdir/opt/$pkgname/lib lib/*
install -m755 bin/flv.sh $pkgdir/opt/$pkgname/bin/
install -m644 $pkgname.desktop $pkgdir/usr/share/applications/
install -m644 Info/MediathekView.png $pkgdir/usr/share/pixmaps/
install -m644 Anleitung/Kurzanleitung.pdf $pkgdir/usr/share/doc/$pkgname/
install -m644 -t $pkgdir/usr/share/licenses/$pkgname Copyright/{*.*,_copyright}
}
<file_sep># mediathek
#
1) Install flvstreamer (also from KCP)
2) Install mediathekview
java-based downloader for several german broadcasting media centers (mediatheken), including ARD, ZDF, Arte, 3Sat, SWR, BR, MDR, NDR, WDR, HR, RBB, ORF, SF
| 455bc3ef24ab4d5a956219bece4444e37104ad30 | [
"Markdown",
"Shell"
]
| 2 | Shell | KaOS-Community-Packages/mediathek | 95988f365e1e012a7356234c823a8d8a4ff9ac75 | a5e55c8a389f7ce16a79fd7b945e3948bb751317 |
refs/heads/main | <file_sep>//
// DaumImageSearchModel.swift
// ImageSearchSwift
//
// Created by APPLE on 2020/10/10.
//
import Foundation
struct ImageData: Codable {
var meta: MetaData
var documents: [DocumentsData]
}
struct MetaData: Codable {
var total_count: Int
var pageable_count: Int
var is_end: Bool
}
struct DocumentsData: Codable {
var thumbnail_url: String
var image_url: String
var display_sitename: String
var datetime: String
}
<file_sep>//
// DetailImageVC.swift
// ImageSearchSwift
//
// Created by APPLE on 2020/10/10.
//
import UIKit
class DetailImageVC: UIViewController {
var index: Int!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var extraView: UIView!
@IBOutlet weak var lblSitename: UILabel!
@IBOutlet weak var lblDatetime: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
makeView()
}
func makeView() {
let urlValue = DataManager.sharedInstance.imageDatas.documents[index].image_url
let sitename = DataManager.sharedInstance.imageDatas.documents[index].display_sitename
var datetime = DataManager.sharedInstance.imageDatas.documents[index].datetime
if !imageView.loadImageFromURLString(urlValue) {
let alert = UIAlertController(title: nil, message: "이미지를 불러올 수 없습니다.", preferredStyle: .alert)
let action = UIAlertAction(title: "닫기", style: .default) { UIAlertAction -> Void in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(action)
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}
lblSitename.text = sitename
if datetime.count > 10 { // 필요한 정보만 보여주기 위해 10자리 이후는 자름
let range = datetime.index(datetime.startIndex, offsetBy: 10)..<datetime.endIndex
datetime.removeSubrange(range)
}
lblDatetime.text = datetime
}
}
<file_sep>//
// ExtensionString.swift
// ImageSearchSwift
//
// Created by APPLE on 2020/10/11.
//
import UIKit
extension String {
func isValidUrlString() -> Bool {
if let tempUrl = URL(string: self), UIApplication.shared.canOpenURL(tempUrl) {
return true
}
return false
}
}
<file_sep>//
// DataManager.swift
// ImageSearchSwift
//
// Created by APPLE on 2020/10/11.
//
import UIKit
class DataManager {
static let sharedInstance = DataManager()
var imageDatas: ImageData!
var imageCount = 0 // collectionview에서 보여지고 있는 이미지 수
var currentPage = 0 // 다음 검색 API request 페이지 번호, 1~50 사이의 값
}
<file_sep>//
// ViewController.swift
// ImageSearchSwift
//
// Created by APPLE on 2020/10/09.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
let shared = DataManager.sharedInstance
var workItem = DispatchWorkItem {}
var textForSearch = "" {
didSet {
workItem.cancel()
guard textForSearch != "" else {
collectionView.reloadData()
return
}
workItem = DispatchWorkItem {
self.requestImage(query: self.textForSearch, page: self.shared.currentPage)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: workItem)
}
}
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
searchBar.becomeFirstResponder()
print("searchBar Height: \(searchBar.frame.height)")
}
func requestImage(query: String, page: Int) {
let headers: HTTPHeaders = [
.authorization("KakaoAK 2962a9faf8ec4f7260cf341077c60ed2")
]
let parameters: [String: Any] = ["query": query, "sort": "accuracy", "page": page]
AF.request("https://dapi.kakao.com/v2/search/image", method: .get, parameters: parameters, headers: headers).responseJSON { response in
switch response.result {
case .success(let obj):
print("success")
do {
let jsonData = try JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted)
do {
let instance = try JSONDecoder().decode(ImageData.self, from: jsonData)
if self.shared.currentPage == 1 {
self.shared.imageDatas = instance
} else {
self.shared.imageDatas.documents.append(contentsOf: instance.documents)
}
switch self.shared.imageDatas.documents.count {
case 0:
self.showBasicAlert("'\(self.textForSearch)'에 대한 검색 결과가 없습니다.")
return
case 1...30:
self.shared.imageCount = self.shared.imageDatas.documents.count
case 31...80:
self.shared.imageCount = 30
default:
_ = ""
}
} catch {
print("getting instance has failed: \(error.localizedDescription)")
}
} catch {
print("making jsonData failed: \(error.localizedDescription)")
}
guard self.shared.currentPage == 1 else {
return
}
DispatchQueue.main.async {
self.collectionView.reloadData()
self.searchBar.resignFirstResponder()
}
case let .failure(error):
print(error.localizedDescription)
}
}
}
}
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { // 검색어 변경 시 동작
shared.imageCount = 0
shared.currentPage = 1
shared.imageDatas = nil
textForSearch = searchText
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return shared.imageCount // 셀 수 반환
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath) as! ImageCollectionViewCell
cell.imageView.loadImageUsingCacheWithURLString(stringImageUrl: shared.imageDatas.documents[indexPath.row].thumbnail_url, placeHolder: nil)
return cell // 셀 반환
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = view.frame.width / 3 // 3 X N 그리드뷰 구성
let height = width
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 셀 눌렀을 때 동작
let vc = self.storyboard?.instantiateViewController(identifier: "DetailImageVC") as! DetailImageVC
vc.index = indexPath.row
self.present(vc, animated: true, completion: nil)
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) { // scroll 끝까지 내렸을 때 동작
if collectionView.contentOffset.y >= (collectionView.contentSize.height - collectionView.frame.size.height) {
switch shared.imageDatas.documents.count - shared.imageCount {
case 31...:
shared.imageCount += 30
if !shared.imageDatas.meta.is_end { // data fetch
shared.currentPage += 1
requestImage(query: textForSearch, page: shared.currentPage)
}
default:
shared.imageCount = shared.imageDatas.documents.count
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
}
<file_sep>//
// ImageCollectionViewCell.swift
// ImageSearchSwift
//
// Created by APPLE on 2020/10/09.
//
import UIKit
class ImageCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override func prepareForReuse() {
self.imageView.image = nil
}
}
<file_sep>//
// ExtensionUIImageView.swift
// ImageSearchSwift
//
// Created by APPLE on 2020/10/09.
//
import UIKit
let imageCache = NSCache<NSString, UIImage>()
extension UIImageView{
func loadImageFromURLString(_ urlString: String) -> Bool {
guard let url = URL(string: urlString) else {
print("[error]: making url")
return false
}
do {
let data = try Data(contentsOf: url)
if let image = UIImage(data: data) {
let ratio = image.size.width / image.size.height
let newHeight = frame.width / ratio
frame.size.height = newHeight
self.image = image // UIImage(data: data)
return true
}
} catch {
print("[error] making image from url: \(error.localizedDescription)")
return false
}
return false
}
func setImageFromURl(stringImageUrl urlString: String?, fadeInAnimation fadeIn: Bool = true) {
if let urlStr = urlString {
if let url = NSURL(string: urlStr) {
DispatchQueue.global(qos: .default).async{
if let data = NSData(contentsOf: url as URL) {
DispatchQueue.main.async {
if fadeIn {
let image = UIImage(data: data as Data)
let crossFade: CABasicAnimation = CABasicAnimation(keyPath: "contents")
crossFade.duration = 1
crossFade.fromValue = self.image?.cgImage
crossFade.toValue = image?.cgImage
self.image = image
self.layer.add(crossFade, forKey: "animateContents")
} else {
self.image = UIImage(data: data as Data)
}
}
}
}
}
}
}
func loadImageUsingCacheWithURLString(stringImageUrl url: String?, placeHolder: UIImage?) {
if let tempUrl = url {
if let cachedImage = imageCache.object(forKey: NSString(string: tempUrl)) {
self.image = cachedImage
return
}
if let url = URL(string: tempUrl) {
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
//print("RESPONSE FROM API: \(response)")
if let err = error {
print("[error] loading images from url: \(err.localizedDescription))")
DispatchQueue.main.async {
self.image = placeHolder
}
return
}
DispatchQueue.main.async {
if let data = data {
if let downloadedImage = UIImage(data: data) {
imageCache.setObject(downloadedImage, forKey: NSString(string: tempUrl))
self.image = downloadedImage
}
}
}
}).resume()
}
}
}
}
| 90e59e9b746060d8c16691c0ae45e0dedb664553 | [
"Swift"
]
| 7 | Swift | HANBYEOL-YOO-developer/ImageSearchSwift | 8b37dba841b36378970cbc3de819dc57af5115e4 | f88d1b58dae1e3c4e4c9c9214daf36e4e875410a |
refs/heads/main | <file_sep>from typing import Tuple, List, Dict
from PIL import Image
from multiprocessing import Pool
import ctypes as cp
from os import getcwd, cpu_count
import os
# from os import environ
# environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame as pg
from itertools import chain
Pixel = Tuple[int, int]
PixelDiverList = List[Tuple[Pixel, int]]
Bound = Tuple[Pixel, Pixel]
View = Tuple[float, float]
class MandelbrotGenerator:
def __init__(self, size: int, max_iterations: int,
lowest_res: int, chunk_count: int):
self.size = size
self.max_iterations = max_iterations
self.lowest_resolution = lowest_res
self.chunk_count = chunk_count
self.bound_list = self.get_bound_list()
self.color_dict = self.load_colors('colors.txt')
def interactive_session(self) -> None:
screen = pg.display.set_mode((self.size, self.size))
render = True
view: View = 0.0, 0.0
zoom = 1 / 2
resolution = self.lowest_resolution
while True:
re_lo, re_hi = view[0] - 1 / zoom, view[0] + 1 / zoom
im_lo, im_hi = view[1] - 1 / zoom, view[1] + 1 / zoom
m_x, m_y = pg.mouse.get_pos()
sc_x = self.scale(re_lo, re_hi, m_x)
sc_y = self.scale(im_lo, im_hi, m_y)
zoom_coeff = 2
for event in pg.event.get():
if event.type == pg.QUIT:
exit(0)
elif event.type == pg.MOUSEBUTTONDOWN:
view = sc_x, sc_y
if event.button == 1: # left click
zoom *= zoom_coeff
elif event.button == 3: # right click
if zoom > 1:
zoom //= zoom_coeff
render = True
resolution = self.lowest_resolution
elif event.type == pg.KEYUP:
if event.key == ord('q'):
exit(0)
elif event.key == ord('r'):
view = (0.0, 0.0)
zoom = 0.5
resolution = self.lowest_resolution
render = True
os.system('clear||cls') # cls for windows compat.
print(sc_x, sc_y)
if render:
if resolution == 1:
render = False
arg_list = self.get_arg_list(view, zoom, resolution)
with Pool(cpu_count()) as pl:
it_maps = pl.starmap(self.build_mandelbrot_bounds, arg_list)
it_map = list(chain.from_iterable(it_maps)) # might be too slow
self.draw_image(it_map, screen, resolution)
pg.display.flip()
resolution //= 2
def get_bound_list(self) -> List[Bound]:
"""Divide the screen/view into <self.chunk_count> chunks for faster processing.
Return a list of bounds -> (<topleft_pixel>, <bottomright_pixel>)
"""
x_step = self.size // self.chunk_count
rest = self.size % self.chunk_count
x_pos = 0
bound_list: List[Bound] = []
for x in range(self.chunk_count):
x_step_end = x_pos + x_step
if x == self.chunk_count - 1:
x_step_end += rest
bound_list.append(((x_pos, 0), (x_step_end, self.size)))
x_pos += x_step
return bound_list
def get_arg_list(self, view: View, zoom: float, resolution: int) \
-> List[Tuple[Bound, View, float, int]]:
"""Pack arguments into a list of tuples to pass to build_mandelbrot_bounds()
"""
arg_list = []
for bound in self.bound_list:
arg_list.append((bound, view, zoom, resolution))
return arg_list
def get_color(self, its: int) -> Tuple[int, int, int]:
cols = [(0, 0, 102), (0, 0, 153), (0, 0, 204), (0, 0, 255)]
if its == self.max_iterations:
return 0, 0, 0
if its < 3:
return cols[0]
elif its < 7:
return cols[1]
elif its < 15:
return cols[2]
return cols[3]
def scale(self, start: float, end: float, position: int) -> float:
"""Scale pixel coord to real/imaginary part of a complex number
"""
coeff = abs(end - start) / self.size
return start + position * coeff
def get_iterations(self, c_lib: cp.cdll, scaled_x: float, scaled_y: float) -> int:
c_get_its = c_lib.c_get_iterations
c_get_its.restype = cp.c_int
iters = c_get_its(cp.c_longdouble(scaled_x),
cp.c_longdouble(scaled_y),
cp.c_int(self.max_iterations))
return iters
def build_mandelbrot_bounds(self, bounds: Tuple[Pixel, Pixel],
view: Tuple[float, float],
zoom: int,
resolution: int) \
-> PixelDiverList:
"""Associate each pixel with their respective number of iterations at
which they diverge.
https://en.wikipedia.org/wiki/Mandelbrot_set
"""
ul_bound, lr_bound = bounds
x0, y0 = ul_bound
x1, y1 = lr_bound
re_lo, re_hi = view[0] - 1 / zoom, view[0] + 1 / zoom
im_lo, im_hi = view[1] - 1 / zoom, view[1] + 1 / zoom
it_list = []
c_lib = cp.cdll.LoadLibrary(getcwd() + '/lib/mandelb.so') # TODO: rethink this
for x in range(x0, x1, resolution):
scaled_x = self.scale(re_lo, re_hi, x)
for y in range(y0, y1, resolution):
pixel = (x, y)
scaled_y = self.scale(im_lo, im_hi, y)
iters = self.get_iterations(c_lib, scaled_x, scaled_y)
it_list.append((pixel, iters))
return it_list
def build_image(self, it_map: PixelDiverList) -> Image:
"""Build an Image object from list of pixels and their respective
divergency points.
"""
img = Image.new('RGB', (self.size, self.size), 'white')
for pixel, iters in it_map:
img.putpixel(pixel, self.get_color(iters))
return img
def generate_ms_image(self, filepath: str) -> None:
view: View = 0.0, 0.0
zoom = 1 / 2
arg_list = self.get_arg_list(view, zoom, 1)
with Pool(self.chunk_count) as pl:
it_maps = pl.starmap(self.build_mandelbrot_bounds, arg_list)
im = list(chain.from_iterable(it_maps)) # might be too slow
img = self.build_image(im)
img.save(filepath)
def load_colors(self, filepath: str) -> Dict[int, Tuple[int, int, int]]:
color_dict = dict()
with open(filepath, 'r') as file:
for line in file.readlines():
line_split = line.split(',')
color_dict[int(line_split[0])] = (int(line_split[1]),
int(line_split[2]),
int(line_split[3].rstrip()))
color_dict[self.max_iterations] = (0, 0, 0)
return color_dict
def draw_image(self, it_map: PixelDiverList, screen, resolution) -> None:
for pixel, iters in it_map:
point = pg.Rect(pixel, (resolution, resolution))
pg.draw.rect(screen, self.color_dict[iters], point)
<file_sep># mandelb
App for generating and visualizing the Mandelbrot set.
## Usage
e.g.
`python3 mandelb.py -s 1000 out.png` to generate a png file with the mandelbrot set.
`python3 mandelb.py -s 800 -m 200 -i` for interactive mode.
See `python3 mandelb.py -h` for more.
<file_sep>#ifndef MANDELB_H
#define MANDELB_H
int c_get_iterations(long double scaled_x, long double scaled_y, int max_iters);
#endif<file_sep>#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <complex.h>
#include "mandelb.h"
int c_get_iterations(long double scaled_x, long double scaled_y, int max_iters)
{
int iters = 0;
long double complex c = scaled_x + scaled_y * I;
long double complex z = 0.0 + 0.0 * I;
//try no square root after
while ((creal(csqrt(z * z)) <= 2) && (iters < max_iters))
{
z = (z * z) + c;
++iters;
}
return iters;
}<file_sep>CFLAGS += -Wall -Wextra -std=c99
all: mandelb.so
lib/mandelb.o: mandelb.c
cc $(CFLAGS) -c mandelb.c -o lib/mandelb.o
mandelb.so: lib/mandelb.o
cc $(CFLAGS) -fPIC -shared -o lib/mandelb.so lib/mandelb.o
clean:
rm -f lib/mandelb.so lib/mandelb.o
<file_sep>#!/usr/bin/python3
from typing import Any, Dict
import cProfile
import argparse as ap
from os import remove, cpu_count
import mandelb_gen as mbg
def get_args() -> Dict[str, Any]:
parser = ap.ArgumentParser()
parser.add_argument('-s,', '--size', required=True,
type=int,
help='Size of the resulting image')
parser.add_argument('-o', '--output', required=False,
type=str,
help='Output filepath')
parser.add_argument('-b', '--benchmark', action='store_const',
const='benchmark',
help='cProfile output to stdin')
parser.add_argument('-m', '--max-iterations',
type=int,
default=1000,
help='Maximum mandelb. set iterations')
parser.add_argument('-i', '--interactive', action='store_const',
const='interactive')
parser.add_argument('-r', '--lowest-resolution',
type=int,
default=16)
cpu_c = cpu_count()
assert cpu_c is not None
cpu_c *= 4
parser.add_argument('-c', '--chunk-count',
help='How many ch. to work on concurrently. Def. 32',
type=int,
default=cpu_c)
parser.add_argument('filepath', nargs='?',
default='out.png',
type=str,
help='Output filepath')
args = vars(parser.parse_args())
return args
if __name__ == "__main__":
args = get_args()
if args['interactive'] is None:
if args['output'] is not None:
output: str = args['output']
else:
output = args['filepath']
max_iterations: int = args['max_iterations']
size: int = args['size']
chunk_count: int = args['chunk_count']
lowest_resolution: int = args['lowest_resolution']
mb_gen = mbg.MandelbrotGenerator(size, max_iterations, lowest_resolution,
chunk_count)
if args['benchmark'] is not None:
cProfile.run(fr'mb_gen.generateMSImage("{output}")')
remove(output)
exit(0)
if args['interactive'] is not None:
mb_gen.interactive_session()
else:
mb_gen.generate_ms_image(output)
| 500c2675c1eaaf475df2cf68efc34a20da9ae89d | [
"Markdown",
"C",
"Python",
"Makefile"
]
| 6 | Python | jedinym/mandelb | eebb3b004dc3086f8fd35753e802839b447989f7 | d42ca3738a4022d1a165ba718151d99eb7430bdc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.