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># Big_Number_Calculator
The problem is to build a simple calculator that can perform the following operations : +, -, *, /, sqrt(), pow() and log() on big numbers. The idea is to be able to manipulate very large numbers that are out of range for the usual numeric data types (int, float, long int, double etc.)
Implemented in C using Flex & Bison that computes algebraic, and other logarithmic expressions on very big numbers (represented as an array of single integers).
<file_sep>/*
Declarations for a calculator
*/
#include<stdbool.h>
void yyerror(char* s);
/*nodes in AST*/
int MAX_INT;
struct bigint
{
int flag; // flag for the sign 1 for non-negative, and -1 for negative
int x[100]; // stores the integer part
int frac[100]; //stores the decimal part
int length; // length of integer part
int lengthDec; // length of fractional part
int max_int; //denotes the maximum length of the bigint(both integer and fractional part)
};
struct ast
{
int nodeType;
struct ast* l;
struct ast* r;
};
struct numval {
int nodeType; /* type K for constant */
struct bigint number;
};
/* build an AST */
struct ast *newast(int nodetype, struct ast *l, struct ast *r);
struct ast *newnum(struct bigint d);
/* evaluate an AST */
struct bigint eval(struct ast *);
struct bigint getSum(struct bigint a,struct bigint b);
struct bigint getSubtraction(struct bigint c,struct bigint d);
struct bigint removeZeros(struct bigint c);
bool equal(struct bigint a, struct bigint b);
bool Greater(struct bigint a, struct bigint b);
bool isGreater(struct bigint a, struct bigint b);
struct bigint getMultiplication(struct bigint c, struct bigint d);
struct bigint getDivision(struct bigint c,struct bigint d);
struct bigint simple_remainder(struct bigint c,struct bigint d,int flag);
int simple_division(struct bigint c,struct bigint d,int flag);
struct bigint setRemainder(struct bigint temp,int factorPoint);
struct bigint getSqrt(struct bigint a);
struct bigint getLog(struct bigint a);
struct bigint get_simple_log(struct bigint x);
struct bigint adjust_with_zeros(struct bigint a);
struct bigint shift_with_zeros(struct bigint c,int number_of_zeros,int flag);
struct bigint shift_with_zeros_and_decimals(struct bigint c,int number_of_zeros,int flag);
struct bigint roundOff(struct bigint a);
struct bigint getPow(struct bigint a, struct bigint b);
/* delete and free an AST */
void treeFree(struct ast *a);
void arrayPrint(struct bigint a);
| a7083a88f4b9c3eabcc67f78c1ee35f585829aa3 | [
"Markdown",
"C"
] | 2 | Markdown | ankursharma-iitd/Big_Number_Calculator | 35ab389656ddfa95948c1851adb5a086dbda728c | e13a46e2ea0eb2c30b25ddb5bff20ff6ff4faaa0 |
refs/heads/master | <file_sep>
#define _CRT_SECURE_NO_WARNINGS
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstdio>
#include <Math.h>
#include <windows.h>
#include <shellapi.h>
#include <ctime>
#include <vector>
#include "map.h"
using namespace sf;
Clock mytime2;
int energy, deep, weight, respect, scalp, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13;
int flag;
String dlgtext, dlgtext2;
time_t t;
int questResult;
int v(int& year, int& mes, int& day, int& ch)
{
int mm[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
if (!(year % 4))
{
mm[1] = 29;
year = year * 366;
}
else year = year * 365;
bool chflag = true;
if (day>mm[mes - 1]) {
std::cout << "Дата неверна!" << std::endl;
chflag = false;
}
if (mes <= 0 || mes>12) {
std::cout << "Месяц неверен!" << std::endl;
chflag = false;
}
if (year<0) {
std::cout << "Год неверен!" << std::endl;
chflag = false;
}
if (chflag) {
int i = 0;
int sm = 0;
while (i < mes - 1)
{
sm = sm + mm[i];
i++;
}
int res = ((year + sm + day) * 24) + ch;
return res;
}
return -1;
}
int load()
{
std::ifstream f("num.txt");
f >> energy;
f >> deep;
f >> weight;
f >> respect;
f >> scalp;
return 0;
}
int save()
{
remove("num.txt");
std::ofstream f;
f.open("num.txt");
f << energy << " " << deep << " " << weight << " " << respect << " " << scalp << " " << std::endl;
f.close();
return 0;
}
int random(int min, int max) //range : [min, max)
{
return min + rand() % (max - min);
}
String toString(Int32 integer)
{
char numstr[10]; // enough to hold all numbers up to 32-bits
sprintf_s(numstr, "%i", integer);
return numstr;
}
int save_t()
{
time(&t);
//v(int& year, int& mes, int& day, int& ch)
int month = localtime(&t)->tm_mon;
int hour = localtime(&t)->tm_hour;
int day = localtime(&t)->tm_mday;
int ye = localtime(&t)->tm_year;
int sum = v(ye, month, day, hour);
remove("date.txt");
std::ofstream f;
f.open("date.txt");
f << sum << std::endl;
f.close();
return 0;
}
int update_me()
{
time(&t);
int sum1, sum2, sum3;
std::ifstream f("date.txt");
f >> sum1;
int month1 = localtime(&t)->tm_mon;
int hour1 = localtime(&t)->tm_hour;
int day1 = localtime(&t)->tm_mday;
int ye1 = localtime(&t)->tm_year;
sum2 = v(ye1, month1, day1, hour1);
sum3 = sum2 - sum1; // сколько прошло часов
std::cout << " " << sum3;
if (sum3 > 0) // если прошло больше 0 часов
{
deep = deep - sum3 * 5;
weight = weight - sum3 * 10;
energy = 100;
dlgtext = L"Вы долго не заходили в игру\nПоказатели изменились!\nВес: -" + toString(sum3 * 10) + L"\nПещера: -" + toString(sum3 * 5) + L"\nЭнергия восполнилась до 100";
}
save_t();
save();
return 0;
}
void menu(RenderWindow & window) {
Texture menuBackground;
Texture buttonStartGame;
Texture buttonContinueGame;
Texture orcRun;
menuBackground.loadFromFile("images/menuBack.jpg");
buttonStartGame.loadFromFile("images/buttonNewGame.png");
buttonContinueGame.loadFromFile("images/buttonContinueGame.png");
orcRun.loadFromFile("images/orcRun.png");
Sprite menu1(buttonStartGame);
Sprite menu2(buttonContinueGame);
Sprite menuBg(menuBackground);
Sprite orcRunSprite(orcRun);
SoundBuffer surpriseBuffer;//создаём буфер для звука
surpriseBuffer.loadFromFile("sound/SURPRISE_MOTHERFUCKER.ogg");//загружаем в него звук
Sound surpriseSound(surpriseBuffer);//создаем звук и загружаем в него звук из буфера
SoundBuffer clickBuffer;//создаём буфер для звука
clickBuffer.loadFromFile("sound/click.ogg");//загружаем в него звук
Sound clickSound(clickBuffer);//создаем звук и загружаем в него звук из буфера
Clock mytime;
float currentFrame = 0;
bool isMenu = 1;
int menuNum = 0;
menu1.setTextureRect(IntRect(0, 0, 392, 100));
menu1.setPosition(450, 500);
menu2.setTextureRect(IntRect(0, 0, 392, 100));
menu2.setPosition(450, 620);
menuBg.setPosition(0, 0);
orcRunSprite.setTextureRect(IntRect(0, 0, 437, 310));//437(*7) *310 px
orcRunSprite.setPosition(20, 480);
//remove("images/num.txt");
//////////////////////////////МЕНЮ///////////////////
while (isMenu)
{
//X13 = GetPrivateProfileInt("Section", "Key", 13, "num.ini");
float time = mytime.getElapsedTime().asMicroseconds();
mytime.restart();
time = time / 800;
Vector2i pixelPos = Mouse::getPosition(window);
Vector2f pos = window.mapPixelToCoords(pixelPos);//переводим их в игровые (уходим от коорд окна)
//std::cout << pixelPos.x << "\n";//смотрим на координату Х позиции курсора в консоли (она не будет больше ширины окна)
//std::cout << pos.x << "\n";
//std::cout << pos.x << " | " << pos.y << "\n";
menuNum = 0;
window.clear();
if (orcRunSprite.getGlobalBounds().contains(pos.x, pos.y))//и при этом координата курсора попадает в спрайт
{
currentFrame += 0.01*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (currentFrame > 7) currentFrame -= 7; //если пришли к третьему кадру - откидываемся назад.
orcRunSprite.setTextureRect(IntRect(437 * int(currentFrame), 0, 437, 310));
}
if (menu1.getGlobalBounds().contains(pos.x, pos.y))//и при этом координата курсора попадает в спрайт
{
menu1.setTextureRect(IntRect(392, 0, 784, 100));
menuNum = 1;
}
else {
menu1.setTextureRect(IntRect(0, 0, 392, 100));
}
if (menu2.getGlobalBounds().contains(pos.x, pos.y))//и при этом координата курсора попадает в спрайт
{
menu2.setTextureRect(IntRect(392, 0, 784, 100));
menuNum = 2;
}
else {
menu2.setTextureRect(IntRect(0, 0, 392, 100));
}
if (Mouse::isButtonPressed(Mouse::Left))
{
if (menuNum == 1) {
isMenu = false; energy = 100; weight = random(35, 45); deep = random(27, 33); scalp = 0; respect = random(20, 30);
save();
}//NEW GAME
if (menuNum == 2) {
isMenu = false; load(); flag = 229; //window.draw(menuBg); window.display(); while (!Keyboard::isKeyPressed(Keyboard::Escape));
} // CONTINUE
if (orcRunSprite.getGlobalBounds().contains(pos.x, pos.y)) {
surpriseSound.play();
}
}
if (Mouse::isButtonPressed(Mouse::Left))
{
if (menu1.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play();}
if (menu2.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
}
window.draw(menuBg);
window.draw(menu1);
window.draw(menu2);
window.draw(orcRunSprite);
window.display();
}
}
int finalBattle(RenderWindow & window, int h) {
srand(time(0));
Texture arenaBackTexture;
Texture arenaHeadsTexture;
Texture heroBarTexture;
Texture enemyBarTexture;
Texture buttonAttackTexture;
Texture buttonDefTexture;
Texture buttonHFightTexture;
Texture shamanTexture;
Texture shamanDeadTexture;
Texture shamanWinexture;
Texture orcArenaTexture;
Texture orcWinTexture;
Texture orcDeadTexture;
Texture looserBackTexture;
Texture winnreBackTexture;
arenaBackTexture.loadFromFile("images/arenaBack.jpg");
arenaHeadsTexture.loadFromFile("images/arenaHeads.png");
heroBarTexture.loadFromFile("images/heroBar.png");// 323*76
enemyBarTexture.loadFromFile("images/enemyBar.png");// 323*76
buttonAttackTexture.loadFromFile("images/buttonAttack.png"); //82(*2) *83
buttonDefTexture.loadFromFile("images/buttonDef.png"); //82(*2) *83
buttonHFightTexture.loadFromFile("images/buttonFight.png"); //82(*2) *83
shamanTexture.loadFromFile("images/shaman.png"); //532(*10) *350
shamanDeadTexture.loadFromFile("images/shamanDead.png"); //430(*10) *350
shamanWinexture.loadFromFile("images/shamanWin.png");//514(*11) *400
orcArenaTexture.loadFromFile("images/orcArena.png");//307(*7) *200
orcWinTexture.loadFromFile("images/orcWin.png");//306(*7) *320
orcDeadTexture.loadFromFile("images/orcDead.png");//414(*7) *200
looserBackTexture.loadFromFile("images/looser.jpg");
winnreBackTexture.loadFromFile("images/victory.jpg");
Sprite arenaBackSprite(arenaBackTexture);
Sprite arenaHeadsSprite(arenaHeadsTexture);
Sprite heroBarSprite(heroBarTexture);
Sprite enemyBarSprite(enemyBarTexture);
Sprite buttonAttackkSprite1, buttonAttackkSprite2, buttonAttackkSprite3;
Sprite buttonDefSprite1, buttonDefSprite2, buttonDefSprite3;
Sprite buttonHFightSprite;
Sprite shamanSprite(shamanTexture);
Sprite shamanDeadSprite(shamanDeadTexture);
Sprite shamanWinSprite(shamanWinexture);
Sprite orcArenaSprite(orcArenaTexture);
Sprite orcWinSprite(orcWinTexture);
Sprite orcDeadSprite(orcDeadTexture);
Sprite looserBackSprite(looserBackTexture);
Sprite winnerBackSprite(winnreBackTexture);
SoundBuffer clickBuffer;//создаём буфер для звука
clickBuffer.loadFromFile("sound/click.ogg");//загружаем в него звук
Sound clickSound(clickBuffer);//создаем звук и загружаем в него звук из буфера
Music musicMortal;//создаем объект музыки
musicMortal.openFromFile("sound/mortal.ogg");
musicMortal.play();//воспроизводим музыку
Music musicChamp;//создаем объект музыки
musicChamp.openFromFile("sound/champ.ogg");
bool attack = false, def = false;
float heroHealth = h;
float enemyHealth = 1500;
float heroPower = heroHealth / 15;
float enemyPower = enemyHealth / 25;
float heroHit = 0;
float heroDef = 0;
float enemyHit = 0;
float enemyDef = 0;
Clock mytime;
double currentFrame = 0;
double currentFrame2 = 0;
Font font;//шрифт
font.loadFromFile("font/Ycfhzibd.ttf");//передаем нашему шрифту файл шрифта
Text text("", font, 30);//создаем объект текст. закидываем в объект текст строку, шрифт, размер шрифта(в пикселях);//сам объект текст (не строка)
text.setFillColor(Color::White);//покрасили текст в красный. если убрать эту строку, то по умолчанию он белый
//text.setStyle(sf::Text::Bold | sf::Text::Underlined);//жирный и подчеркнутый текст. по умолчанию он "худой":)) и не подчеркнутый
text.setString("");//задает строку тексту
text.setPosition(170, 55);//задаем позицию текста
Text text2("", font, 30);//создаем объект текст. закидываем в объект текст строку, шрифт, размер шрифта(в пикселях);//сам объект текст (не строка)
text2.setFillColor(Color::White);//покрасили текст в красный. если убрать эту строку, то по умолчанию он белый
text2.setString("");//задает строку тексту
text2.setPosition(1050, 55);//задаем позицию текста
std::ostringstream playerScoreString; // объявили переменную
playerScoreString << heroHealth; //занесли в нее число очков, то есть формируем строку
text.setString("" + playerScoreString.str());//задаем строку тексту и вызываем сформированную выше строку методом .str()
std::ostringstream playerScoreString2; // объявили переменную
playerScoreString2 << enemyHealth; //занесли в нее число очков, то есть формируем строку
text2.setString("" + playerScoreString2.str());//задаем строку тексту и вызываем сформированную выше строку методом .str()
////////////////// Health Bars
heroBarSprite.setTextureRect(IntRect(0, 0, 323 * 1, 76));
heroBarSprite.setPosition(133, 39);
enemyBarSprite.setTextureRect(IntRect(0 + 0, 0, 323, 76));
enemyBarSprite.setPosition(825 + 0, 39);
//////////////////////// Button Attack
buttonAttackkSprite1.setTexture(buttonAttackTexture);
buttonAttackkSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite1.setPosition(750, 320);
buttonAttackkSprite2.setTexture(buttonAttackTexture);
buttonAttackkSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite2.setPosition(750, 420);
buttonAttackkSprite3.setTexture(buttonAttackTexture);
buttonAttackkSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite3.setPosition(750, 520);
//////////////////// Button Def
buttonDefSprite1.setTexture(buttonDefTexture);
buttonDefSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite1.setPosition(450, 320);
buttonDefSprite2.setTexture(buttonDefTexture);
buttonDefSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite2.setPosition(450, 420);
buttonDefSprite3.setTexture(buttonDefTexture);
buttonDefSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite3.setPosition(450, 520);
//////////////////////// Button Fight
buttonHFightSprite.setTexture(buttonHFightTexture);
buttonHFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonHFightSprite.setPosition(600, 420);
shamanSprite.setTextureRect(IntRect(0 * 532, 0, 532, 350));
shamanSprite.setPosition(650, 300);
shamanDeadSprite.setTextureRect(IntRect(0 * 430, 0, 430, 350));
shamanDeadSprite.setPosition(1725, 350);
shamanWinSprite.setTextureRect(IntRect(0 * 514, 0, 514, 400));
shamanWinSprite.setPosition(1725, 350);
orcWinSprite.setPosition(2100, 420);
orcDeadSprite.setPosition(2100, 420);
looserBackSprite.setPosition(2100, 420);
winnerBackSprite.setPosition(2100, 420);
while (window.isOpen())
{
float time = mytime.getElapsedTime().asMicroseconds();
mytime.restart();
time = time / 800;
if (enemyHealth > 0 && heroHealth > 0) {
currentFrame += 0.008*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (currentFrame > 10) currentFrame -= 10; //если пришли к 10 кадру - откидываемся назад.
shamanSprite.setTextureRect(IntRect(532 * int(currentFrame), 0, 532, 350));
orcArenaSprite.setPosition(100, 420);
currentFrame2 += 0.008*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (currentFrame2 > 7) currentFrame2 -= 7; //если пришли к 10 кадру - откидываемся назад.
orcArenaSprite.setTextureRect(IntRect(307 * int(currentFrame2), 0, 307, 200));
}
else if(enemyHealth<=0 && heroHealth > 0)
{
shamanSprite.setPosition(1650, 1300);
shamanDeadSprite.setPosition(725, 350);
currentFrame += 0.008*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (currentFrame > 10) currentFrame = 9;
shamanDeadSprite.setTextureRect(IntRect(430 * int(currentFrame), 0, 430, 350));
orcArenaSprite.setPosition(2100, 420);
orcWinSprite.setPosition(120, 320);
currentFrame2 += 0.008*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (currentFrame2 > 7) currentFrame2 = 6;
orcWinSprite.setTextureRect(IntRect(306 * int(currentFrame2), 0, 306, 320));
winnerBackSprite.setPosition(0, 0);
}
else if(enemyHealth > 0 && heroHealth <= 0)
{
musicMortal.stop();
shamanSprite.setPosition(1650, 1300);
shamanWinSprite.setPosition(725, 250);
currentFrame += 0.01*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (currentFrame > 11) currentFrame = 10; //если пришли к 10 кадру - откидываемся назад.
shamanWinSprite.setTextureRect(IntRect(514 * int(currentFrame), 0, 514, 400));
orcArenaSprite.setPosition(1650, 1300);
orcDeadSprite.setPosition(100, 450);
currentFrame2 += 0.01*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (currentFrame2 > 7) currentFrame2 = 6; //если пришли к 10 кадру - откидываемся назад.
orcDeadSprite.setTextureRect(IntRect(414 * int(currentFrame2), 0, 414, 200));
looserBackSprite.setPosition(0, 0);
}
Vector2i pixelPos = Mouse::getPosition(window);
Vector2f pos = window.mapPixelToCoords(pixelPos);//переводим их в игровые (уходим от коорд окна)
//std::cout << pixelPos.x << "\n";//смотрим на координату Х позиции курсора в консоли (она не будет больше ширины окна)
//std::cout << pos.x << "\n";
sf::Event startPage;
while (window.pollEvent(startPage))
{
if (startPage.type == sf::Event::Closed)
window.close();
if (startPage.type == startPage.MouseButtonReleased && startPage.mouseButton.button == Mouse::Left)
{
if (looserBackSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
return 0;
}
}
if (startPage.type == startPage.MouseButtonReleased && startPage.mouseButton.button == Mouse::Left)
{
if (winnerBackSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
return 0;
}
}
if (startPage.type == startPage.MouseButtonReleased && startPage.mouseButton.button == Mouse::Left)
{
if (buttonAttackkSprite1.getGlobalBounds().contains(pos.x, pos.y)) clickSound.play();
if (buttonAttackkSprite2.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonAttackkSprite3.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonDefSprite1.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonDefSprite2.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonDefSprite3.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonHFightSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
}
if (attack == true && def == true) {
if (startPage.type == startPage.MouseButtonReleased && startPage.mouseButton.button == Mouse::Left) {
if (buttonHFightSprite.getGlobalBounds().contains(pos.x, pos.y)) {//координата курсора попадает в спрайт
buttonHFightSprite.setTextureRect(IntRect(1 * 82, 0, 82, 83));
buttonAttackkSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
enemyHit = rand() % 3 + 1;
enemyDef = rand() % 3 + 1;
float t1;
float t2;
int t3, t4;
if (heroHit != enemyDef)
{
enemyHealth = enemyHealth - heroPower;
std::ostringstream playerScoreString2; // объявили переменную
t3 = enemyHealth;
playerScoreString2 << t3; //занесли в нее число очков, то есть формируем строку
text2.setString("" + playerScoreString2.str());//задаем строку тексту и вызываем сформированную выше строку методом .str()
t1 = enemyHealth / 1500;
enemyBarSprite.setTextureRect(IntRect(0 + ((1 - t1) * 323), 0, 323, 76));
enemyBarSprite.setPosition(825 + ((1 - t1) * 323), 39);
}
if (heroDef != enemyHit)
{
heroHealth = heroHealth - enemyPower;
std::ostringstream playerScoreString; // объявили переменную
t4 = heroHealth;
playerScoreString << t4; //занесли в нее число очков, то есть формируем строку
text.setString("" + playerScoreString.str());//задаем строку тексту и вызываем сформированную выше строку методом .str()
t2 = heroHealth / h;
if (t2 >= -0.1) {
heroBarSprite.setTextureRect(IntRect(0, 0, 323 * t2, 76));
heroBarSprite.setPosition(133, 39);
}
}
}
}
}
}
if (Mouse::isButtonPressed(Mouse::Left))
{
/////////////////////////////////////
if (buttonAttackkSprite1.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonAttackkSprite1.setTextureRect(IntRect(1 * 82, 0, 82, 83)); attack = true; heroHit = 1;
buttonAttackkSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonHFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
if (buttonAttackkSprite2.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonAttackkSprite2.setTextureRect(IntRect(1 * 82, 0, 82, 83)); attack = true; heroHit = 2;
buttonAttackkSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonHFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
if (buttonAttackkSprite3.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonAttackkSprite3.setTextureRect(IntRect(1 * 82, 0, 82, 83)); attack = true; heroHit = 3;
buttonAttackkSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonHFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
////////////////////////////////
if (buttonDefSprite1.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonDefSprite1.setTextureRect(IntRect(1 * 82, 0, 82, 83)); def = true; heroDef = 1;
buttonDefSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonHFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
if (buttonDefSprite2.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonDefSprite2.setTextureRect(IntRect(1 * 82, 0, 82, 83)); def = true; heroDef = 2;
buttonDefSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonHFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
if (buttonDefSprite3.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonDefSprite3.setTextureRect(IntRect(1 * 82, 0, 82, 83)); def = true; heroDef = 3;
buttonDefSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonHFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
}
window.clear();
window.draw(arenaBackSprite);
window.draw(heroBarSprite);
window.draw(enemyBarSprite);
window.draw(arenaHeadsSprite);
window.draw(shamanSprite);
window.draw(shamanDeadSprite);
window.draw(shamanWinSprite);
window.draw(orcArenaSprite);
window.draw(orcWinSprite);
window.draw(orcDeadSprite);
window.draw(buttonAttackkSprite1);
window.draw(buttonAttackkSprite2);
window.draw(buttonAttackkSprite3);
window.draw(buttonDefSprite1);
window.draw(buttonDefSprite2);
window.draw(buttonDefSprite3);
window.draw(buttonHFightSprite);
window.draw(text);//рисую этот текст
window.draw(text2);//рисую этот текст
window.draw(looserBackSprite);
window.draw(winnerBackSprite);
window.display();
}
return 0;
}
int questBattle(RenderWindow & window, int heroHP, char difficultyQuest) {
//difficultyQuest 'e' or 'h',easy and hard
srand(time(0));
Texture arenaEasyBackTexture;
Texture arenaEasyHeadsTexture;
Texture arenaHardBackTexture;
Texture arenaHardHeadsTexture;
Texture heroBarTexture;
Texture enemyBarTexture;
Texture buttonAttackTexture;
Texture buttonDefTexture;
Texture buttonFightTexture;
Texture elfEasyTexture;
Texture elfHardTexture;
Texture orcArenaTexture;
arenaEasyBackTexture.loadFromFile("images/questImages/easyElfBack.jpg");
arenaEasyHeadsTexture.loadFromFile("images/questImages/arenaEasyElfHeads.png");
arenaHardBackTexture.loadFromFile("images/questImages/hardElfBack.jpg");
arenaHardHeadsTexture.loadFromFile("images/questImages/arenaHardElfHeads.png");
heroBarTexture.loadFromFile("images/questImages/heroBar.png");// 323*76
enemyBarTexture.loadFromFile("images/questImages/enemyBar.png");// 323*76
buttonAttackTexture.loadFromFile("images/questImages/buttonAttack.png"); //82(*2) *83
buttonDefTexture.loadFromFile("images/questImages/buttonDef.png"); //82(*2) *83
buttonFightTexture.loadFromFile("images/questImages/buttonFight.png"); //82(*2) *83
elfEasyTexture.loadFromFile("images/questImages/elfEasy.png"); //396(*5) *200
elfHardTexture.loadFromFile("images/questImages/elfHard.png"); //343(*5) *200
orcArenaTexture.loadFromFile("images/questImages/orcArena.png");//307(*7) *200
Sprite arenaEasyBackSprite(arenaEasyBackTexture);
Sprite arenaEasyHeadsSprite(arenaEasyHeadsTexture);
Sprite arenaHardBackSprite(arenaHardBackTexture);
Sprite arenaHardHeadsSprite(arenaHardHeadsTexture);
Sprite heroBarSprite(heroBarTexture);
Sprite enemyBarSprite(enemyBarTexture);
Sprite buttonAttackkSprite1, buttonAttackkSprite2, buttonAttackkSprite3;
Sprite buttonDefSprite1, buttonDefSprite2, buttonDefSprite3;
Sprite buttonFightSprite;
Sprite elfEasySprite(elfEasyTexture);
Sprite elfHardSprite(elfHardTexture);
Sprite orcArenaSprite(orcArenaTexture);
SoundBuffer clickBuffer;//создаём буфер для звука
clickBuffer.loadFromFile("sound/click.ogg");//загружаем в него звук
Sound clickSound(clickBuffer);//создаем звук и загружаем в него звук из буфера
bool attack = false, def = false;
float heroHealth = heroHP;
float enemyHealth;
if (difficultyQuest == 'e')
{
enemyHealth = 150;
}
else if (difficultyQuest = 'h')
{
enemyHealth = 200;
}
float heroPower = heroHealth / 15;
float enemyPower = enemyHealth / 25;
float heroHit = 0;
float heroDef = 0;
float enemyHit = 0;
float enemyDef = 0;
Clock mytime;
double currentFrame = 0;
double currentFrame2 = 0;
Font font;//шрифт
font.loadFromFile("font/Ycfhzibd.ttf");//передаем нашему шрифту файл шрифта
Text text("", font, 30);//создаем объект текст. закидываем в объект текст строку, шрифт, размер шрифта(в пикселях);//сам объект текст (не строка)
text.setFillColor(Color::White);//покрасили текст в красный. если убрать эту строку, то по умолчанию он белый
//text.setStyle(sf::Text::Bold | sf::Text::Underlined);//жирный и подчеркнутый текст. по умолчанию он "худой":)) и не подчеркнутый
text.setString("");//задает строку тексту
text.setPosition(170, 55);//задаем позицию текста
Text text2("", font, 30);//создаем объект текст. закидываем в объект текст строку, шрифт, размер шрифта(в пикселях);//сам объект текст (не строка)
text2.setFillColor(Color::White);//покрасили текст в красный. если убрать эту строку, то по умолчанию он белый
text2.setString("");//задает строку тексту
text2.setPosition(1050, 55);//задаем позицию текста
std::ostringstream playerScoreString; // объявили переменную
playerScoreString << heroHealth; //занесли в нее число очков, то есть формируем строку
text.setString("" + playerScoreString.str());//задаем строку тексту и вызываем сформированную выше строку методом .str()
std::ostringstream playerScoreString2; // объявили переменную
playerScoreString2 << enemyHealth; //занесли в нее число очков, то есть формируем строку
text2.setString("" + playerScoreString2.str());//задаем строку тексту и вызываем сформированную выше строку методом .str()
////////////////// Health Bars
heroBarSprite.setTextureRect(IntRect(0, 0, 323 * 1, 76));
heroBarSprite.setPosition(133, 39);
enemyBarSprite.setTextureRect(IntRect(0 + 0, 0, 323, 76));
enemyBarSprite.setPosition(825 + 0, 39);
//////////////////////// Button Attack
buttonAttackkSprite1.setTexture(buttonAttackTexture);
buttonAttackkSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite1.setPosition(750, 320);
buttonAttackkSprite2.setTexture(buttonAttackTexture);
buttonAttackkSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite2.setPosition(750, 420);
buttonAttackkSprite3.setTexture(buttonAttackTexture);
buttonAttackkSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite3.setPosition(750, 520);
//////////////////// Button Def
buttonDefSprite1.setTexture(buttonDefTexture);
buttonDefSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite1.setPosition(450, 320);
buttonDefSprite2.setTexture(buttonDefTexture);
buttonDefSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite2.setPosition(450, 420);
buttonDefSprite3.setTexture(buttonDefTexture);
buttonDefSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite3.setPosition(450, 520);
//////////////////////// Button Fight
buttonFightSprite.setTexture(buttonFightTexture);
buttonFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonFightSprite.setPosition(600, 420);
elfEasySprite.setTextureRect(IntRect(0 * 396, 0, 396, 200));
elfEasySprite.setPosition(700, 420);
elfHardSprite.setTextureRect(IntRect(0 * 343, 0, 343, 200));
elfHardSprite.setPosition(750, 420);
while (window.isOpen())
{
float time = mytime.getElapsedTime().asMicroseconds();
mytime.restart();
time = time / 800;
if (enemyHealth > 0 && heroHealth > 0) {
if (difficultyQuest == 'e')
{
currentFrame += 0.008*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (currentFrame > 5) currentFrame -= 5; //если пришли к 10 кадру - откидываемся назад.
elfEasySprite.setTextureRect(IntRect(396 * int(currentFrame), 0, 396, 200));
}
else if (difficultyQuest = 'h')
{
currentFrame += 0.008*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (currentFrame > 5) currentFrame -= 5; //если пришли к 10 кадру - откидываемся назад.
elfHardSprite.setTextureRect(IntRect(343 * int(currentFrame), 0, 343, 200));
}
orcArenaSprite.setPosition(100, 420);
currentFrame2 += 0.008*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (currentFrame2 > 7) currentFrame2 -= 7; //если пришли к 10 кадру - откидываемся назад.
orcArenaSprite.setTextureRect(IntRect(307 * int(currentFrame2), 0, 307, 200));
}
else if (enemyHealth <= 0 && heroHealth > 0)
{
return heroHealth;
}
else if (enemyHealth > 0 && heroHealth <= 0)
{
return heroHealth;
}
Vector2i pixelPos = Mouse::getPosition(window);
Vector2f pos = window.mapPixelToCoords(pixelPos);//переводим их в игровые (уходим от коорд окна)
//std::cout << pixelPos.x << "\n";//смотрим на координату Х позиции курсора в консоли (она не будет больше ширины окна)
//std::cout << pos.x << "\n";
sf::Event startPage;
while (window.pollEvent(startPage))
{
if (startPage.type == sf::Event::Closed)
window.close();
if (startPage.type == startPage.MouseButtonReleased && startPage.mouseButton.button == Mouse::Left)
{
if (buttonAttackkSprite1.getGlobalBounds().contains(pos.x, pos.y)) clickSound.play();
if (buttonAttackkSprite2.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonAttackkSprite3.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonDefSprite1.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonDefSprite2.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonDefSprite3.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonFightSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
}
if (attack == true && def == true) {
if (startPage.type == startPage.MouseButtonReleased && startPage.mouseButton.button == Mouse::Left) {
if (buttonFightSprite.getGlobalBounds().contains(pos.x, pos.y)) {//координата курсора попадает в спрайт
buttonFightSprite.setTextureRect(IntRect(1 * 82, 0, 82, 83));
buttonAttackkSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
enemyHit = rand() % 3 + 1;
enemyDef = rand() % 3 + 1;
float t1;
float t2;
int t3, t4;
if (heroHit != enemyDef)
{
enemyHealth = enemyHealth - heroPower;
std::ostringstream playerScoreString2; // объявили переменную
t3 = enemyHealth;
playerScoreString2 << t3; //занесли в нее число очков, то есть формируем строку
text2.setString("" + playerScoreString2.str());//задаем строку тексту и вызываем сформированную выше строку методом .str()
if (difficultyQuest == 'e') {
t1 = enemyHealth / 150;
}
else if (difficultyQuest == 'h') {
t1 = enemyHealth / 200;
}
enemyBarSprite.setTextureRect(IntRect(0 + ((1 - t1) * 323), 0, 323, 76));
enemyBarSprite.setPosition(825 + ((1 - t1) * 323), 39);
}
if (heroDef != enemyHit)
{
heroHealth = heroHealth - enemyPower;
std::ostringstream playerScoreString; // объявили переменную
t4 = heroHealth;
playerScoreString << t4; //занесли в нее число очков, то есть формируем строку
text.setString("" + playerScoreString.str());//задаем строку тексту и вызываем сформированную выше строку методом .str()
t2 = heroHealth / heroHP;
if (t2 >= -0.1) {
heroBarSprite.setTextureRect(IntRect(0, 0, 323 * t2, 76));
heroBarSprite.setPosition(133, 39);
}
}
}
}
}
}
if (Mouse::isButtonPressed(Mouse::Left))
{
/////////////////////////////
if (buttonAttackkSprite1.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonAttackkSprite1.setTextureRect(IntRect(1 * 82, 0, 82, 83)); attack = true; heroHit = 1;
buttonAttackkSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
if (buttonAttackkSprite2.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonAttackkSprite2.setTextureRect(IntRect(1 * 82, 0, 82, 83)); attack = true; heroHit = 2;
buttonAttackkSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
if (buttonAttackkSprite3.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonAttackkSprite3.setTextureRect(IntRect(1 * 82, 0, 82, 83)); attack = true; heroHit = 3;
buttonAttackkSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonAttackkSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
////////////////////////////////
if (buttonDefSprite1.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonDefSprite1.setTextureRect(IntRect(1 * 82, 0, 82, 83)); def = true; heroDef = 1;
buttonDefSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
if (buttonDefSprite2.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonDefSprite2.setTextureRect(IntRect(1 * 82, 0, 82, 83)); def = true; heroDef = 2;
buttonDefSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite3.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
if (buttonDefSprite3.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonDefSprite3.setTextureRect(IntRect(1 * 82, 0, 82, 83)); def = true; heroDef = 3;
buttonDefSprite1.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonDefSprite2.setTextureRect(IntRect(0 * 82, 0, 82, 83));
buttonFightSprite.setTextureRect(IntRect(0 * 82, 0, 82, 83));
}
}
window.clear();
if (difficultyQuest == 'e')
{
window.draw(arenaEasyBackSprite);
window.draw(heroBarSprite);
window.draw(enemyBarSprite);
window.draw(arenaEasyHeadsSprite);
window.draw(elfEasySprite);
}
else if (difficultyQuest = 'h')
{
window.draw(arenaHardBackSprite);
window.draw(heroBarSprite);
window.draw(enemyBarSprite);
window.draw(arenaHardHeadsSprite);
window.draw(elfHardSprite);
}
window.draw(orcArenaSprite);
window.draw(buttonAttackkSprite1);
window.draw(buttonAttackkSprite2);
window.draw(buttonAttackkSprite3);
window.draw(buttonDefSprite1);
window.draw(buttonDefSprite2);
window.draw(buttonDefSprite3);
window.draw(buttonFightSprite);
window.draw(text);//рисую этот текст
window.draw(text2);//рисую этот текст
window.display();
}
return heroHealth;
}
void objectMap(int object, char letter)
{
while (object>0)
{
int randomElementX = rand() % 12;
int randomElementY = rand() % 12;
if (TileMap[randomElementY][randomElementX] == ' ')
{
object--;
TileMap[randomElementY][randomElementX] = letter;
}
}
}
int questModul(char difficulty)
{
//difficulty 'e' or 'h',easy and hard
sf::RenderWindow window(sf::VideoMode(1280, 800), "Battle Field", sf::Style::Close | sf::Style::Titlebar);
srand(time(NULL));
int countPurse;//количество кошельков
int countChest;//...сундуков
int countTrap;//...ловушек
int countFountain;//...фонтанов
int countEnemy;//...врагов
int countMeat;///...еда
if (difficulty == 'e') {
countPurse = 2;//количество кошельков
countChest = 1;//...сундуков
countTrap = 2;//...ловушек
countFountain = 1;//...фонтанов
countEnemy = 3;//...врагов
countMeat = 1;///...еда
}
if (difficulty == 'h') {
countPurse = 3;//количество кошельков
countChest = 2;//...сундуков
countTrap = 3;//...ловушек
countFountain = 1;//...фонтанов
countEnemy = 3;//...врагов
countMeat = 1;///...еда
}
int HP = 300;
int PW = 30;
int Gold = 0;
sf::Image mapImage;
mapImage.loadFromFile("images/questImages/mapTile.jpg");
sf::Texture map;
map.loadFromImage(mapImage);
sf::Sprite mapSprite;
mapSprite.setTexture(map);
sf::Image mapImageTop;
mapImageTop.loadFromFile("images/questImages/mapTop.png");
sf::Texture mapTop;
mapTop.loadFromImage(mapImageTop);
sf::Sprite mapSpriteTop;
mapSpriteTop.setTexture(mapTop);
sf::Texture heroTexture;
heroTexture.loadFromFile("images/questImages/hero.png");
sf::Sprite heroSprite;
heroSprite.setTexture(heroTexture);
heroSprite.setTextureRect(sf::IntRect(0, 0, 64, 64));
int px, py;
px = 1 + rand() % 7;
py = 1 + rand() % 7;
heroSprite.setPosition(0 + 15 + 64 * px, 0 + 15 + 64 * py);
for (int i = 1; i < HEIGHT_MAP_TOP - 1; i++)
{
for (int j = 1; j < WiDTH_MAP_TOP - 1; j++)
{
TileMap[i][j] = ' ';
}
}
for (int i = 1; i < HEIGHT_MAP_TOP-1; i++)
{
for (int j = 1; j < WiDTH_MAP_TOP-1; j++)
{
TileMapTOP[i][j] = ' ';
}
}
sf::Texture backTexture;
backTexture.loadFromFile("images/questImages/backBF.png");
sf::Sprite backSprite(backTexture);
sf::Texture buttonLooserTexture;
buttonLooserTexture.loadFromFile("images/questImages/buttonLooser.png");
sf::Sprite buttonLooserSprite(buttonLooserTexture);
buttonLooserSprite.setPosition(1500, 0);
sf::Texture buttonWinnerTexture;
buttonWinnerTexture.loadFromFile("images/questImages/buttonWinner.png");
sf::Sprite buttonWinnerSprite(buttonWinnerTexture);
buttonWinnerSprite.setPosition(1500, 0);
objectMap(countPurse, 'P');
objectMap(countChest, 'C');
objectMap(countTrap, 'T');
objectMap(countFountain, 'F');
objectMap(countEnemy, 'E');
objectMap(countMeat, 'M');
sf::Font font;
font.loadFromFile("font/Ycfhzibd.ttf");
sf::Text textGold("", font, 40);
textGold.setFillColor(sf::Color::Black);
textGold.setPosition(1100, 320);
std::ostringstream playerScoreGold;
playerScoreGold << Gold;
textGold.setString("" + playerScoreGold.str());
sf::Text textHP("", font, 40);
textHP.setFillColor(sf::Color::Black);
textHP.setPosition(1100, 410);
std::ostringstream playerScoreHP;
playerScoreHP << HP;
textHP.setString("" + playerScoreHP.str());
sf::Text textLog("", font, 18);
textLog.setFillColor(sf::Color::Black);
textLog.setPosition(850, 215);
textLog.setString("QUEST LOG");
int randomPurse = 0;
int randomChest = 0;
bool meal = false;
while (window.isOpen())
{
sf::Event evnt;
while (window.pollEvent(evnt))
{
if (evnt.type == evnt.Closed)
{
window.close();
}
}
window.clear();
Vector2i pixelPos = Mouse::getPosition(window);
Vector2f pos = window.mapPixelToCoords(pixelPos);
for (int i = 0; i < HEIGHT_MAP; i++)
{
for (int j = 0; j < WiDTH_MAP; j++)
{
if (TileMap[i][j] == ' ') mapSprite.setTextureRect(sf::IntRect(64 * 0, 0, 64, 64));
if (TileMap[i][j] == '0') mapSprite.setTextureRect(sf::IntRect(64 * 1, 0, 64, 64));
if (TileMap[i][j] == 'P' || TileMap[i][j] == 'p') mapSprite.setTextureRect(sf::IntRect(64 * 2, 0, 64, 64));
if (TileMap[i][j] == 'C' || TileMap[i][j] == 'c') mapSprite.setTextureRect(sf::IntRect(64 * 3, 0, 64, 64));
if (TileMap[i][j] == 'T' || TileMap[i][j] == 't') mapSprite.setTextureRect(sf::IntRect(64 * 4, 0, 64, 64));
if (TileMap[i][j] == 'F' || TileMap[i][j] == 'f') mapSprite.setTextureRect(sf::IntRect(64 * 5, 0, 64, 64));
if (difficulty == 'e') {
if (TileMap[i][j] == 'E' || TileMap[i][j] == 'e') mapSprite.setTextureRect(sf::IntRect(64 * 6, 0, 64, 64));
}
else if (difficulty == 'h')
{
if (TileMap[i][j] == 'E' || TileMap[i][j] == 'e') mapSprite.setTextureRect(sf::IntRect(64 * 7, 0, 64, 64));
}
if (TileMap[i][j] == 'M' || TileMap[i][j] == 'm') mapSprite.setTextureRect(sf::IntRect(64 * 8, 0, 64, 64));
mapSprite.setPosition(15 + j * 64, 15 + i * 64);
window.draw(mapSprite);
}
}
for (int i = 0; i < HEIGHT_MAP_TOP; i++)
{
for (int j = 0; j < WiDTH_MAP_TOP; j++)
{
if (TileMapTOP[i][j] == ' ') mapSpriteTop.setTextureRect(sf::IntRect(0, 0, 64, 64));
if (TileMapTOP[i][j] == '0') mapSpriteTop.setTextureRect(sf::IntRect(64, 0, 64, 64));
mapSpriteTop.setPosition(15 + j * 64, 15 + i * 64);
window.draw(mapSpriteTop);
}
}
int coordX = (heroSprite.getPosition().x - 15) / 64;
int coordY = (heroSprite.getPosition().y - 15) / 64;
//std::cout << "x = " << coordX << "\n";
//std::cout << "y = " << coordY << "\n";
//std::cout << "gold = " << Gold << "\n";
if (TileMapTOP[coordY][coordX] == ' ')
{
TileMapTOP[coordY][coordX] = '0';
window.draw(mapSpriteTop);
std::cout << TileMapTOP[coordX][coordY] << "\n";
}
if (Gold >= 0 && meal == false) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && evnt.type == sf::Event::KeyReleased)
{
if (TileMap[coordY][coordX - 1] != '0')
{
heroSprite.move(-64, 0);
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && evnt.type == sf::Event::KeyReleased)
{
if (TileMap[coordY][coordX + 1] != '0')
{
heroSprite.move(64, 0);
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && evnt.type == sf::Event::KeyReleased)
{
if (TileMap[coordY - 1][coordX] != '0')
{
heroSprite.move(0, -64);
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && evnt.type == sf::Event::KeyReleased)
{
if (TileMap[coordY + 1][coordX] != '0')
{
heroSprite.move(0, 64);
}
}
}
if (TileMap[coordY][coordX] == 'P' && TileMapTOP[coordY][coordX] == '0')
{
TileMap[coordY][coordX] = 'p';
randomPurse = 1 + rand() % 8;
Gold = Gold + randomPurse;
std::ostringstream playerScoreGold;
playerScoreGold << Gold;
textGold.setString(playerScoreGold.str());
textLog.setString("You found a lost purse with " + toString(randomPurse) + " gold");
}
if (TileMap[coordY][coordX] == 'C' && TileMapTOP[coordY][coordX] == '0')
{
TileMap[coordY][coordX] = 'c';
randomChest = 10 + rand() % 30;
Gold = Gold + randomChest;
std::ostringstream playerScoreGold;
playerScoreGold << Gold;
textGold.setString(playerScoreGold.str());
textLog.setString("You found a lost elfs chest with " + toString(randomChest) + " gold");
}
if (TileMap[coordY][coordX] == 'T' && TileMapTOP[coordY][coordX] == '0')
{
HP = HP - HP / 4;
TileMap[coordY][coordX] = 't';
std::ostringstream playerScoreHP;
playerScoreHP << HP;
textHP.setString(playerScoreHP.str());
textLog.setString("You are trapped and lost 25% HP");
}
if (TileMap[coordY][coordX] == 'F' && TileMapTOP[coordY][coordX] == '0')
{
HP = 300;
TileMap[coordY][coordX] = 'f';
std::ostringstream playerScoreHP;
playerScoreHP << HP;
textHP.setString(playerScoreHP.str());
textLog.setString("You found the fountain of life \n\nand restored all HP");
}
if (TileMap[coordY][coordX] == 'E' && TileMapTOP[coordY][coordX] == '0')
{
TileMap[coordY][coordX] = 'e';
if (difficulty == 'e') {
HP = questBattle(window, HP, 'e');
}
else if (difficulty == 'h') {
HP = questBattle(window, HP, 'h');
}
if (HP>0)
{
textLog.setString("The elf attacked you, but you were \n\nable to defeat");
}
else
{
textLog.setString("The elf attacked you, defeated and drove \n\nyou out of the forest");
Gold = 0 - rand() % 7 - 1;
std::ostringstream playerScoreGold;
playerScoreGold << Gold;
textGold.setString(playerScoreGold.str());
buttonLooserSprite.setPosition(0, 0);
}
std::ostringstream playerScoreHP;
playerScoreHP << HP;
textHP.setString(playerScoreHP.str());
}
if (TileMap[coordY][coordX] == 'M' && TileMapTOP[coordY][coordX] == '0')
{
TileMap[coordY][coordX] = 'm';
textLog.setString("Victory!!!\n\nYou found the beast and got food");
meal = true;
buttonWinnerSprite.setPosition(0, 0);
}
if (evnt.type == evnt.MouseButtonReleased && evnt.mouseButton.button == Mouse::Left)
{
if (buttonLooserSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
return Gold;
}
}
if (evnt.type == evnt.MouseButtonReleased && evnt.mouseButton.button == Mouse::Left)
{
if (buttonWinnerSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
return Gold;
}
}
window.draw(backSprite);
window.draw(textGold);
window.draw(textHP);
window.draw(textLog);
window.draw(heroSprite);
window.draw(buttonLooserSprite);
window.draw(buttonWinnerSprite);
window.display();
}
}
int main()
{
RenderWindow window(sf::VideoMode(1280, 800), "TAMAGOTCHI", sf::Style::Close | sf::Style::Titlebar);
menu(window);
setlocale(LC_ALL, "rus");
Font font;
font.loadFromFile("font/comic.ttf");
Font fontH;
fontH.loadFromFile("font/FEASFBRG_0.TTF");
Text arenaText("Arena",fontH,60);
arenaText.setFillColor(sf::Color::Color(36, 76, 75, 255));
Text weightText("Weight", fontH, 60);
weightText.setFillColor(sf::Color::Color(36, 76, 75, 255));
Text caveText("Cave", fontH, 60);
caveText.setFillColor(sf::Color::Color(36, 76, 75, 255));
weightText.setPosition(2260, 95);
caveText.setPosition(2270, 95);
arenaText.setPosition(2260, 95);
Text text("", font, 20);
Text text2("", font, 20);
Text text3("", font, 20);
Text text4("", font, 20);
Text text5("", font, 20);
Text text6("", font, 20);
Text text7("", font, 20);
Text text8("GAME OVER", font, 20);
text.setCharacterSize(20);
text2.setCharacterSize(20);
text3.setCharacterSize(20);
text4.setCharacterSize(20);
text5.setCharacterSize(20);
text6.setCharacterSize(18);
text7.setCharacterSize(18);
text8.setCharacterSize(40); //GAME OVER
text.setFillColor(sf::Color::Black);
text2.setFillColor(sf::Color::Black);
text3.setFillColor(sf::Color::Black);
text4.setFillColor(sf::Color::Black);
text5.setFillColor(sf::Color::Black);
text6.setFillColor(sf::Color::Black);
text7.setFillColor(sf::Color::Black);
///////////Textures of backgrounds for main page of game
Texture mainBackTexture;
Texture oldPaperTexture;
///////////Textures of top 3 buttons
Texture buttonWeightTexture;
Texture buttonCaveTexture;
Texture buttonArenaTexture;
/////////Texture of background for left block
Texture backLeftBlockTexture;
//////// Texture of main hero
Texture orcTexture;
//////// Textures of bottom 2 icons
Texture respectIconTexture;
Texture energyIconTexture;
/////////Textures for 6 buttons of change way
Texture buttonEasyArenaTexture;
Texture buttonHardArenaTexture;
Texture buttonMainBattleTexture;
Texture buttonEasyHuntTexture;
Texture buttonHardHuntTexture;
Texture buttonEasyWorkTexture;
Texture buttonHardWorkTexture;
Texture buttonManualTexture;
Texture manualTexture;
Texture buttonBackTexture;
Texture notEnoughEnergyTexture;
mainBackTexture.loadFromFile("images/mainGameBack.png");
oldPaperTexture.loadFromFile("images/oldPaper.jpg");
notEnoughEnergyTexture.loadFromFile("images/notenergy.png");
buttonWeightTexture.loadFromFile("images/buttonWeight.png"); //130(*2) * 134 px
buttonCaveTexture.loadFromFile("images/buttonDeepCave.png"); //130(*2) * 134 px
buttonArenaTexture.loadFromFile("images/buttonArena.png"); //130(*2) * 134 px
backLeftBlockTexture.loadFromFile("images/backLeft.jpg");//497(*7) * 565 px
orcTexture.loadFromFile("images/orc.png");//220(*8) *195;
respectIconTexture.loadFromFile("images/respect.png"); // 130(*10) *134 px
energyIconTexture.loadFromFile("images/energy.png");//130(*10) *134 px
buttonEasyArenaTexture.loadFromFile("images/arenaEasy.png"); //139(*2) *175 px
buttonHardArenaTexture.loadFromFile("images/arenaHard.png"); //139(*2) *175 px
buttonMainBattleTexture.loadFromFile("images/buttonMainBattle.png");//229(*2) *186
buttonEasyHuntTexture.loadFromFile("images/huntEasy.png"); //139(*2) *175 px
buttonHardHuntTexture.loadFromFile("images/huntHard.png"); //139(*2) *175 px
buttonEasyWorkTexture.loadFromFile("images/workEasy.png"); //139(*2) *175 px
buttonHardWorkTexture.loadFromFile("images/workHard.png"); //139(*2) *175 px
buttonManualTexture.loadFromFile("images/buttonManual.png");//84(*2) *99 px
manualTexture.loadFromFile("images/manual.jpg");
buttonBackTexture.loadFromFile("images/buttonBack.png");//84(*2) *99 px
Sprite mainBackSprite;
Sprite oldPaperSprite;
Sprite buttonWeightSprite;
Sprite buttonCaweightprite;
Sprite buttonArenaSprite;
Sprite backLeftBlockSprite;
Sprite orcSprite;
Sprite respectIconSprite;
Sprite energyIconSprite;
Sprite buttonEasyArenaSprite;
Sprite buttonHardArenaSprite;
Sprite buttonMainBattleSprite;
Sprite buttonEasyHuntSprite;
Sprite buttonHardHuntSprite;
Sprite buttonEasyWorkSprite;
Sprite buttonHardWorkSprite;
Sprite buttonManualSprite;
Sprite manualSprite(manualTexture);
Sprite buttonBackSprite;
Sprite notEnoughEnergySprite;
SoundBuffer clickBuffer;//создаём буфер для звука
clickBuffer.loadFromFile("sound/click.ogg");//загружаем в него звук
Sound clickSound(clickBuffer);//создаем звук и загружаем в него звук из буфера
notEnoughEnergySprite.setTexture(notEnoughEnergyTexture);
notEnoughEnergySprite.setPosition(1450, 250);//450, 250
mainBackSprite.setTexture(mainBackTexture);
mainBackSprite.setTextureRect(IntRect(0, 0, 1280, 800));
mainBackSprite.setPosition(0, 0);
oldPaperSprite.setTexture(oldPaperTexture);
oldPaperSprite.setTextureRect(IntRect(0, 0, 1280, 800));
oldPaperSprite.setPosition(0, 0);
buttonWeightSprite.setTexture(buttonWeightTexture);
buttonWeightSprite.setTextureRect(IntRect(0, 0, 130, 134));
buttonWeightSprite.setPosition(730, 30);
buttonCaweightprite.setTexture(buttonCaveTexture);
buttonCaweightprite.setTextureRect(IntRect(0, 0, 130, 134));
buttonCaweightprite.setPosition(900, 30);
buttonArenaSprite.setTexture(buttonArenaTexture);
buttonArenaSprite.setTextureRect(IntRect(0, 0, 130, 134));
buttonArenaSprite.setPosition(1070, 30);
backLeftBlockSprite.setTexture(backLeftBlockTexture);
backLeftBlockSprite.setTextureRect(IntRect(0 * 497, 0, 497, 565));
backLeftBlockSprite.setPosition(80, 170);
orcSprite.setTexture(orcTexture);
orcSprite.setTextureRect(IntRect(0 * 220, 0, 220, 195));
orcSprite.setPosition(125, 425);
respectIconSprite.setTexture(respectIconTexture);
respectIconSprite.setTextureRect(IntRect(8 * 130, 0, 130, 134));
respectIconSprite.setPosition(830, 650);
energyIconSprite.setTexture(energyIconTexture);
energyIconSprite.setTextureRect(IntRect(5 * 130, 0, 130, 134));
energyIconSprite.setPosition(1000, 650);
buttonEasyArenaSprite.setTexture(buttonEasyArenaTexture);
buttonEasyArenaSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
buttonEasyArenaSprite.setPosition(1500, 1500);//(820, 475)
buttonHardArenaSprite.setTexture(buttonHardArenaTexture);
buttonHardArenaSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
buttonHardArenaSprite.setPosition(1500, 1500);//(990, 475)
buttonMainBattleSprite.setTexture(buttonMainBattleTexture);
buttonMainBattleSprite.setTextureRect(IntRect(0 * 229, 0, 229, 186));
buttonMainBattleSprite.setPosition(1500, 1500);
buttonEasyHuntSprite.setTexture(buttonEasyHuntTexture);
buttonEasyHuntSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
buttonEasyHuntSprite.setPosition(1500, 1500);//(820, 475)
buttonHardHuntSprite.setTexture(buttonHardHuntTexture);
buttonHardHuntSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
buttonHardHuntSprite.setPosition(1500, 1500);//(990, 475)
buttonEasyWorkSprite.setTexture(buttonEasyWorkTexture);
buttonEasyWorkSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
buttonEasyWorkSprite.setPosition(1500, 1500);//(820, 475)
buttonHardWorkSprite.setTexture(buttonHardWorkTexture);
buttonHardWorkSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
buttonHardWorkSprite.setPosition(1500, 1500);//(990, 475)
buttonManualSprite.setTexture(buttonManualTexture);
buttonManualSprite.setTextureRect(IntRect(0 * 84, 0, 84, 99));
buttonManualSprite.setPosition(50, 660);
manualSprite.setPosition(2000, 2000);
buttonBackSprite.setTexture(buttonBackTexture);
buttonBackSprite.setTextureRect(IntRect(0 * 84, 0, 84, 99));
buttonBackSprite.setPosition(2180, 5);
while (window.isOpen())
{
if (respect < 0) respect = 0;
if (respect > 100) respect = 100;
if (energy < 0) energy = 0;
if (energy > 100) energy = 100;
if (weight < 0) weight = 0;
int time2 = mytime2.getElapsedTime().asSeconds();
if (time2>30)
{
energy = energy + 1;
mytime2.restart();
save_t();
}
if (flag == 229)
{
std::cout << "flag 299";
update_me();
flag = 228;
}
Vector2i pixelPos = Mouse::getPosition(window);
Vector2f pos = window.mapPixelToCoords(pixelPos);//переводим их в игровые (уходим от коорд окна)
std::cout << pixelPos.x << "\n";//смотрим на координату Х позиции курсора в консоли (она не будет больше ширины окна)
std::cout << pixelPos.y << "\n";//смотрим на координату Х позиции курсора в консоли (она не будет больше ширины окна)
//std::cout << pos.x << " | " << pos.y << "\n";
sf::Event startPage;
while (window.pollEvent(startPage))
{
if (startPage.type == sf::Event::Closed)
window.close();
if (startPage.type == startPage.MouseButtonReleased && startPage.mouseButton.button == Mouse::Left)
{
if (buttonWeightSprite.getGlobalBounds().contains(pos.x, pos.y)) clickSound.play();
if (buttonCaweightprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonArenaSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonEasyArenaSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonHardArenaSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonMainBattleSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonEasyHuntSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonHardHuntSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonEasyWorkSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonHardWorkSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonManualSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
if (buttonBackSprite.getGlobalBounds().contains(pos.x, pos.y)) { clickSound.play(); }
}
}
if (scalp >= 0) orcSprite.setTextureRect(IntRect(0 * 220, 0, 220, 195));
if (scalp >= 1) orcSprite.setTextureRect(IntRect(1 * 220, 0, 220, 195));
if (scalp >= 3) orcSprite.setTextureRect(IntRect(2 * 220, 0, 220, 195));
if (scalp >= 5) orcSprite.setTextureRect(IntRect(3 * 220, 0, 220, 195));
if (scalp >= 10) orcSprite.setTextureRect(IntRect(4 * 220, 0, 220, 195));
if (scalp >= 15) orcSprite.setTextureRect(IntRect(5 * 220, 0, 220, 195));
if (scalp >= 20) orcSprite.setTextureRect(IntRect(6 * 220, 0, 220, 195));
if (scalp >= 25) orcSprite.setTextureRect(IntRect(7 * 220, 0, 220, 195));
if (notEnoughEnergySprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
if (Mouse::isButtonPressed(Mouse::Left))
{
notEnoughEnergySprite.setPosition(1450,250);
}
}
if (buttonManualSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonManualSprite.setTextureRect(IntRect(84, 0, 84, 99));
if (Mouse::isButtonPressed(Mouse::Left))
{
manualSprite.setPosition(0, 0);
buttonBackSprite.setPosition(1180, 5);
weightText.setPosition(2260, 95);
caveText.setPosition(2270, 95);
arenaText.setPosition(2260, 95);
}
}
else {
buttonManualSprite.setTextureRect(IntRect(0, 0, 84, 99));
}
if (buttonBackSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonBackSprite.setTextureRect(IntRect(84, 0, 84, 99));
if (Mouse::isButtonPressed(Mouse::Left))
{
manualSprite.setPosition(2000, 0);
buttonBackSprite.setPosition(2180, 5);
}
}
else
{
buttonBackSprite.setTextureRect(IntRect(0, 0, 84, 99));
}
if (buttonWeightSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonWeightSprite.setTextureRect(IntRect(130, 0, 260, 134));
if (Mouse::isButtonPressed(Mouse::Left))
{
backLeftBlockSprite.setTextureRect(IntRect(0 * 497, 0, 497, 565));
buttonEasyHuntSprite.setPosition(820, 475);//(820, 475)
buttonHardHuntSprite.setPosition(990, 475);//(990, 475)
buttonEasyArenaSprite.setPosition(1500, 1500);//(820, 475)
buttonHardArenaSprite.setPosition(1500, 1500);//(990, 475)
buttonEasyWorkSprite.setPosition(1500, 1500);//(820, 475)
buttonHardWorkSprite.setPosition(1500, 1500);//(990, 475)
weightText.setPosition(260, 95);
caveText.setPosition(2270, 95);
arenaText.setPosition(2260, 95);
buttonMainBattleSprite.setPosition(1860, 450);
dlgtext = L"Have you decided to have a light meal?\nYou can hunt for easy prey,\nor try a more serious beast.\nWhat do you choose?";
dlgtext2 = "";
}
}
else {
buttonWeightSprite.setTextureRect(IntRect(0, 0, 130, 134));
}
if (buttonCaweightprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonCaweightprite.setTextureRect(IntRect(130, 0, 260, 134));
if (Mouse::isButtonPressed(Mouse::Left))
{
backLeftBlockSprite.setTextureRect(IntRect(3 * 497, 0, 497, 565));
buttonEasyWorkSprite.setPosition(820, 475);//(820, 475)
buttonHardWorkSprite.setPosition(990, 475);//(990, 475)
buttonEasyArenaSprite.setPosition(1500, 1500);//(820, 475)
buttonHardArenaSprite.setPosition(1500, 1500);//(990, 475)
buttonEasyHuntSprite.setPosition(1500, 1500);//(820, 475)
buttonHardHuntSprite.setPosition(1500, 1500);//(990, 475)
weightText.setPosition(2260, 95);
caveText.setPosition(270, 95);
arenaText.setPosition(2260, 95);
buttonMainBattleSprite.setPosition(1860, 450);
dlgtext = L"You are in the digger mode.\nUse the two buttons below to select the complexity \nof the job.\nThe faster you dig the faster you'll be tired\n";
dlgtext2 = "";
}
}
else {
buttonCaweightprite.setTextureRect(IntRect(0, 0, 130, 134));
}
if(scalp<25){
if (buttonArenaSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonArenaSprite.setTextureRect(IntRect(130, 0, 130, 134));
if (Mouse::isButtonPressed(Mouse::Left))
{
backLeftBlockSprite.setTextureRect(IntRect(4 * 497, 0, 497, 565));
buttonEasyArenaSprite.setPosition(820, 475);//(820, 475)
buttonHardArenaSprite.setPosition(990, 475);//(990, 475)
buttonEasyHuntSprite.setPosition(1500, 1500);//(820, 475)
buttonHardHuntSprite.setPosition(1500, 1500);//(990, 475)
buttonEasyWorkSprite.setPosition(1500, 1500);//(820, 475)
buttonHardWorkSprite.setPosition(1500, 1500);//(990, 475)
weightText.setPosition(2260, 95);
caveText.setPosition(2270, 95);
arenaText.setPosition(260, 95);
dlgtext = L"You chose the arena mode.\nUse the two buttons at the bottom of the screen to \nselect the difficulty level of your opponent.\nThe harder the opponent is, the higher the reward for it!";
dlgtext2 = "";
}
}
else {
buttonArenaSprite.setTextureRect(IntRect(0, 0, 130, 134));
}
}
else
{
buttonArenaSprite.setTextureRect(IntRect(130*2, 0, 130, 134));
if (buttonArenaSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonArenaSprite.setTextureRect(IntRect(130*3, 0, 130, 134));
if (Mouse::isButtonPressed(Mouse::Left))
{
backLeftBlockSprite.setTextureRect(IntRect(7 * 497, 0, 497, 565));
buttonEasyArenaSprite.setPosition(1500, 475);//(820, 475)
buttonHardArenaSprite.setPosition(1500, 475);//(990, 475)
buttonEasyHuntSprite.setPosition(1500, 1500);//(820, 475)
buttonHardHuntSprite.setPosition(1500, 1500);//(990, 475)
buttonEasyWorkSprite.setPosition(1500, 1500);//(820, 475)
buttonHardWorkSprite.setPosition(1500, 1500);//(990, 475)
weightText.setPosition(2260, 95);
caveText.setPosition(2270, 95);
arenaText.setPosition(260, 95);
buttonMainBattleSprite.setPosition(860, 450);
dlgtext = L"You did it!!!.\nYou have 25 scalps and now tribe's leader\nis waiting for you.\nGood luck good luck in the main battle of your life!";
dlgtext2 = "";
}
}
}
if (buttonMainBattleSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonMainBattleSprite.setTextureRect(IntRect(229 * 1, 0, 229, 186));
if (Mouse::isButtonPressed(Mouse::Left))
{
finalBattle(window,weight);
}
}
else
{
buttonMainBattleSprite.setTextureRect(IntRect(229 * 0, 0, 229, 186));
}
if (buttonEasyArenaSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonEasyArenaSprite.setTextureRect(IntRect(139, 0, 139, 175));
if (Mouse::isButtonPressed(Mouse::Left))
{
if (energy >= 10) {
if (X7 == 0)
{
backLeftBlockSprite.setTextureRect(IntRect(5 * 497, 0, 497, 565));
X4 = random(0, 101); // WIN RANDOM CHANGE
if (X4 > 16)
{
X1 = random(1, 4); // weight
X2 = random(2, 5); // STAM
X3 = random(-3, 3); // respect
X4 = random(0, 101); // SCALP RANDOM CHANGE
if (X4 < 16)
{
X5 = 1;
}
else X5 = 0;
dlgtext2 = L"Victory over a weak opponent!\nRewards and losses:\nWeight: -" + toString(X1) + L"\nEnergy: -" + toString(X2) + L"\nRespect: " + toString(X3) + L"\nScalp: " + toString(X5);
weight = weight - X1;
energy = energy - X2;
respect = respect + X3;
scalp = scalp + X5;
X7 = 1;
save();
}
else
{
X1 = random(4, 9); // weight
X2 = random(5, 9); // STAM
X3 = random(-10, 0); // respect
X5 = 0;
dlgtext2 = L"Defeat against a weak opponent!\nRewards and losses:\nWeight: -" + toString(X1) + L"\nEnergy: -" + toString(X2) + L"\nRespect: " + toString(X3) + L"\nScalp: " + toString(X5);
weight = weight - X1;
energy = energy - X2;
respect = respect + X3;
scalp = scalp + X5;
X7 = 1;
save();
}
}
}
else
{
notEnoughEnergySprite.setPosition(450, 250);//450, 250
}
}
}
else {
buttonEasyArenaSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
X7 = 0;
}
if (buttonHardArenaSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonHardArenaSprite.setTextureRect(IntRect(139, 0, 139, 175));
if (Mouse::isButtonPressed(Mouse::Left))
{
if (energy >= 10) {
if (X8 == 0)
{
backLeftBlockSprite.setTextureRect(IntRect(6 * 497, 0, 497, 565));
X4 = random(0, 101); // RANDOM CHANGE WIN
if (X4 > 50) {
X1 = random(3, 9); // weight
X2 = random(6, 12); // STAMIN
X3 = random(5, 12); // respect
X4 = random(0, 101);//RANDOM CHANGE SCALP
if (X4 < 31)
{
X5 = 1;
}
else X5 = 0;
dlgtext2 = L"Victory over a strong opponent!\nRewards and losses:\nWeight: -" + toString(X1) + L"\nEnergy: -" + toString(X2) + L"\nRespect: -" + toString(X3) + L"\nScalp: " + toString(X5);
weight = weight - X1;
energy = energy - X2;
respect = respect + X3;
scalp = scalp + X5;
X8 = 1;
save();
}
else
{
X1 = random(5, 13); // weight
X2 = random(8, 15); // STAMIN
X3 = random(1, 5); // respect
dlgtext2 = L"Defeat against a strong opponent!\nRewards and losses:\nWeight: -" + toString(X1) + L"\nEnergy: -" + toString(X2) + L"\nRespect: -" + toString(X3) + L"\nScalp: " + toString(X5);
weight = weight - X1;
energy = energy - X2;
respect = respect + X3;
scalp = scalp + X5;
X8 = 1;
save();
}
}
}
else
{
notEnoughEnergySprite.setPosition(450, 250);//450, 250
}
}
}
else {
buttonHardArenaSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
X8 = 0;
}
if (buttonEasyHuntSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonEasyHuntSprite.setTextureRect(IntRect(139, 0, 139, 175));
if (Mouse::isButtonPressed(Mouse::Left))
{
if (energy >= 10) {
questResult = questModul('e');
if (questResult >= 0) {
if (X9 == 0)
{
X1 = random(50, 75); // weight
X2 = random(7, 11); // STAMIN
X3 = random(1, 6); // respect
backLeftBlockSprite.setTextureRect(IntRect(2 * 497, 0, 497, 565));
dlgtext2 = L"Victory over a weak beast!\nRewards and losses:\nWeight: +" + toString(X1) + L"\nEnergy: -" + toString(X2) + L"\nRespect: -" + toString(X3);
weight = weight + X1;
energy = energy - X2;
respect = respect - X3;
X9 = 1;
save();
}
}
else if (questResult < 0)
{
if (X9 == 0)
{
X1 = random(5, 15); // weight
X2 = random(14, 22); // STAMIN
X3 = random(2, 12); // respect
backLeftBlockSprite.setTextureRect(IntRect(2 * 497, 0, 497, 565));
dlgtext2 = L"Defeat against a weak beast!\nRewards and losses:\nWeight: +" + toString(X1) + L"\nEnergy: -" + toString(X2) + L"\nRespect: -" + toString(X3);
weight = weight - X1;
energy = energy - X2;
respect = respect - X3;
X9 = 1;
save();
}
}
}
else
{
notEnoughEnergySprite.setPosition(450, 250);//450, 250
}
}
}
else {
buttonEasyHuntSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
X9 = 0;
}
if (buttonHardHuntSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonHardHuntSprite.setTextureRect(IntRect(139, 0, 139, 175));
if (Mouse::isButtonPressed(Mouse::Left))
{
if (energy >= 10) {
questResult = questModul('h');
if (questResult >= 0) {
if (X10 == 0)
{
backLeftBlockSprite.setTextureRect(IntRect(1 * 497, 0, 497, 565));
X1 = random(100, 150); // weight
X2 = random(14, 22); // STAMIN
X3 = random(7, 11); // respect
dlgtext2 = L"Victory over a strong beast!\nRewards and losses:\nWeight: +" + toString(X1) + L"\nEnergy: -" + toString(X2) + L"\nRespect: +" + toString(X3);
weight = weight + X1;
energy = energy - X2;
respect = respect + X3;
X10 = 1;
save();
}
}
else if (questResult < 0)
{
backLeftBlockSprite.setTextureRect(IntRect(1 * 497, 0, 497, 565));
X1 = random(20, 40); // weight
X2 = random(12, 18); // STAMIN
X3 = random(1, 7); // respect
dlgtext2 = L"Defeat against a strong beast!\nRewards and losses:\nWeight: -" + toString(X1) + L"\nEnergy: -" + toString(X2) + L"\nRespect: +" + toString(X3);
weight = weight - X1;
energy = energy - X2;
respect = respect + X3;
X10 = 1;
save();
}
}
else
{
notEnoughEnergySprite.setPosition(450, 250);//450, 250
}
}
}
else {
buttonHardHuntSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
X10 = 0;
}
if (buttonEasyWorkSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonEasyWorkSprite.setTextureRect(IntRect(139, 0, 139, 175));
if (Mouse::isButtonPressed(Mouse::Left))
{
if (energy >= 10) {
if (X11 == 0)
{
X1 = random(5, 10); // weight
X2 = random(7, 11); // STAMIN
X3 = random(1, 3); // respect
X4 = random(2, 6); // deep
dlgtext2 = L"You digging badly, the results are not very good!\nRewards and losses:\nWeight: -" + toString(X1) + L"\nEnergy: -" + toString(X2) + L"\nRespect: -" + toString(X3) + L"\nDeep: +" + toString(X4);
weight = weight - X1;
energy = energy - X2;
respect = respect - X3;
deep = deep + X4;
X11 = 1;
save();
}
//backLeftBlockSprite.setTextureRect(IntRect(1 * 497, 0, 497, 565));
}
else
{
notEnoughEnergySprite.setPosition(450, 250);//450, 250
}
}
}
else {
buttonEasyWorkSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
X11 = 0;
}
if (buttonHardWorkSprite.getGlobalBounds().contains(pos.x, pos.y))//координата курсора попадает в спрайт
{
buttonHardWorkSprite.setTextureRect(IntRect(139, 0, 139, 175));
if (Mouse::isButtonPressed(Mouse::Left))
{
if (energy >= 10) {
if (X12 == 0)
{
X1 = random(5, 10); // weight
X2 = random(7, 11); // STAMIN
X3 = random(1, 3); // respect
X4 = random(2, 6); // deep
dlgtext2 = L"You WELL digging, the results are good!\nRewards and losses:\nWeight: -" + toString(X1) + L"\nEnergy: -" + toString(X2) + L"\nRespect: +" + toString(X3) + L"\nDeep: +" + toString(X4);
weight = weight - X1;
energy = energy - X2;
respect = respect - X3;
deep = deep + X4;
X12 = 1;
save();
}
//backLeftBlockSprite.setTextureRect(IntRect(1 * 497, 0, 497, 565));
}
else
{
notEnoughEnergySprite.setPosition(450, 250);//450, 250
}
}
}
else {
buttonHardWorkSprite.setTextureRect(IntRect(0 * 139, 0, 139, 175));
X12 = 0;
}
if (energy >= 90 && energy <= 100) energyIconSprite.setTextureRect(IntRect(0 * 130, 0, 130, 134));
if (energy >= 80 && energy < 90) energyIconSprite.setTextureRect(IntRect(1 * 130, 0, 130, 134));
if (energy >= 70 && energy < 80) energyIconSprite.setTextureRect(IntRect(2 * 130, 0, 130, 134));
if (energy >= 60 && energy < 70) energyIconSprite.setTextureRect(IntRect(3 * 130, 0, 130, 134));
if (energy >= 50 && energy < 60) energyIconSprite.setTextureRect(IntRect(4 * 130, 0, 130, 134));
if (energy >= 40 && energy < 50) energyIconSprite.setTextureRect(IntRect(5 * 130, 0, 130, 134));
if (energy >= 30 && energy < 40) energyIconSprite.setTextureRect(IntRect(6 * 130, 0, 130, 134));
if (energy >= 20 && energy < 30) energyIconSprite.setTextureRect(IntRect(7 * 130, 0, 130, 134));
if (energy >= 10 && energy < 20) energyIconSprite.setTextureRect(IntRect(8 * 130, 0, 130, 134));
if (energy >= 0 && energy < 10) energyIconSprite.setTextureRect(IntRect(9 * 130, 0, 130, 134));
if (respect >= 90 && respect <= 100) respectIconSprite.setTextureRect(IntRect(0 * 130, 0, 130, 134));
if (respect >= 80 && respect < 90) respectIconSprite.setTextureRect(IntRect(1 * 130, 0, 130, 134));
if (respect >= 70 && respect < 80) respectIconSprite.setTextureRect(IntRect(2 * 130, 0, 130, 134));
if (respect >= 60 && respect < 70) respectIconSprite.setTextureRect(IntRect(3 * 130, 0, 130, 134));
if (respect >= 50 && respect < 60) respectIconSprite.setTextureRect(IntRect(4 * 130, 0, 130, 134));
if (respect >= 40 && respect < 50) respectIconSprite.setTextureRect(IntRect(5 * 130, 0, 130, 134));
if (respect >= 30 && respect < 40) respectIconSprite.setTextureRect(IntRect(6 * 130, 0, 130, 134));
if (respect >= 20 && respect < 30) respectIconSprite.setTextureRect(IntRect(7 * 130, 0, 130, 134));
if (respect >= 10 && respect < 20) respectIconSprite.setTextureRect(IntRect(8 * 130, 0, 130, 134));
if (respect >= 0 && respect < 10) respectIconSprite.setTextureRect(IntRect(9 * 130, 0, 130, 134));
window.clear();
window.draw(oldPaperSprite);
window.draw(backLeftBlockSprite);
window.draw(mainBackSprite);
window.draw(buttonWeightSprite);
window.draw(buttonCaweightprite);
window.draw(buttonArenaSprite);
window.draw(orcSprite);
window.draw(respectIconSprite);
window.draw(energyIconSprite);
window.draw(buttonEasyArenaSprite);
window.draw(buttonHardArenaSprite);
window.draw(buttonMainBattleSprite);
window.draw(buttonEasyHuntSprite);
window.draw(buttonHardHuntSprite);
window.draw(buttonEasyWorkSprite);
window.draw(buttonHardWorkSprite);
// int energy,deep,weight,respect,scalp;
//dlgtext2 = "test";
text.setString(toString(weight)); // weight
text.setPosition(772, 133);
text2.setString(toString(deep)); // deep
text2.setPosition(949, 133);
text3.setString(toString(scalp)); // arena
text3.setPosition(1117, 133);
text4.setString(toString(respect)); // respect
text4.setPosition(872, 754);
text5.setString(toString(energy)); //energy
text5.setPosition(1047, 754);
window.draw(text);
window.draw(text2);
window.draw(text3);
window.draw(text4);
window.draw(text5);
text6.setString(dlgtext);
text6.setPosition(730, 200);
text7.setString(dlgtext2);
text7.setPosition(730, 320);
window.draw(text6);
window.draw(text7);
window.draw(buttonManualSprite);
window.draw(manualSprite);
window.draw(buttonBackSprite);
window.draw(weightText);
window.draw(arenaText);
window.draw(caveText);
window.draw(notEnoughEnergySprite);
//if (weight < 10)
//{
// window.draw(GameOverSprite);
// window.draw(text8);
// text8.setPosition(530, 360);
//}
window.display();
}
return 0;
}<file_sep># Tamagotchi
![alt text]()
| f1373039d5a324939226b45a0455ddc8dbe2617f | [
"Markdown",
"C++"
] | 2 | C++ | Elhantero/Tamagotchi | a78693c532c53a82f1f6567b2897c25cc80fca02 | 657c517a9a5141040197eb4c2abe29af73f5bf84 |
refs/heads/master | <repo_name>bobiandreev/Methods-And-Debugging-Exercises<file_sep>/Max-Method/Max-Method.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Max_Method
{
class Program
{
static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int c = int.Parse(Console.ReadLine());
int max = GetMax(a, b, c);
Console.WriteLine(max);
}
private static int GetMax(int a, int b, int c)
{
int getMax = Math.Max (c, Math.Max(a, b));
return getMax;
}
}
}
<file_sep>/Longer-Line/Longer-Line.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Longer_Line
{
class Program
{
static void Main(string[] args)
{
double x1 = double.Parse(Console.ReadLine());
double y1 = double.Parse(Console.ReadLine());
double x2 = double.Parse(Console.ReadLine());
double y2 = double.Parse(Console.ReadLine());
double x3 = double.Parse(Console.ReadLine());
double y3 = double.Parse(Console.ReadLine());
double x4 = double.Parse(Console.ReadLine());
double y4 = double.Parse(Console.ReadLine());
double line1 = CalcLine1(x1, y1, x2, y2);
double line2 = CalcLine2(x3, y3, x4, y4);
double distCentx1y1 = Centx1y1(x1, y1);
double distCentx2y2 = Centx2y2(x2, y2);
double distCentx3y3 = Centx3y3(x3, y3);
double distCentx4y4 = Centx4y4(x4, y4);
if (line1 >= line2)
{
if (distCentx1y1 < distCentx2y2)
{ Console.WriteLine($"({x1}, {y1})({x2}, {y2})"); }
else
Console.WriteLine($"({x2}, {y2})({x1}, {y1})");
}
else
{
if (distCentx3y3 < distCentx4y4)
{ Console.WriteLine($"({x3}, {y3})({x4}, {y4})"); }
else
{ Console.WriteLine($"({x4}, {y4})({x3}, {y3})"); }
}
}
private static double Centx4y4(double x4, double y4)
{
double dist = Math.Sqrt(Math.Pow(x4, 2) + Math.Pow(y4, 2));
return dist;
}
private static double Centx3y3(double x3, double y3)
{
double dist = Math.Sqrt(Math.Pow(x3, 2) + Math.Pow(y3, 2));
return dist;
}
private static double Centx2y2(double x2, double y2)
{
double dist = Math.Sqrt(Math.Pow(x2, 2) + Math.Pow(y2, 2));
return dist;
}
private static double Centx1y1(double x1, double y1)
{
double dist = Math.Sqrt(Math.Pow(x1, 2) + Math.Pow(y1, 2));
return dist;
}
private static double CalcLine2(double x3, double y3, double x4, double y4)
{
double dist = Math.Sqrt(Math.Pow((x4 - x3), 2) + Math.Pow((y4 - y3), 2));
return dist;
}
private static double CalcLine1(double x1, double y1, double x2, double y2)
{
double dist = Math.Sqrt(Math.Pow((x2 - x1), 2)+ Math.Pow((y2-y1),2));
return dist;
}
}
}
<file_sep>/Cube-Properties/Cube-Properties.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cube_Properties
{
class Program
{
static void Main(string[] args)
{
double n = double.Parse(Console.ReadLine());
string type = Console.ReadLine();
if (type == "face")
{
double face = GetFace(n);
Console.WriteLine($"{face:f2}");
}
else if (type == "space")
{
double space = GetSpace(n);
Console.WriteLine($"{space:f2}");
}
else if (type == "area")
{
double area = GetArea(n);
Console.WriteLine($"{area:f2}");
}
else if (type == "volume")
{
double volume = GetVolume(n);
Console.WriteLine($"{volume:f2}");
}
}
private static double GetVolume(double n)
{
double volume = Math.Pow(n, 3);
return volume;
}
private static double GetArea(double n)
{
double area = 6 * Math.Pow(n, 2);
return area;
}
private static double GetSpace(double n)
{
double space = Math.Sqrt(3* Math.Pow(n,2));
return space;
}
private static double GetFace(double n)
{
double face = Math.Sqrt(2 * Math.Pow(n,2));
return face;
}
}
}
<file_sep>/Geometry-Calculator/Geometry-Calculator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Geometry_Calculator
{
class Program
{
static void Main(string[] args)
{
string type = Console.ReadLine();
if (type == "triangle")
{
double side = double.Parse(Console.ReadLine());
double height = double.Parse(Console.ReadLine());
Console.WriteLine($"{(side*height)/2:f2}");
}
if (type == "square")
{
double side = double.Parse(Console.ReadLine());
Console.WriteLine($"{side*side:f2}");
}
if (type == "circle")
{
double radius = double.Parse(Console.ReadLine());
Console.WriteLine($"{Math.PI*Math.Pow(radius,2):f2}");
}
if (type == "rectangle")
{
double width = double.Parse(Console.ReadLine());
double height = double.Parse(Console.ReadLine());
Console.WriteLine($"{width*height:f2}");
}
}
}
}
<file_sep>/Numbers-in-Revers/Numbers-in-Reverse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Numbers_in_Reverse
{
class Program
{
static void Main(string[] args)
{
string reverse = null;
int Length = 0;
string str = Console.ReadLine();
Length = str.Length - 1;
while (Length>=0)
{
reverse = reverse + str[Length];
Length--;
}
Console.WriteLine(reverse);
}
}
}
<file_sep>/Primes-in-a-Given-Range/Primes-in-a-Given-Range.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Primes_in_a_Given_Range
{
class Program
{
static void Main(string[] args)
{
int startingValue, stoppingValue;
startingValue = Convert.ToInt32(Console.ReadLine());
stoppingValue = Convert.ToInt32(Console.ReadLine());
for (int i = startingValue; i <= stoppingValue; i++)
{
bool isPrime = true;
for (int j = 2; j <= Math.Sqrt(i); j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (i == 0 || i == 1)
{
i++;
}
else if (isPrime)
{
Console.Write(i + ", ");
}
}
}
}
}
<file_sep>/Hello-Name/Hello-Name.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hello_Name
{
class Program
{
static void Main(string[] args)
{
string name = Console.ReadLine();
string helloName = printName(name);
Console.WriteLine(helloName);
}
private static string printName(string name)
{
name = $"Hello, {name}!";
return name;
}
}
}
<file_sep>/Center-Point/Center-Point.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Center_Point
{
class Program
{
static void Main(string[] args)
{
double x1 = double.Parse(Console.ReadLine());
double y1 = double.Parse(Console.ReadLine());
double x2 = double.Parse(Console.ReadLine());
double y2 = double.Parse(Console.ReadLine());
double dist1 = CalculateDist(x1, y1);
double dist2 = CalculateDist(x2, y2);
var list = new List<double>();
if (dist1 >= dist2)
{
list.Add(x2);
list.Add(y2);
}
else
{
list.Add(x1);
list.Add(y1);
}
Console.Write("(");
Console.Write(string.Join(", ", list));
Console.Write(")");
}
private static double CalculateDist(double x, double y)
{
double dist = Math.Sqrt(Math.Pow(x,2) + Math.Pow(y,2));
return dist;
}
}
}
| 436ef37776b75c9b2fa104980bcea111aa98edee | [
"C#"
] | 8 | C# | bobiandreev/Methods-And-Debugging-Exercises | 46695559102ad053fb1f77d05157e82767d6f43a | 84faf79818da14cc0195a1b82debb48286624df0 |
refs/heads/master | <repo_name>python-learner123/mypythonlearning123<file_sep>/everything_everywhere.py
#/usr/bin/python
import os
import fnmatch
import sys
# * matches everything
# ? matches any single character
# [seq] matches any character in seq
# [!seq] matches any character not in seq
scriptname=sys.argv[0]
count=0
try:
path=sys.argv[1]
filematch=sys.argv[2]
except IndexError as err:
print("Please pass two argument as input for script, As example following:")
print(f'{scriptname} "C:\3781\Projects\Production_file\" "*msi"')
raise
for dir, dir_mid, files in os.walk(path):
for filename in files:
if fnmatch.fnmatch(filename, filematch):
print(os.path.join(dir, filename))
count=count+1
print(f"--------- Total {count} files available --------")
| d86f42120934aa4bf7add04511d61e1744088e90 | [
"Python"
] | 1 | Python | python-learner123/mypythonlearning123 | 696c2d6c9391673e2b12232a0f5b69a6bdd053e0 | aa1f2a64c98e5a7a8a1ec3bce8ed1e9c26cd38cc |
refs/heads/master | <file_sep># PHP-Ports-Checker
A simple port checker tool in php
<file_sep><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<center><br><br><form action="" method="GET">
<input type="text" name="w" placeholder="ip / web address">
<input type="text" name="p" placeholder="ports">
<input type="submit" value="check">
</form>
<?php
error_reporting(0);
$w = $_GET['w'];
$p = $_GET['p'];;
if(fsockopen($w,$p))
{
echo "I can see port <font color='green'>$p</font> on web <font color='green'>$w</font>";
}
else
{
echo "I cannot see port <font color='red'>$p</font> on web <font color='red'>$w</font>";
}
?>
| 4cb1159466fbea7442ddef48eea26ebb4900f391 | [
"Markdown",
"PHP"
] | 2 | Markdown | MEGAMINDMK/PHP-Ports-Checker | ed956c5c3449e1f649951b31ddf863e58ce8df53 | 10d4268f44b080086968cc9e3da6e89f84cb010f |
refs/heads/master | <repo_name>FunPythonEC/xl320_upy<file_sep>/test/main.py
from xl320 import *
import time
dxl = xl320(baudrate=1000000, serialid=0)
dxl.set_control_mode(1, 1)
while True:
dxl.goal_speed(1, 500)
time.sleep(3)
dxl.goal_speed(1, 1500)
time.sleep(3)
<file_sep>/README.md
# Dynamixel XL-320 uPy (MicroPython)
Los scripts en este repositorio han sido creados a partir del siguiente: https://github.com/MultipedRobotics/pyxl320
Se encuentra aquí el script de `xl320.py`, el cual contiene la clase `xl320`, los metodos y funciones necesarios para poder dar uso de los motores dynamixel xl320 eficaz y rapidamente con MicroPython, especificamente para los microcontroladores ESP8266 y ESP32.
## Hardware
Debido a que los microcontroladores ESP soportan una comunicación por UART mientras los motores Dynamixel es OneWire, es necesario un hardware especifico que te permita esta interfaz para la comunicación de los distintos protocolos, para ello se esta diseñando en el siguiente repositorio el hardware necesario: [OpenFPy](https://github.com/FunPythonEC/OpenFpy)
## Comunicación con el motor
Para la comunicación se utiliza UART. A pesar de que los motores dynamixel para la comunicación utilizan un pin DATA, este puede ser manejado utilizando la siguiente configuración electrónica: [UART to 1-WIRE interface](https://hackaday.com/2015/01/29/easier-uart-to-1-wire-interface/)
Para su uso en la parte de programación, se ha especificado en el constructor de `xl320()`, el id de UART a usar que es especificado como serialid, ya que ciertas placas carecen de cierta cantidad de objetos UART para crear. Correspondiendo entonces serialid al numero de UART usado en el microcontrolador. Para más información de UART con uPy: [UART MicroPython](https://docs.micropython.org/en/latest/library/machine.UART.html)
### Nota
A pesar de que para controlar el motor se puede utilizar la configuracion de [UART to 1-WIRE interface](https://hackaday.com/2015/01/29/easier-uart-to-1-wire-interface/), para tener un sistema más robusto se ha utilizado lo siguiente [Robotis TTL Communication](http://emanual.robotis.com/docs/en/dxl/x/xl320/#ttl-communication). Para esta es necesario especificar la dirección en que se envian datos. Para lo cual en la clase `xl320()`se especifica un pin de dirección con el cual poder manejar si se envia o se recibe datos al ESP, lo cual es sumamente necesario para la lectura.
## Video
[Moviendo un Dynamixel XL320 con un ESP-01](https://drive.google.com/file/d/1Kv3WGl3ykeTJ5h9S8OCWee8K0cMC2VE8/view?usp=sharing)
## `XL320.PY`
En este script se ha incluido todo lo necesario para poder hacer uso del motor. En este se puede encontrar la clase `xl320` con su respectivo constructor y metodos. Su uso es especificado a continuación
### Diagrama Interfaz UART-To-1Wire

### Constructor
~~~~ python
xl320(self, dir_com, baudrate=1000000, serialid=2)
~~~~
* dir_com: debido a la interface de UART-1Wire, para prevenir el fallo de lectura se utiliza un pin que especifica en que dirección se transmiten los datos, que es especificado con esta variable, que basicamente representa el pin con el que se manejara la dirección.
* baudrate: define los baudios con el cual se utilizará el motor
* serialid: define que pines tx, rx del ESP se usaran, por default UART(2)
Tener en cuenta que hay valores especificados como default en el constructor de la clase, por lo que si se quiere unos distintos, este debe ser especficado. Además se permite la creación de distintos objetos para el uso de motores, en el caso del ESP32 se permite hasta 3 lineas de motores. Para el ESP8266 tan solo 2. Con linea de motores, se refiere a motores conectados en serie en distintos buses.
#### Ejemplo de inicialización de objeto
~~~~ python
from xl320 import *
dxl=xl320(dir_com=22) #dir_com=22 es la
~~~~
Si se desea especificar el baudrate o el serial uart a usar:
~~~~ python
from xl320 import *
dxl=xl320(dir_com=22,baudrate=15200,serialid=1)
~~~~
### Métodos
Para la clase se han creado una serie de metodos especificos para su uso. En los cuales se usan funciones encontradas en el mismo script. Como le() y makePacket().
Los metodos especificos, son para el control sobre el ID, baudrate, goal speed, present speed, etc. Pero también se agrego un metodo llamado sendPacket() el cual es un método genérico, este es más detallado en la próxima sección.
#### Genéricos
##### sendPacket()
Este metodo del objeto, esta principalmente para poder enviar por UART, un paquete propio creado.
Para la creación de un paquete se puede usar el metodo de `makePacket(ID, instr, reg=None, params=None)`, el cual regresa un array con los valores a enviar por serial.
###### Ejemplo
~~~~ python
from xl320 import *
dxl=xl320(dir_com=22)
#cambio de id, de 1 a 2
pkt=makePacket(1,WRITE,XL320_ID,[2])
~~~~
Tener en cuenta que en el ejemplo anterior, se hace un cambio de id, el cual es un registro al cual le corresponde 1 byte, por lo que en el metodo basta con poner como parametro [2], mientras que si este fuera de 2 bytes, se tendria que usar el metodo le() que se encuentra en el mismo script. Basicamente el metodo le() se encarga de representar un numero mayor a 255 en dos bytes.
#### Especificos de escritura
##### EEPROM
Tener en cuenta que para que el EEPROM sea modificable, es necesario que TORQUE_ENABLE tenga 0 como valor, si es cambiado a 1, EEPROM no puede ser modificado.
|Metodo|¿Qué hace?|Descripcion de parametros|
|-----------|-----------|--------------------------------------|
|set_control_mode(ID, mode)|Ayuda a setear el modo de control del motor.|**ID**: corresponde al id del motor al cual se le quiere cambiar el modo. Puede ser un valor desde 1 hasta 253. **mode**: puede ser 1 o 2. 1 para el modo WHEEL y 2 para JOINT|
|set_id(ID,newID)|Ayuda a cambiar o setear un id nuevo a uno de los motores.|**ID**: es el id del motor al que se le cambiara. **newID**: es el nuevo ID que se sobreescribira|
|set_baudrate(ID,baudrate)|Seteo de baud rate a uno de los motores.|**baudrate**:los valores van desde 0 a 3. Cada uno especificando un valor de baudios tal y como se muestra en la documentación del motor, que puede ser desde 9600 hasta 1000000.|
|set_cw_angle_limit(ID,angle)|Seteo de ángulo límite para el movimiento del motor en sentido horario.|**angle**: en este caso, por las capacidades del motor xl320, el valor de angulos para el cual permite el giro funcionando como un servo motor (JOINT mode) es desde 0 hasta 300 grados.|
|set_ccw_angle_limit(ID, angle)|Seteo de ángulo límite para el movimiento del motor en sentido antihorario.|**angle**: en este caso, por las capacidades del motor xl320, el valor de angulos para el cual permite el giro funcionando como un servo motor (JOINT mode) es desde 0 hasta 300 grados.|
|set_max_torque(ID,torque)|Seteo de torque máximo que puede ejercer el motor.|**torque**: el valor puede variar de 0 a 1023, siendo 1023 el máximo de torque que es capaz de ejercer el motor.|
##### RAM
|Metodo|¿Qué hace?|Descripción de parámetros|
|:-----------|------------|---------------------------------------|
|torque_enable(ID,status)|Deshabilita o habilita el torque.|**status**: el valor puede ser 1 (wheel mode) o 2 (joint mode).|
|goal_speed(ID,speed)|Pone una velocidad definida a la que se mueva el motor, funciona diferente dependiendo del modo de control en el que se encuentre.|**speed**: (JOINT) para este caso speed se refiere a la velocidad a la que girará el motor cuando se le especifique un ángulo, su valor puede ser entre 0-1023. (WHEEL) en este caso, se refiere a la velocidad a la que se quiere que se mueva el motor actualmente, su valor puede ser entre 0-2047. 0-1023 para que gire en un sentido. 1024-2047 para el otro.|
|goal_position(ID,position)|Coloca al motor en una posición definida que se da por el ángulo como posición.|**position**: corresponde al ángulo en que se quiere que se ponga el motor.|
|goal_torque(ID, torque)|Setea el torque en un valor definido.|**torque**: su valor es entre 0-1023, siendo 1023 el valor máximo.|
#### Especificos de lectura
Todos los metodos de lectura tiene como parámetro nada más que el ID, por lo que no se explica a continucación, solo que hace cada metodo.
Tener en cuenta que todos los metodos de lectura, al usarlos, por ahora imprimen todo lo que le llega al microcontrolador. Se tiene que entonces identificar que generalmente el unico print que se mostraría es lo que envia como respuesta el motor. Lo cual correspondera a un paquete del cual se tendrá que identificar los valores regresados.
##### EEPROM
| Metodos | ¿Qué hace? |
| ------------------------ | ------------------------------------------------------------ |
| read_model_number(ID) | Lectura el numero de modelo del motor. |
| read_firmware(ID) | Lectura el firmware que tiene el motor. |
| read_baudrate(ID) | Lectura el valor de baud rate con el que esta trabajando el motor para la comunicación. |
| read_delay_time(ID) | Lectura el tiempo de delay entre escritura y respuesta. **Todavia no esta implementado el metodo para el cambio de delay time** |
| read_cw_angle_limit(ID) | Lectura de angulo limite para el giro horario. |
| read_ccw_angle_limit(ID) | Lectura de angulo limite para el giro anti-horario. |
| read_control_mode(ID) | Lectura de modo de control actual. |
| read_max_torque(ID) | Lectura de torque máximo al cual ha sido seteado el motor. |
| read_return_level(ID) | Lectura de nivel de retorno en el motor. |
##### RAM
| Metodos | ¿Qué hace? |
| ---------------------------- | ------------------------------------------------------------ |
| read_torque_enable(ID) | Lectura del estado de torque, si esta activado o no. |
| read_goal_torque(ID) | Lectura de el valor de torque al que se haya seteado el motor. |
| read_goal_speed(ID) | Lectura del valor de goal speed puesto. |
| read_present_position(ID) | Lectura de la posición actual del motor. |
| read_present_speed(ID) | Lectura de la velocidad actual del motor. |
| read_present_load(ID) | Lectura del peso o fuerza ejercida por el motor. |
| read_present_voltage(ID) | Lectura del voltage presente suministrado al motor. |
| read_present_temperature(ID) | Lectura de temperatura actual del motor. |
| read_moving(ID) | Lectura de estado del motor, para saber si esta o no en movimiento. |
| read_hw_error_status(ID) | Lectura de estado de error de hardware. |
| read_goal_position(ID) | Lectura de valor de goal position indicado. |
| read_punch(ID) | Lectura de minima corriente suministrada al motor. |
## Referencias
* [XL320 Dynamixel](http://emanual.robotis.com/docs/en/dxl/x/xl320/)
* [XL320 Dynamixel Further Documentation](http://support.robotis.com/en/product/actuator/dynamixel_x/xl_series/xl-320.htm)
* [CRC Calculator](http://support.robotis.com/en/product/actuator/dynamixel_pro/communication/crc.htm)
* [Instruction Packet Protocol 2.0](http://support.robotis.com/en/product/actuator/dynamixel_pro/communication/instruction_status_packet.htm)
<file_sep>/xl320.py
import machine as m # for uart use
import utime # for time control
# --------- INSTRUCTIONS -----
PING = 0x01
READ = 0x02
WRITE = 0x03
REG_WRITE = 0x04
ACTION = 0x05
RESET = 0x06
REBOOT = 0x08
STATUS = 0x55
SYNC_READ = 0x82
SYNC_WRITE = 0x83
BULK_READ = 0x92
BULK_WRITE = 0x93
# -------- EEPROM -------------
XL320_MODEL_NUMBER = 0
XL320_VER_FIRMWARE = 2
XL320_ID = 3
XL320_BAUD_RATE = 4
XL320_DELAY_TIME = 5
XL320_CW_ANGLE_LIMIT = 6 # min angle, default 0
XL320_CCW_ANGLE_LIMIT = 8 # max angle, default 300
XL320_CONTROL_MODE = 11 # joint or wheel mode, default joint (servo)
XL320_MAX_TORQUE = 15
XL320_RETURN_LEVEL = 17
# -------- RAM ----------------
XL320_TORQUE_ENABLE = 24 # servo mode on/off - turn into wheel
XL320_LED = 25
XL320_GOAL_POSITION = 30
XL320_GOAL_VELOCITY = 32
XL320_GOAL_TORQUE = 35
XL320_PRESENT_POSITION = 37 # current servo angle
XL320_PRESENT_SPEED = 39 # current speed
XL320_PRESENT_LOAD = 41 # current load
XL320_PRESENT_VOLTAGE = 45 # current voltage
XL320_PRESENT_TEMP = 46 # current temperature
XL320_MOVING = 49
XL320_HW_ERROR_STATUS = 50
XL320_PUNCH = 51
# --------- OTHER -------------
XL320_RESET_ALL = 0xFF
XL320_RESET_ALL_BUT_ID = 0x01
XL320_RESET_ALL_BUT_ID_BAUD_RATE = 0x02
XL320_LED_WHITE = 7
XL320_LED_BLUE_GREEN = 6
XL320_LED_PINK = 5
XL320_LED_BLUE = 4
XL320_LED_YELLOW = 3
XL320_LED_GREEN = 2
XL320_LED_RED = 1
XL320_LED_OFF = 0
XL320_BROADCAST_ADDR = 0xFE # a packet with this ID will go to all servos
XL320_WHEEL_MODE = 1
XL320_JOINT_MODE = 2 # normal servo
XL320_9600 = 0 # 0: 9600, 1:57600, 2:115200, 3:1Mbps
XL320_57600 = 1
XL320_115200 = 2
XL320_1000000 = 3
# this table is needed in order to create the ultimate two values which correspond to only
# the checksum of protocol 2.0
crc_table = [
0x0000,
0x8005,
0x800F,
0x000A,
0x801B,
0x001E,
0x0014,
0x8011,
0x8033,
0x0036,
0x003C,
0x8039,
0x0028,
0x802D,
0x8027,
0x0022,
0x8063,
0x0066,
0x006C,
0x8069,
0x0078,
0x807D,
0x8077,
0x0072,
0x0050,
0x8055,
0x805F,
0x005A,
0x804B,
0x004E,
0x0044,
0x8041,
0x80C3,
0x00C6,
0x00CC,
0x80C9,
0x00D8,
0x80DD,
0x80D7,
0x00D2,
0x00F0,
0x80F5,
0x80FF,
0x00FA,
0x80EB,
0x00EE,
0x00E4,
0x80E1,
0x00A0,
0x80A5,
0x80AF,
0x00AA,
0x80BB,
0x00BE,
0x00B4,
0x80B1,
0x8093,
0x0096,
0x009C,
0x8099,
0x0088,
0x808D,
0x8087,
0x0082,
0x8183,
0x0186,
0x018C,
0x8189,
0x0198,
0x819D,
0x8197,
0x0192,
0x01B0,
0x81B5,
0x81BF,
0x01BA,
0x81AB,
0x01AE,
0x01A4,
0x81A1,
0x01E0,
0x81E5,
0x81EF,
0x01EA,
0x81FB,
0x01FE,
0x01F4,
0x81F1,
0x81D3,
0x01D6,
0x01DC,
0x81D9,
0x01C8,
0x81CD,
0x81C7,
0x01C2,
0x0140,
0x8145,
0x814F,
0x014A,
0x815B,
0x015E,
0x0154,
0x8151,
0x8173,
0x0176,
0x017C,
0x8179,
0x0168,
0x816D,
0x8167,
0x0162,
0x8123,
0x0126,
0x012C,
0x8129,
0x0138,
0x813D,
0x8137,
0x0132,
0x0110,
0x8115,
0x811F,
0x011A,
0x810B,
0x010E,
0x0104,
0x8101,
0x8303,
0x0306,
0x030C,
0x8309,
0x0318,
0x831D,
0x8317,
0x0312,
0x0330,
0x8335,
0x833F,
0x033A,
0x832B,
0x032E,
0x0324,
0x8321,
0x0360,
0x8365,
0x836F,
0x036A,
0x837B,
0x037E,
0x0374,
0x8371,
0x8353,
0x0356,
0x035C,
0x8359,
0x0348,
0x834D,
0x8347,
0x0342,
0x03C0,
0x83C5,
0x83CF,
0x03CA,
0x83DB,
0x03DE,
0x03D4,
0x83D1,
0x83F3,
0x03F6,
0x03FC,
0x83F9,
0x03E8,
0x83ED,
0x83E7,
0x03E2,
0x83A3,
0x03A6,
0x03AC,
0x83A9,
0x03B8,
0x83BD,
0x83B7,
0x03B2,
0x0390,
0x8395,
0x839F,
0x039A,
0x838B,
0x038E,
0x0384,
0x8381,
0x0280,
0x8285,
0x828F,
0x028A,
0x829B,
0x029E,
0x0294,
0x8291,
0x82B3,
0x02B6,
0x02BC,
0x82B9,
0x02A8,
0x82AD,
0x82A7,
0x02A2,
0x82E3,
0x02E6,
0x02EC,
0x82E9,
0x02F8,
0x82FD,
0x82F7,
0x02F2,
0x02D0,
0x82D5,
0x82DF,
0x02DA,
0x82CB,
0x02CE,
0x02C4,
0x82C1,
0x8243,
0x0246,
0x024C,
0x8249,
0x0258,
0x825D,
0x8257,
0x0252,
0x0270,
0x8275,
0x827F,
0x027A,
0x826B,
0x026E,
0x0264,
0x8261,
0x0220,
0x8225,
0x822F,
0x022A,
0x823B,
0x023E,
0x0234,
0x8231,
0x8213,
0x0216,
0x021C,
0x8219,
0x0208,
0x820D,
0x8207,
0x0202,
]
# header of the packet
HEADER = [0xFF, 0xFF, 0xFD, 0x00]
# xl320 class for servo control
class xl320(object):
# constructor
def __init__(self, dir_com, baudrate=1000000, serialid=2):
self.baudrate = baudrate
self.serialid = serialid
self.dir_com = m.Pin(
dir_com, m.Pin.OUT
) # a pin for the communication direction is defined
# uart object defined
try:
self.uart = m.UART(self.serialid, self.baudrate)
self.uart.init(self.baudrate, bits=8, parity=None, stop=1)
except Exception as e:
print(e)
# generic methods to send packet -> this is a list of values
def sendPacket(self, packet):
self.dir_com.value(1)
try:
self.uart.write(bytearray(packet))
a = utime.ticks_us() # start time counting
except Exception as e:
print(e)
utime.sleep_us(325) # this is a time specified experimentally
self.dir_com.value(0)
while True:
msg = com.read()
if msg is not None and (utime.ticks_us() - a) >= 1450:
print(list(msg))
return list(msg)
if (utime.ticks_us() - a) >= 1450:
break
# --------------------------SPECIFIC WRITING METHODS------------------------------
# ==================================EEPROM=========================================
def set_control_mode(self, ID, mode): # 1 (wheel), 2 (joint)
comwrite(self.uart, self.dir_com, ID, XL320_CONTROL_MODE, [mode])
def set_id(self, ID, newID):
comwrite(self.uart, self.dir_com, ID, XL320_ID, [newID])
def set_baudrate(self, ID, baudrate):
comwrite(self.uart, self.dir_com, ID, XL320_BAUD_RATE, [baudrate])
def set_cw_angle_limit(self, ID, angle):
comwrite(
self.uart,
self.dir_com,
ID,
XL320_CW_ANGLE_LIMIT,
le(int(angle / 300 * 1023)),
)
def set_ccw_angle_limit(self, ID, angle):
comwrite(
self.uart,
self.dir_com,
ID,
XL320_CCW_ANGLE_LIMIT,
le(int(angle / 300 * 1023)),
)
def set_max_torque(self, ID, torque):
comwrite(self.uart, self.dir_com, ID, XL320_MAX_TORQUE, le(torque))
# ========================RAM======================================================
def torque_enable(
self, ID, status
): # default 0 (torque disabled), 1 (torque enabled), cuando torque enabled, eeprom es bloqueado
comwrite(self.uart, self.dir_com, ID, XL320_TORQUE_ENABLE, [status])
def goal_speed(self, ID, speed):
comwrite(self.uart, self.dir_com, ID, XL320_GOAL_VELOCITY, le(speed))
def goal_position(self, ID, position):
comwrite(
self.uart,
self.dir_com,
ID,
XL320_GOAL_POSITION,
le(int(position / 300 * 1023)),
)
def goal_torque(self, ID, torque):
comwrite(self.uart, self.dir_com, ID, XL320_GOAL_TORQUE, le(1023))
# ----------------------------SPECIFIC READING METHODS-----------------------------
# ==================================EEPROM=========================================
def read_model_number(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_MODEL_NUMBER, le(2))
return word(data[-4], data[-3])
def read_firmware(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_VER_FIRMWARE, le(1))
return data[-3]
def read_baudrate(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_BAUD_RATE, le(1))
return data[-3]
def read_delay_time(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_DELAY_TIME, le(1))
return data[-3]
def read_cw_angle_limit(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_CW_ANGLE_LIMIT, le(2))
return word(data[-4], data[-3]) * 300 / 1023
def read_ccw_angle_limit(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_CCW_ANGLE_LIMIT, le(2))
return word(data[-4], data[-3]) * 300 / 1023
def read_control_mode(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_CONTROL_MODE, le(1))
return data[-3]
def read_max_torque(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_MAX_TORQUE, le(2))
return word(data[-4], data[-3])
def read_return_level(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_RETURN_LEVEL, le(1))
return data[-3]
# =================================RAM===============================================
def read_torque_enable(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_TORQUE_ENABLE, le(1))
return data[-3]
def read_goal_torque(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_GOAL_TORQUE, le(2))
return word(data[-4], data[-3])
def read_goal_position(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_GOAL_POSITION, le(2))
return word(data[-4], data[-3]) * 300 / 1023
def read_goal_speed(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_GOAL_VELOCITY, le(2))
return word(data[-4], data[-3])
def read_present_position(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_PRESENT_POSITION, le(2))
return word(data[-4], data[-3]) * 300 / 1023
def read_present_speed(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_PRESENT_SPEED, le(2))
return word(data[-4], data[-3])
def read_present_load(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_PRESENT_LOAD, le(2))
return word(data[-4], data[-3])
def read_present_voltage(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_PRESENT_VOLTAGE, le(1))
return data[-3]
def read_present_temperature(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_PRESENT_TEMP, le(1))
return data[-3]
def read_moving(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_MOVING, le(1))
return data[-3]
def read_hw_error_status(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_HW_ERROR_STATUS, le(1))
return data[-3]
def read_punch(self, ID):
data = comread(self.uart, self.dir_com, ID, XL320_PUNCH, le(2))
return word(data[-4], data[-3])
# ================================OTHER METHODS====================================
def reset_all(self, ID):
comwrite(self.uart, self.dir_com, ID, [XL320_RESET_ALL])
def reset_all_id(self, ID):
comwrite(self.uart, self.dir_com, ID, [XL320_RESET_ALL_BUT_ID])
def reset_all_id_baud(self, ID):
comwrite(self.uart, self.dir_com, ID, [XL320_RESET_ALL_BUT_ID_BAUD_RATE])
# ===============================GENERIC METHODS==================================
# creacion del paquete de escritura y envio
# package creation, about write instruction
def comwrite(com, dir_com, ID, reg=None, params=None):
dir_com.value(1)
try:
pkt = bytearray(makePacket(ID, WRITE, reg, params))
com.write(pkt)
a = utime.ticks_us()
except Exception as e:
print(e)
utime.sleep_us(325)
dir_com.value(0)
while True:
msg = com.read()
if msg is not None:
print(list(msg))
return list(msg)
if (utime.ticks_us() - a) >= 1450:
break
# package creation, send and receive
def comread(com, dir_com, ID, reg, length):
dir_com.value(1)
try:
pkt = bytearray(makePacket(ID, READ, reg, length))
com.write(pkt)
except Exception as e:
print(e)
utime.sleep_us(325)
dir_com.value(0)
a = utime.ticks_us()
data = []
while True:
msg = com.read(13)
if msg is not None:
data += list(msg)
try:
if data[5] == (len(data) - 7):
print(data)
return data
except:
if (utime.ticks_us() - a) >= 2000:
break
def makePacket(ID, instr, reg=None, params=None):
"""
This makes a generic packet.
TODO: look a struct ... does that add value using it?
0xFF, 0xFF, 0xFD, 0x00, ID, LEN_L, LEN_H, INST, PARAM 1, PARAM 2, ..., PARAM N, CRC_L, CRC_H]
in:
ID - servo id
instr - instruction
reg - register
params - instruction parameter values
out: packet
"""
pkt = []
pkt += HEADER # header and reserved byte
pkt += [ID]
pkt += [0x00, 0x00] # length placeholder
pkt += [instr] # instruction
if reg:
pkt += le(reg) # not everything has a register
if params:
pkt += params # not everything has parameters
length = le(len(pkt) - 5) # length = len(packet) - (header(3), reserve(1), id(1))
pkt[5] = length[0] # L
pkt[6] = length[1] # H
crc = crc16(pkt)
pkt += le(crc)
print(pkt)
return pkt
# util function?
def le(h):
"""
Little-endian, takes a 16b number and returns an array arrange in little
endian or [low_byte, high_byte].
"""
h &= 0xFFFF # make sure it is 16 bits
return [h & 0xFF, h >> 8]
def word(l, h):
"""
Given a low and high bit, converts the number back into a word.
"""
return (h << 8) + l
def crc16(data_blk):
"""
Calculate crc
in: data_blk - entire packet except last 2 crc bytes
out: crc_accum - 16 word
"""
data_blk_size = len(data_blk)
crc_accum = 0
for j in range(data_blk_size):
i = ((crc_accum >> 8) ^ data_blk[j]) & 0xFF
crc_accum = (crc_accum << 8) ^ crc_table[i]
crc_accum &= 0xFFFF # keep to 16 bits
return crc_accum
| b125af8b7a557b0334afe030d13f2b6696bda24f | [
"Markdown",
"Python"
] | 3 | Python | FunPythonEC/xl320_upy | 947880f1f6c97d12607a5eddf8efae0a5cbf3969 | 4ec2a47110a7eebb01306dfe69f00ad0e03fb567 |
refs/heads/master | <file_sep>package tera.prog;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
// Program entry point
public static void main(String[] args) {
run();
}
// Main run function
private static void run() {
System.out.print("Enter file path: ");
String filePath = getUserInput();
String[] fileContent = parseFile(filePath);
List<Integer> integerFileContent = new ArrayList<Integer>();
for (String string : fileContent)
integerFileContent.add(Integer.parseInt(string.trim()));
Collections.sort(integerFileContent);
System.out.print("Enter nth digit: ");
String nthDigitStr = getUserInput();
int nthDigit = Integer.parseInt(nthDigitStr.trim());
if (nthDigit >= integerFileContent.size())
System.out.println("No such nth digit exits.");
else
System.out.println(integerFileContent.get(nthDigit - 1));
}
// Gets the user's input
private static String getUserInput() {
Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextLine();
if (userInput != null)
return userInput;
else
return null;
}
// Collects content of file and returns it as an array
private static String[] parseFile(String path) {
String[] content = null;
try (BufferedReader reader = new BufferedReader(new FileReader(new File("./src/" + path)))) {
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
builder.append(line).append("\n");
content = builder.toString().split(" ");
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
<file_sep># Hopson-Programming-Challenge
A program that finds the NTH smallest digit in an array. Written for the 19 Sept 2018 Hopson Programming Challenge
| 1ad45f5ef047ff8853d031511fd57a526325e169 | [
"Markdown",
"Java"
] | 2 | Java | Terabyte04/Hopson-Programming-Challenge | 1878d42b0cbef2bdf1a4876b459328175796e139 | 95308fb86c65ce87e3f827d109e5fb3951b68dff |
refs/heads/main | <file_sep>############################################################
# CIS 521: Sudoku Homework
############################################################
student_name = "<NAME>"
############################################################
import collections
from copy import deepcopy
############################################################
# Include your imports here, if any are used.
############################################################
# Section 1: Sudoku Solver
############################################################
def sudoku_cells():
ls=[]
for i in range(9):
for j in range(9):
ls.append((i,j))
return ls
# return list of all arcs which need to follow constraints
# row, col, subgrid
def sudoku_arcs():
ls=[]
for i in range(9):
for j in range(9):
p=(i,j)
for m in range(9):
if m !=i:
ls.append((p,(m,j)))
if m!=j:
ls.append((p,(i,m)))
for sub1 in range(int(i/3)*3,int(i/3)*3+3):
for sub2 in range(int(j/3)*3,int(j/3)*3+3):
if sub1 != i or sub2 !=j:
ls.append((p,(sub1,sub2)))
ls =list(set(ls))
# set 会过滤掉重复的值
return ls
def read_board(path):
dic={}
i=0
j=0
l=set(list((1,2,3,4,5,6,7,8,9)))
with open(path) as f:
lines=f.read().split()
for line in lines:
for word in line:
if word=='*':
dic[(i,j)]=l
else:
dic[(i,j)]=set([int(word)])
j=(j+1)%9
i=(i+1)%9
return dic
class Sudoku(object):
CELLS = sudoku_cells()
ARCS = sudoku_arcs()
def __init__(self, board):
self.board=board
def get_values(self, cell):
return self.board[cell]
def remove_inconsistent_values(self, cell1, cell2):
## 这里的constraint是同一行、同一列、同一个subgrid不能有相同值
inconsistent_values=set()
ls1=list(self.board[cell1])
ls2=list(self.board[cell2])
# todo: check cell2
# 如果 y中没有一个值满足contraint,就不是arc-consistent
if len(ls2)>1:
return False
else:
for i in ls1:
for j in ls2:
if i == j:
inconsistent_values.add(i)
ls1.pop(ls1.index(i))
self.board[cell1]=set(ls1)
return len(inconsistent_values)>0
def infer_ac3(self):
queue=collections.deque(Sudoku.ARCS)
while queue:
c1,c2=queue.pop()
if self.remove_inconsistent_values(c1,c2):
if self.board[c1] ==():
return False
# if x_i is removed/revised, add (X_k,X_i)
# into agenda/queue
for arc in Sudoku.ARCS:
if arc[1]==c1 and arc[0]!=c2:
queue.append(arc)
return self.board
def check_unique(self,cell,val):
for i in range(9):
if i!=cell[1]:
if val in self.board[(cell[0],i)]:
return False
if i!=cell[0]:
if val in self.board[(i,cell[1])]:
return False
for sub1 in range(int(cell[0] / 3) * 3, int(cell[0] / 3) * 3 + 3):
for sub2 in range(int(cell[1]/ 3) * 3, int(cell[1] / 3) * 3 + 3):
if sub1 != cell[0] or sub2 != cell[1]:
if val in self.board[(sub1,sub2)]:
return False
return True
#cell is position
#i is the position value
def infer_improved(self):
made_additional_inference=True
while made_additional_inference:
#todo: check the status of self.infer_ac3
# if it is empty, the process fails
self.infer_ac3()
made_additional_inference = False
for cell in Sudoku.CELLS:
a=list(self.board[cell])
if len(a)>1:
# todo: the standard of uniqueness: how to check the value of cell
for i in a:
if self.check_unique(cell,i):
self.board[cell]=set([i])
made_additional_inference = True
break
return self.board
def is_solved(self):
for cell in self.CELLS:
a=list(self.board[cell])
if len(a)!=1:
return False
else:
if not self.check_unique(cell,a[0]):
return False
return True
def infer_with_guessing(self):
self.infer_improved()
for cell in Sudoku.CELLS:
a = list(self.board[cell])
if len(a)>1:
for i in a:
p=deepcopy(self)
p.board[cell]=set([i])
p.infer_improved()
if p.is_solved():
self.board=p.board
return self.board
break
else:
p.infer_with_guessing()
break
return self.board
sudoku = Sudoku(read_board("sudoku/hard1.txt"))
# See below for a picture.
for i in range(9):
for j in range(9):
if i !=0:
removed = sudoku.remove_inconsistent_values((0, 4), (i, 4))
print(sudoku.board[(i,4)], sudoku.get_values((0, 4)))
if i!=4:
removed = sudoku.remove_inconsistent_values((0, 4), (0, i))
print(sudoku.board[(0,i)], sudoku.get_values((0, 4)))
for sub1 in range(int(0 / 3) * 3, int(0/ 3) * 3 + 3):
for sub2 in range(int(4 / 3) * 3, int(4/ 3) * 3 + 3):
if sub1 != 0 or sub2 != 4:
removed = sudoku.remove_inconsistent_values((0, 4), (sub1,sub2))
print(sudoku.board[(sub1,sub2)], sudoku.get_values((0, 4)))
# b=sudoku.is_solved()
# print(a)
# print(b)
############################################################
# Section 2: Feedback
############################################################
# Just an approximation is fine.
feedback_question_1 = 10
feedback_question_2 = """
the second question
"""
feedback_question_3 = """
It introduces how to solve Sudoku
"""
| b3d751d8a61b83615d65be061c6c5dec52c8aeff | [
"Python"
] | 1 | Python | avniahuja2000/hw1 | 847446078a12af5cff214c473321a555b84032fa | b5019cd55aa61a18ce23fc0e877950d27542e526 |
refs/heads/master | <repo_name>rmustafa/pagination<file_sep>/README.md
# pagination
Example pagination implementation for collections
You can use maven for this project like
```
mvn test
```
<file_sep>/src/main/java/com/rmustafa/paginate/Pagination.java
package com.rmustafa.paginate;
public class Pagination {
public static void main(String args[]) {
}
}
<file_sep>/src/main/java/com/rmustafa/paginate/PaginationService.java
package com.rmustafa.paginate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.IntStream;
/**
* Example pagination model for {@link Collection}
*
* @param <T> Model for pagination
*/
public class PaginationService<T> {
PaginationService() {
}
/**
* Assuming the nextPage, previousPage, hasNext, hasPrevious methods are implemented,
* this method stands for getting requested page.
*
* @param page {@link Integer} page [1..n]
* @param pageSize {@link Integer} element count that a page contains.
* @return {@link Collection} of requested page.
*/
public Collection<T> getPage(int page, int pageSize, Collection<Result> list) {
if (page == 0 || list == null || list.size() == 0) return null;
int handledPageSize = pageSize <= 0 ? 20 : pageSize;
ArrayList<T> pageResults = new ArrayList<>();
ArrayList<T> arrayList = (ArrayList<T>) list;
--page;
IntStream.range(page * handledPageSize, page * handledPageSize + handledPageSize)
.forEach(index -> pageResults.add(arrayList.get(index)));
return pageResults;
}
}
<file_sep>/src/test/java/com/rmustafa/paginate/PageableTest.java
package com.rmustafa.paginate;
import org.junit.Test;
import java.util.ArrayList;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class PageableTest {
@Test
public void test_null_results() {
PaginationService service = new PaginationService();
assertNull(service.getPage(1, 11, null));
assertNull(service.getPage(1, 11, new ArrayList<>()));
}
@Test
public void test_pagination() {
ArrayList<Result> list = new ArrayList<>();
for(int i = 1; i < 112; i++) {
String identifier = i + "";
list.add(new Result(identifier, identifier, identifier));
}
PaginationService service = new PaginationService();
int pageSize = 11, page = 1;
ArrayList<Result> pageResults = (ArrayList<Result>)service.getPage(page, pageSize, list);
assertEquals(pageSize, pageResults.size());
IntStream.range(0, pageResults.size()).forEach(index -> {
assertEquals(((page - 1) * pageSize + index + 1) + "", pageResults.get(index).getTitle());
});
}
}
| 4f3a2a7d6a3e32eda929f8b66dc419bc5a2a806f | [
"Markdown",
"Java"
] | 4 | Markdown | rmustafa/pagination | a3f342b6f2211295b431c4aac0ea72191045af3d | 602e34eefebba5cb5de407770541652181f2da6e |
refs/heads/master | <file_sep>import React from 'react';
import { IndexRoute, Router, Route, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { App, Note, History } from './containers';
const Home = () => <div>Home</div>
const getRoutes = (store) => (
<Router history={syncHistoryWithStore(browserHistory, store)}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="note" component={Note} />
<Route path="history" component={History} />
</Route>
</Router>
)
export default getRoutes
<file_sep># saving-money-firebase
History of money usage with firebase
*This project is experiment how react and redux working with firebase.*
## Development
- `yarn` or `npm install`
- `npm start`
<file_sep>import { createStore, compose } from 'redux'
import { reduxReactFirebase } from 'redux-react-firebase'
import rootReducer from './reducers';
const config = {
apiKey: "<KEY>",
authDomain: "saving-money.firebaseapp.com",
databaseURL: "https://saving-money.firebaseio.com",
storageBucket: "saving-money.appspot.com",
messagingSenderId: "335518301516"
};
const createStoreWithFirebase = compose(
reduxReactFirebase(config),
)(createStore)
const store = createStoreWithFirebase(rootReducer);
export default store;
<file_sep>import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';
import 'rc-time-picker/assets/index.css';
import TimePicker from 'rc-time-picker';
import './Note.css';
import cn from 'classnames';
import { connect } from 'react-redux'
import { firebase, helpers } from 'redux-react-firebase';
const { dataToJS } = helpers
// @firebase([
// 'myaccount'
// ])
// @connect(
// ({ firebase }) => ({
// myaccount: dataToJS(firebase, 'myaccount'),
// })
// )
class Note extends Component {
constructor() {
super();
this.state = {
time: moment(),
transaction: 'income'
};
}
onSubmit() {
const data = {
type: this.state.transaction,
price: +this.refs.price.value || 0,
name: this.refs.name.value,
time: this.state.time.valueOf(),
// transaction: this.state.transaction
}
this.props.firebase.push('myaccount', data, () => {
console.log('[submit]', data)
});
}
handleChange(value) {
this.setState({
time: value
});
}
toggleTransactionType() {
this.setState({
transaction: this.state.transaction === 'income' ? 'expense' : 'income'
})
}
render() {
return (
<div className="row">
<div className="col-md-12">
<h1>Note</h1>
<div>
<div className="form-group">
<label>Type: </label>
<button type="button" className={cn('btnType', 'btn', {
'btn-success': this.state.transaction === 'income',
'btn-danger': this.state.transaction === 'expense'
})} onClick={this.toggleTransactionType.bind(this)}>{this.state.transaction}</button>
</div>
<div className="form-group">
<label>Price</label>
<input ref="price" type="number" className="form-control" defaultValue={0} min={0} />
</div>
<div className="form-group">
<label>Name</label>
<input ref="name" type="text" className="form-control"/>
</div>
<div className="form-group">
<label>Date</label><br/>
<DatePicker
className="form-control"
selected={this.state.time}
onChange={this.handleChange.bind(this)}
/>
</div>
<div className="form-group">
<label>Time</label><br/>
<TimePicker
className="time-picker"
defaultValue={this.state.time}
onChange={this.handleChange.bind(this)}
showSecond={false}
/>
</div>
<button className="btn btn-primary" onClick={this.onSubmit.bind(this)}>Save</button>
</div>
</div>
</div>
);
}
}
export default connect(
({ firebase }) => ({
myaccount: dataToJS(firebase, 'myaccount')
})
)(
firebase([
'myaccount'
])(Note)
);
<file_sep>import { combineReducers } from 'redux'
import { firebaseStateReducer } from 'redux-react-firebase'
import { routerReducer } from 'react-router-redux'
export default combineReducers({
firebase: firebaseStateReducer,
routing: routerReducer
});
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { firebase, helpers } from 'redux-react-firebase';
const { dataToJS } = helpers;
import _ from 'lodash';
class History extends Component {
renderTransaction({ name, type, price, time }, id) {
return (
<tr key={id}>
<td>{name}</td>
<td>{type}</td>
<td>{price}</td>
<td>{time}</td>
</tr>
);
}
renderTransactions() {
return (
_.map(this.props.transactions, (transaction, id) => (
this.renderTransaction(transaction, id)
))
);
}
render() {
return (
<table className="table table-striped">
<thead>
<tr>
<th>name</th>
<th>type</th>
<th>price</th>
<th>time</th>
</tr>
</thead>
<tbody>{this.renderTransactions()}</tbody>
</table>
);
}
}
export default connect(
({ firebase }) => ({
transactions: dataToJS(firebase, '/myaccount')
})
)(
firebase([
['/myaccount']
])(History)
);
<file_sep>import App from './App';
import Note from './Note';
import History from './History';
export {
App,
Note,
History
}
| 1f7b7d8e363aca60b1b222b2af4ab0b6f79d649b | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | zugarzeeker/saving-money-firebase | 6b60bba23d8ca9ac75c48187f1cf07423be864c6 | f9569df5726b4612191c2a7043dc657c128528f4 |
refs/heads/master | <file_sep>const reviewsRouter = require('express').Router();
const Review = require('../models/review');
reviewsRouter.get('/', async (req, res) => {
const auth = req.currentUser;
if (auth){
const reviews = await Review.find({});
return res.json(reviews.map((review) => review.toJSON()));
}
return res.status(403).send('Not Authorized!');
});
reviewsRouter.post('/', (req, res) => {
auth = req.currentUser;
if (auth){
const review = new Review(res.body);
const savedReview = review.save();
// console.log('authenticated!', auth)
// return res.status('Hi, from within the reviews router POST');
return res.status(201).json(savedReview);
}
return res.status(403).send('Not Authorized');
});
module.exports = reviewsRouter;
<file_sep>const mongoose = require('mongoose');
const reviewSchema = new mongoose.Schema({
volume: String,
reviewer: String,
number: String
});
reviewSchema.set('toJSON', {
transform: (doc, returnedObject) => {
returnedObject.id = returnedObject._id.toString();
delete returnedObject._id;
delete returnedObject._v;
},
});
module.exports = mongoose.model('Review', reviewSchema);
| 51d8b18d91dcc7d8adf7baf1fa7950289bb3237c | [
"JavaScript"
] | 2 | JavaScript | JonWash86/book-bug-backend | 08b73864a990836bc0030aea1725c2c1fb9f63ce | 51a5b313ab87275a6fb88aae0948f35dd2006bc5 |
refs/heads/master | <repo_name>basith374/react-print-test<file_sep>/src/App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import PrintTemplate from 'react-print';
import ReactDOM from 'react-dom';
class MyTemplate extends React.Component {
componentDidMount() {
new window.google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
render() {
return (
<PrintTemplate>
moozie
<div id="map"></div>
foozi
</PrintTemplate>
)
}
}
class App extends Component {
componentDidMount() {
window.initMap = () => {
}
}
foo() {
let template = `
<html>
<head>
<style>
#map {
height: 300px;
}
body {
margin: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCTtf_3SOMerJ6WeT4roxHoFSr893OYg2Q&callback=initMap" async defer></script>
</body>
</html>
`
let w = window.open();
w.document.write(template);
w.initMap = () => {
let map = new w.google.maps.Map(w.document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
map.addListener('tilesloaded', () => w.print())
}
w.document.body.onload = () => console.log('loaded')
w.document.close();
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<div className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
<button onClick={this.foo}>print</button>
</div>
</div>
);
}
}
export default App;
| a1ea77649f4f227d20beeca5aed01577af4e3d5a | [
"JavaScript"
] | 1 | JavaScript | basith374/react-print-test | 1b8be4a0f6fa8248de51a44fd51616b4855b8802 | ff03de86720c040b0af6c89a85378ed42751fb52 |
refs/heads/master | <repo_name>VictoriaBrown/Find-PI-to-the-Nth-Digit<file_sep>/FindPItotheNthDigit.java
/*
FindPItotheNthDigit.java
Programmer: <NAME>
Date: July 2016
Purpose of class:
Enter a number and have the program generate PI up to that many decimal places.
Keep a limit to how far the program will go
*/
// Import statement:
import java.util.Scanner; // Scanner to accept user input
public class FindPItotheNthDigit {
public static void main(String[] args) {
// Scanner object to obtain number from user.
Scanner input = new Scanner(System.in);
int num; // Variable to save number in.
double pi = Math.PI;
// Prompt user for input:
System.out.print("Please enter a number for which to cut PI off at: ");
num = input.nextInt();
// Return PI rounded to nth decimal.
System.out.println( );
System.out.println("PI rounded to the " + num + " decimal: ");
System.out.printf("%." + num + "f", pi);
}
} | c245972a15019ee1c9104330b0e092d1f0d1e7c4 | [
"Java"
] | 1 | Java | VictoriaBrown/Find-PI-to-the-Nth-Digit | 1e5eb8687f2d217b875a7f7526f18032516adcb8 | 8cda3da1b9d5938c24445aca11799c37311c071f |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ErnstTech.SoundCore;
namespace ErnstTech.SoundCore.Tests
{
[TestClass]
public class WaveReaderWriterTests
{
[TestMethod]
public void Test8BitSingleChannelRoundTrip()
{
const int samplesPerSecond = 44_100;
const double delta = 1.0 / samplesPerSecond;
Func<double, double> func = (double t) => Math.Cos(2.0 * Math.PI * t);
byte[] data = new byte[samplesPerSecond];
for (int i = 0; i < samplesPerSecond; ++i)
data[i] = (byte)(byte.MaxValue * ((func(i * delta) + 1.0) / 2.0));
using var ms = new MemoryStream();
var writer = new WaveWriter(ms, samplesPerSecond);
writer.Write(data.Length, data);
ms.Position = 0;
var reader = new WaveReader(ms);
Assert.AreEqual(reader.Format.Channels, 1);
Assert.AreEqual(reader.Format.SamplesPerSecond, samplesPerSecond);
Assert.AreEqual(reader.Format.BitsPerSample, 8);
var channel = reader.GetChannelInt8(0);
int h = 0;
var e = channel.GetEnumerator();
while (e.MoveNext())
Assert.AreEqual(data[h++], e.Current);
}
[TestMethod]
public void Test16BitSingleChannelRoundTrip()
{
const int samplesPerSecond = 44_100;
const double delta = 1.0 / samplesPerSecond;
Func<double, double> func = (double t) => Math.Cos(2.0 * Math.PI * t);
short[] data = new short[samplesPerSecond];
for (int i = 0; i < samplesPerSecond; ++i)
data[i] = (short)(short.MaxValue * func(i * delta));
using var ms = new MemoryStream();
var writer = new WaveWriter(ms, samplesPerSecond);
writer.Write(data.Length, data);
ms.Position = 0;
var reader = new WaveReader(ms);
Assert.AreEqual(reader.Format.Channels, 1);
Assert.AreEqual(reader.Format.SamplesPerSecond, samplesPerSecond);
Assert.AreEqual(reader.Format.BitsPerSample, 16);
var channel = reader.GetChannelInt16(0);
int h = 0;
var e = channel.GetEnumerator();
while (e.MoveNext())
Assert.AreEqual(data[h++], e.Current, $"Index: {h}");
}
[TestMethod]
public void Test32BitSingleChannelRoundTrip()
{
const int samplesPerSecond = 44_100;
const double delta = 1.0 / samplesPerSecond;
Func<double, double> func = (double t) => Math.Cos(2.0 * Math.PI * t);
float[] data = new float[samplesPerSecond];
for (int i = 0; i < samplesPerSecond; ++i)
data[i] = (float)func(i * delta);
using var ms = new MemoryStream();
var writer = new WaveWriter(ms, samplesPerSecond);
writer.Write(data.Length, data);
ms.Position = 0;
var reader = new WaveReader(ms);
Assert.AreEqual(reader.Format.FormatTag, FormatTag.WAVE_FORMAT_IEEE_FLOAT);
Assert.AreEqual(reader.Format.Channels, 1);
Assert.AreEqual(reader.Format.SamplesPerSecond, samplesPerSecond);
Assert.AreEqual(reader.Format.BitsPerSample, 32);
var channel = reader.GetChannelFloat(0);
int h = 0;
var e = channel.GetEnumerator();
while (e.MoveNext())
Assert.AreEqual(data[h++], e.Current);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis.Expressions.AST
{
public class NumberNode : ExpressionNode
{
public double Value { get; init; }
public NumberNode(double value) => Value = value;
}
public class PiNode : NumberNode
{
public PiNode() : base(Math.PI) { }
}
public class EulerNode : NumberNode
{
public EulerNode() : base(Math.E) { }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Sampler
{
public interface ISampler
{
/// <summary>
/// The number of samples per second. Must be non-negative.
/// </summary>
int SampleRate { get; }
/// <summary>
/// The number of bits per sample. Expected to be one of: 8, 16, 32.
/// </summary>
int BitsPerSample { get; }
/// <summary>
/// The amount of time between samples, in seconds.
/// </summary>
double TimeDelta { get { return 1.0 / SampleRate; } }
/// <summary>
/// The length of the sample in terms of number of samples. May be -1, if length cannot be determined.
/// </summary>
long Length { get; set; }
/// <summary>
/// Get a sample at a specific offset.
/// </summary>
/// <param name="sampleOffset">The offset of the sample to retrieve.</param>
/// <returns>A double containing the sample indicated.</returns>
double Sample(long sampleOffset);
long GetSamples(double[] destination, long destOffset, long sampleStartOffset, long numSamples);
double[] GetSamples(long sampleStartOffset, long numSamples)
{
var dest = new double[numSamples];
var count = GetSamples(dest, 0, sampleStartOffset, numSamples);
if (count != numSamples)
throw new InvalidOperationException($"Failed to read expected number of samples. Read {count}, expected {numSamples}.");
return dest;
}
double[] GetSamples() => GetSamples(0, Length);
}
}
<file_sep>using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using ErnstTech.SoundCore;
namespace ErnstTech.SynthesizerControls
{
/// <summary>
/// Summary description for WaveFormDialog.
/// </summary>
public class WaveFormDialog : System.Windows.Forms.Form
{
private WaveFormat _Format;
public WaveFormat Format
{
get{ return _Format; }
set
{
if ( value == null )
throw new ArgumentNullException( "value" );
_Format = value;
FormatChange();
}
}
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private ErnstTech.SynthesizerControls.BeatBox beatBox1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.GroupBox groupBox1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public WaveFormDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.beatBox1 = new ErnstTech.SynthesizerControls.BeatBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.SuspendLayout();
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.Location = new System.Drawing.Point(540, 362);
this.btnCancel.Name = "btnCancel";
this.btnCancel.TabIndex = 0;
this.btnCancel.Text = "&Cancel";
//
// btnOK
//
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOK.Location = new System.Drawing.Point(460, 362);
this.btnOK.Name = "btnOK";
this.btnOK.TabIndex = 1;
this.btnOK.Text = "&Ok";
//
// beatBox1
//
this.beatBox1.BaseFrequency = 200F;
this.beatBox1.Location = new System.Drawing.Point(69, 67);
this.beatBox1.Name = "beatBox1";
this.beatBox1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.beatBox1.SampleQuality = ErnstTech.SoundCore.AudioBits.Bits16;
this.beatBox1.Size = new System.Drawing.Size(464, 296);
this.beatBox1.TabIndex = 2;
this.beatBox1.Load += new System.EventHandler(this.beatBox1_Load);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(320, 40);
this.textBox1.Name = "textBox1";
this.textBox1.TabIndex = 3;
this.textBox1.Text = "textBox1";
//
// groupBox1
//
this.groupBox1.Location = new System.Drawing.Point(8, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabIndex = 4;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Wave Form Name";
//
// WaveFormDialog
//
this.AutoScaleDimensions = new SizeF(5, 13);
this.ClientSize = new System.Drawing.Size(620, 391);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.beatBox1);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.btnCancel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "WaveFormDialog";
this.Text = "Edit Wave Form";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void beatBox1_Load(object sender, System.EventArgs e)
{
}
private void FormatChange()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for Chunk.
/// </summary>
public abstract class Chunk
{
public abstract string ID { get; }
public int DataSize
{
get { return Data.Length; }
}
public byte[] Data { get; private set; }
internal Chunk(byte[] data)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
this.Data = data;
}
internal static Chunk GetChunk(BinaryReader reader)
{
var buffer = new byte[4];
reader.Read(buffer, 0, buffer.Length);
var id = Encoding.ASCII.GetString(buffer);
var length = reader.ReadInt32();
if (length < 0)
throw new SoundCoreException($"Chunk '{id}' specifies a negative length: {length}.");
var data = new byte[length];
reader.Read(data, 0, length);
return id switch
{
"fmt " => new FormatChunk(data),
"data" => new DataChunk(data),
"RIFF" => new RiffChunk(data),
"WAVE" => new WaveChunk(data),
_ => throw new SoundCoreException($"Unknown or Unexpected chunk type encountered: '{id}'."),
};
}
protected short ReadInt16(int offset)
{
return BitConverter.ToInt16(Data.AsSpan()[offset..]);
}
protected int ReadInt32(int offset)
{
return BitConverter.ToInt32(Data.AsSpan()[offset..]);
}
}
}
<file_sep>using System;
using System.IO;
using System.Threading;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WavePlayer.
/// </summary>
internal class WavePlayer : IDisposable
{
private IntPtr _Device;
private int _BufferDataSize;
private int _BufferCount;
private WaveBufferEmptyHandler _BufferEmptyHandler;
private AutoResetEvent _FinishEvent = new AutoResetEvent( false );
private ManualResetEvent _WriteBufferEvent = new ManualResetEvent( true );
public int BufferDataSize
{
get{ return this._BufferDataSize; }
}
public int BufferCount
{
get{ return this._BufferCount; }
}
private bool _Disposing = false;
public bool Disposing
{
get{ return _Disposing; }
}
private bool _IsPlaying = false;
public bool IsPlaying
{
get{ return _IsPlaying; }
}
private Thread _PlayThread;
private readonly object SyncRoot = new object();
private WaveOutProcDelegate _CallBack = new WaveOutProcDelegate( WaveOutBuffer.WaveOutProcCallback );
private WaveOutBuffer[] _Buffers;
//
// private Stream _DataStream;
//
// public WavePlayer( int device, Stream s )
// {
// if ( s == null )
// throw new ArgumentNullException( "s" );
//
// _DataStream = s;
//
// }
public WavePlayer( int device,
int bufferDataSize, int bufferCount,
WaveFormat format,
WaveBufferEmptyHandler bufferEmptyHandler )
{
if ( bufferDataSize <= 0 )
throw new ArgumentOutOfRangeException( "bufferDataSize", bufferDataSize, "bufferDataSize must be greater than 0." );
this._BufferDataSize = bufferDataSize;
if ( bufferCount <= 0 )
throw new ArgumentOutOfRangeException( "bufferCount", bufferCount, "bufferCount must be greater than 0." );
if ( format == null )
throw new ArgumentNullException( "format" );
WaveFormatEx formatEx = format.GetFormat();
this._BufferCount = 2;
if ( bufferEmptyHandler == null )
throw new ArgumentNullException( "bufferEmptyHandler" );
this._BufferEmptyHandler = bufferEmptyHandler;
int result = WaveFormNative.waveOutOpen( out _Device,
device,
ref formatEx,
_CallBack,
0,
(int)DeviceOpenFlags.CallbackFunction );
if ( result != WaveError.MMSYSERR_NOERROR )
throw new SoundCoreException( WaveError.GetMessage( result ), result );
AllocateBuffers();
_IsPlaying = true;
FillBuffer( _Buffers[0] );
_Buffers[0].Play();
// FillBuffers();
//
// _FillThread = new Thread( new ThreadStart( FillBufferLoop ) );
// _FillThread.Start();
//
// _RootBuffer.Play();
_PlayThread = new Thread( new ThreadStart( PlayLoop ) );
_PlayThread.Priority = ThreadPriority.Highest;
_PlayThread.Start();
}
~WavePlayer()
{
Dispose();
}
public static int GetDevices()
{
return WaveFormNative.waveOutGetNumDevs();
}
private void AllocateBuffers()
{
// _RootBuffer = new WaveOutBuffer( this._Device, this.BufferDataSize );
//// _RootBuffer.Completed += new EventHandler(buffer_Completed);
//
// WaveOutBuffer prev = _RootBuffer;
_Buffers = new WaveOutBuffer[ BufferCount ];
_Buffers[0] = new WaveOutBuffer( this._Device, this.BufferDataSize, new WaveBufferEmptyHandler( FillBuffer ) );
_Buffers[1] = new WaveOutBuffer( this._Device, this.BufferDataSize, new WaveBufferEmptyHandler( FillBuffer ) );
_Buffers[0].NextBuffer = _Buffers[1];
_Buffers[1].NextBuffer = _Buffers[0];
// for ( int i = 0; i < this.BufferCount; i++ )
// {
// _Buffers[i] = new WaveOutBuffer( this._Device, this.BufferDataSize );
// prev.NextBuffer = new WaveOutBuffer( this._Device, this.BufferDataSize );
// prev = prev.NextBuffer;
// prev.Completed += new EventHandler( buffer_Completed );
// }
//
// prev.NextBuffer = _RootBuffer;
}
private void FreeBuffers()
{
for( int i = 0; i < this.BufferCount; i++ )
{
_Buffers[i].Dispose();
}
// WaveOutBuffer buffer = this._RootBuffer;
//
// for ( int i = 0; i < this.BufferCount; i++ )
// {
// WaveOutBuffer temp = buffer;
// buffer = temp.NextBuffer;
// temp.Dispose();
// }
//
// _RootBuffer = null;
}
// private void FillBuffers()
// {
// this._CurrentWriteBuffer = this._RootBuffer;
//
// do
// {
// FillBuffer( _CurrentWriteBuffer );
//
// _CurrentWriteBuffer = _CurrentWriteBuffer.NextBuffer;
//
// } while( _CurrentWriteBuffer != _RootBuffer );
// }
//
private void FillBuffer( object sender, WaveBufferEmptyEventArgs args )
{
// Fill the buffer
this._BufferEmptyHandler( this, args);
// TODO: Examine args.BytesWritten to determine when end of data reached.
if ( args.BytesWritten <= 0 )
{
// TODO: Take action to signal playing should stop.
this._IsPlaying = false;
}
//
// // Signal the buffer that it has data.
// buffer.BufferFilled();
}
private void FillBuffer( WaveOutBuffer buffer )
{
WaveBufferEmptyEventArgs args = new WaveBufferEmptyEventArgs( buffer.Data, buffer.Size );
// Fill the buffer
this._BufferEmptyHandler( this, args);
// TODO: Examine args.BytesWritten to determine when end of data reached.
if ( args.BytesWritten <= 0 )
{
// TODO: Take action to signal playing should stop.
this._IsPlaying = false;
}
//
// // Signal the buffer that it has data.
// buffer.BufferFilled();
}
//
// private void FillBufferLoop()
// {
// WaveOutBuffer current = _RootBuffer;
//
// while( IsPlaying )
// {
// // Wait until buffer has been read
// current.WaitUntilEmpty();
//
// // Fill the buffer
// FillBuffer( current );
//
// // Move to next buffer
// current = current.NextBuffer;
// }
// }
private void PlayLoop()
{
int index = 0;
WaveOutBuffer buffer = _Buffers[index];
WaveOutBuffer playing = null;
FillBuffer(buffer);
while ( IsPlaying )
{
buffer.Play();
playing = buffer;
index = ++index % BufferCount;
buffer = _Buffers[ index ];
FillBuffer(buffer);
playing.WaitUntilCompleted();
//
// WaveOutBuffer buffer = _Buffers[index];
// FillBuffer( buffer );
//
//
// buffer.Play();
// buffer.WaitUntilCompleted();
//
// current = current.NextBuffer;
}
this._FinishEvent.Set();
}
#region IDisposable Members
public void Dispose()
{
if ( Disposing )
return;
this._Disposing = true;
if ( this.IsPlaying )
Stop();
WaveFormNative.waveOutClose( this._Device );
FreeBuffers();
}
#endregion
public void Stop()
{
this._IsPlaying = false;
this._FinishEvent.WaitOne();
}
private void buffer_Completed(object sender, EventArgs e)
{
// WaveOutBuffer buffer = sender as WaveOutBuffer;
//
// FillBuffer( buffer );
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore.Synthesis
{
/// <summary>
/// Applies an ADSR (Attack-Decay-Sustain-Release) envelope to
/// </summary>
public class ADSREnvelope
{
/// <summary>
/// Maximum value of the attack.
/// </summary>
public double AttackHeight { get; set; } = 1.0;
/// <summary>
/// Duration of the attack, in seconds. Must be non-negative.
/// </summary>
public double AttackTime { get; set; } = 0.01;
public double AttackRate => AttackHeight / AttackTime;
/// <summary>
/// Duration of the decay, in seconds. Must be non-negative.
/// </summary>
public double DecayTime { get; set; } = 0.10;
public double DecayStart => AttackTime;
public double DecayEnd => AttackTime + DecayTime;
public double DecayRate => (SustainHeight - AttackHeight) / DecayTime;
/// <summary>
/// Maximum value of the sustained signal.
/// </summary>
public double SustainHeight { get; set; } = 0.5;
/// <summary>
/// Duration of the Sustain, in seconds. Must be non-negative.
/// </summary>
public double SustainTime { get; set; } = 0.250;
public double SustainStart => DecayEnd;
public double SustainEnd => SustainStart + SustainTime;
/// <summary>
/// Duration of the Release, in seconds. Must be non-negative.
/// </summary>
public double ReleaseTime { get; set; } = 0.10;
public double ReleaseStart => SustainEnd;
public double ReleaseEnd => ReleaseStart + ReleaseTime;
public double ReleaseRate => SustainHeight / ReleaseTime;
public ADSREnvelope()
{ }
/// <summary>
/// The scaling factor as a function of time.
/// </summary>
/// <param name="time">The time, in seconds, from the start of the envelope.</param>
/// <returns>The scaling factor to be applied.</returns>
public double Factor(double time)
{
if (time <= AttackTime)
return AttackHeight * (time / AttackTime);
else if (DecayStart < time && time <= DecayEnd)
return AttackHeight + DecayRate * (time - DecayStart);
else if (SustainStart < time && time <= SustainEnd)
return SustainHeight;
else if (ReleaseStart < time && time <= ReleaseEnd)
return SustainHeight - ReleaseRate * (time - ReleaseStart);
return 0;
}
/// <summary>
/// Scale a factor to a moment in time.
/// </summary>
/// <param name="time">The time, in seconds, from the start of the envelope.</param>
/// <param name="value">The value to be scaled.</param>
/// <returns>The scaled value for the moment in time.</returns>
public double ValueAt(double time, double value) => value * Factor(time);
/// <summary>
/// Scale a factor from a function of time to a moment in time.
/// </summary>
/// <param name="time">The time, in seconds, for the function to be applied and scaled.</param>
/// <param name="func">A function of time, in seconds, returning a value to be scaled.</param>
/// <returns>The scaled value of the function at the moment in time.</returns>
public double ValueAt(double time, Func<double, double> func) => ValueAt(time, func(time));
/// <summary>
/// Adapts a function, wrapping an ADSR evelope around the source function.
/// </summary>
/// <param name="func">The function, parameterized by time, to be adapted.</param>
/// <returns>A function that has been adapted to apply the envelope.</returns>
public Func<double, double> Adapt(Func<double, double> func) => (double t) => ValueAt(t, func);
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
public enum SampleRate
{
Rate44100 = 44100,
Rate22050 = 22050,
Rate11025 = 11025
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis.Expressions.AST
{
public class ExpressionListNode : ExpressionNode
{
public List<ExpressionNode> Children { get; set; }
public ExpressionListNode(List<ExpressionNode> children) => Children = children;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Synthesizer.Controls
{
/// <summary>
/// Interaction logic for BeatLoopControl.xaml
/// </summary>
public partial class BeatLoopControl : UserControl
{
public Views.BeatLoopView BeatLoopView => (Views.BeatLoopView)DataContext;
public BeatLoopControl()
{
InitializeComponent();
this.DataContext = new Views.BeatLoopView()
{
};
}
}
}
<file_sep>using ErnstTech.Math;
using ErnstTech.SoundCore;
using ErnstTech.Synthesizer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Numerics;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace ErnstTech.Synthesizer
{
public partial class WaveFormView : Form
{
private Stream _Stream;
private WaveFormat _Format;
private WaveReader _Reader;
private PointF[] _DataPoints;
private PointF[] _ScaledPoints;
private PointF[] _MagnitudePoints;
private PointF[] _ScaledMagnitudePoints;
private PointF[] _PhasePoints;
private PointF[] _ScaledPhasePoints;
private double _ZoomFactor = 1.0;
public double ZoomFactor
{
get { return this._ZoomFactor; }
set
{
value = System.Math.Abs(value);
if (value == 0.0f)
value = 1.0f;
if (value == this._ZoomFactor)
return;
this._ZoomFactor = value;
this.OnZoomFactorChanged(EventArgs.Empty);
}
}
public event EventHandler ZoomFactorChanged
{
add { this.Events.AddHandler(ZoomFactorChangedEvent, value); }
remove { this.Events.RemoveHandler(ZoomFactorChangedEvent, value); }
}
private static readonly object ZoomFactorChangedEvent = new object();
protected virtual void OnZoomFactorChanged(EventArgs arguments)
{
EventHandler handler = this.Events[ZoomFactorChangedEvent] as EventHandler;
if (handler != null)
handler(this, arguments);
}
private bool _ShowFrequencyDomain = false;
public bool ShowFrequencyDomain
{
get { return this._ShowFrequencyDomain; }
set
{
if (this._ShowFrequencyDomain == value)
return;
this._ShowFrequencyDomain = value;
this.OnShowFrequencyDomainChanged(EventArgs.Empty);
}
}
private static readonly object ShowFrequencyDomainChangedEvent = new object();
public event EventHandler ShowFrequencyDomainChanged
{
add { this.Events.AddHandler(ShowFrequencyDomainChangedEvent, value); }
remove { this.Events.RemoveHandler(ShowFrequencyDomainChangedEvent, value); }
}
protected virtual void OnShowFrequencyDomainChanged(EventArgs arguments)
{
EventHandler handler = this.Events[ShowFrequencyDomainChangedEvent] as EventHandler;
if (handler != null)
handler(this, arguments);
}
#region MagnitudeColor Property
private Color _MagnitudeColor = Color.Blue;
public Color MagnitudeColor
{
get { return this._MagnitudeColor; }
set
{
if (this._MagnitudeColor == value)
return;
this._MagnitudeColor = value;
this.OnMagnitudeColorChanged(EventArgs.Empty);
}
}
private static readonly object MagnitudeColorChangedEvent = new object();
public event EventHandler MagnitudeColorChanged
{
add { this.Events.AddHandler(MagnitudeColorChangedEvent, value); }
remove { this.Events.RemoveHandler(MagnitudeColorChangedEvent, value); }
}
protected virtual void OnMagnitudeColorChanged(EventArgs arguments)
{
EventHandler handler = this.Events[MagnitudeColorChangedEvent] as EventHandler;
if (handler != null)
handler(this, arguments);
}
#endregion
#region PhaseColor Property
private Color _PhaseColor = Color.Red;
public Color PhaseColor
{
get { return this._PhaseColor; }
set
{
if (this._PhaseColor == value)
return;
this._PhaseColor = value;
this.OnPhaseColorChanged(EventArgs.Empty);
}
}
private static readonly object PhaseColorChangedEvent = new object();
public event EventHandler PhaseColorChanged
{
add { this.Events.AddHandler(PhaseColorChangedEvent, value); }
remove { this.Events.RemoveHandler(PhaseColorChangedEvent, value); }
}
protected virtual void OnPhaseColorChanged(EventArgs arguments)
{
EventHandler handler = this.Events[PhaseColorChangedEvent] as EventHandler;
if (handler != null)
handler(this, arguments);
}
#endregion
private ManualResetEvent _FFTReady = new ManualResetEvent(false);
public WaveFormView(Stream waveForm)
{
if (waveForm == null)
throw new ArgumentNullException(nameof(WaveForm));
this._Stream = waveForm;
this._Reader = new WaveReader(waveForm);
this._Format = this._Reader.Format;
this.ReadPointsFromWaveForm();
InitializeComponent();
this.panelWaveForm.Paint += new PaintEventHandler(panelWaveForm_Paint);
this.MouseWheel += (o, e) =>
{
var d = e.Delta / 120.0;
this.ZoomFactor *= d switch
{
< 0 => 1.0 / (d * 10),
> 0 => d * 10,
_ => 1.0
};
};
this.ZoomFactorChanged += delegate
{
this.ScalePoints();
this.Refresh();
};
this.MagnitudeColorChanged += delegate
{
if (this.ShowFrequencyDomain)
this.Refresh();
};
this.PhaseColorChanged += delegate
{
if (this.ShowFrequencyDomain)
this.Refresh();
};
this.ShowFrequencyDomainChanged += delegate
{
this.Refresh();
};
this.miFFTOff.Click += delegate
{
this.ShowFrequencyDomain = false;
};
this.miFFTOn.Click += delegate
{
this.ShowFrequencyDomain = true;
};
//Thread fftThread = new Thread(new ThreadStart(this.CalculateFFT));
//fftThread.Start();
}
private void CalculateFFT()
{
long nPoints = this._DataPoints.LongLength;
Complex[] data = new Complex[nPoints];
for (long i = 0; i < nPoints; ++i)
data[i] = new Complex(Convert.ToDouble(i), this._DataPoints[i].Y);
ErnstTech.Math.FastFourierTransform.Transform(1, data);
this._MagnitudePoints = new PointF[nPoints];
this._PhasePoints = new PointF[nPoints];
for (long i = 0; i < nPoints; ++i)
{
float x = Convert.ToSingle(i);
this._MagnitudePoints[i] = new PointF(x,
Convert.ToSingle(data[i].Magnitude));
this._PhasePoints[i] = new PointF(x,
Convert.ToSingle(data[i].Phase));
}
this.Normalize(this._MagnitudePoints);
this.Normalize(this._PhasePoints);
this._FFTReady.Set();
}
private int CalculateHeight()
{
return this.ClientSize.Height - this.toolStrip1.Height;
}
void panelWaveForm_Paint(object sender, PaintEventArgs e)
{
using (Brush b = new SolidBrush(this.panelWaveForm.BackColor))
{
e.Graphics.FillRectangle(b, this.Bounds);
}
using (Brush b = new SolidBrush(this.ForeColor))
using (Pen p = new Pen(b))
{
e.Graphics.DrawLines(p, this._ScaledPoints);
//e.Graphics.DrawCurve(p, this._ScaledPoints);
}
//if (this.ShowFrequencyDomain)
//{
// this._FFTReady.WaitOne();
// using (Brush b = new SolidBrush(this.MagnitudeColor))
// using (Pen p = new Pen(b))
// {
// e.Graphics.DrawLines(p, this._ScaledMagnitudePoints);
// }
// using (Brush b = new SolidBrush(this.PhaseColor))
// using (Pen p = new Pen(b))
// {
// e.Graphics.DrawLines(p, this._ScaledPhasePoints);
// }
//}
}
private void ReadPointsFromWaveForm()
{
switch (this._Format.BitsPerSample)
{
case 8:
this.ReadBytePointsFromWaveForm();
break;
case 16:
this.ReadShortPointsFromWaveForm();
break;
case 32:
this.ReadSinglePointsFromWaveForm();
break;
default:
throw new NotSupportedException($"An unsupported sample size was encountered: {this._Format.BitsPerSample}.");
}
}
void Normalize(PointF[] points)
{
float max = 0.0f;
foreach (PointF pt in points)
{
float abs = System.Math.Abs(pt.Y);
if (abs > max)
max = abs;
}
for (long i = 0, len = points.LongLength; i < len; ++i)
{
points[i] = new PointF(points[i].X, points[i].Y / max);
}
}
private void ScalePoints()
{
this.panelWaveForm.ClientSize = new Size(Convert.ToInt32(this._DataPoints.LongLength * this.ZoomFactor),
this.CalculateHeight());
this.panelWaveForm.Top = this.toolStrip1.Height;
long nPoints = this._DataPoints.LongLength;
this._ScaledPoints = new PointF[nPoints];
this._ScaledMagnitudePoints = new PointF[nPoints];
this._ScaledPhasePoints = new PointF[nPoints];
int height = this.panelWaveForm.ClientSize.Height;
float vScale = height / -2.0f; // Invert the points
int vTranslation = height / 2;
float zf = (float)this.ZoomFactor;
for (long idx = 0; idx < nPoints; ++idx)
{
float x = Convert.ToSingle(idx) * zf;
this._ScaledPoints[idx] = new PointF(x,
Convert.ToSingle(vScale * this._DataPoints[idx].Y + vTranslation));
if (this.ShowFrequencyDomain)
{
this._ScaledMagnitudePoints[idx] = new PointF(x,
Convert.ToSingle(vScale * this._MagnitudePoints[idx].Y + vTranslation));
this._ScaledPhasePoints[idx] = new PointF(x,
Convert.ToSingle(vScale * this._PhasePoints[idx].Y + vTranslation));
}
}
}
protected override void OnResize(EventArgs e)
{
this.panelWaveForm.ClientSize = new Size(this.panelWaveForm.ClientSize.Width, this.Height);
this.ScalePoints();
base.OnResize(e);
}
private void ReadBytePointsFromWaveForm()
{
long nSamples = this._Reader.NumberOfSamples;
this._DataPoints = new PointF[nSamples];
long i = 0;
foreach (var s in this._Reader.GetChannelInt8(0))
this._DataPoints[i++] = new PointF(Convert.ToSingle(i), Convert.ToSingle(s) / sbyte.MaxValue);
}
private void ReadShortPointsFromWaveForm()
{
long nSamples = this._Reader.NumberOfSamples;
this._DataPoints = new PointF[nSamples];
long i = 0;
foreach (var s in this._Reader.GetChannelInt16(0))
this._DataPoints[i++] = new PointF(Convert.ToSingle(i), Convert.ToSingle(s) / short.MaxValue);
}
private void ReadSinglePointsFromWaveForm()
{
long nSamples = this._Reader.NumberOfSamples;
this._DataPoints = new PointF[nSamples];
long i = 0;
foreach (var s in this._Reader.GetChannelFloat(0))
this._DataPoints[i++] = new PointF(Convert.ToSingle(i), s);
}
private void txtZoomFactor_Validating(object sender, CancelEventArgs e)
{
float result;
e.Cancel = !float.TryParse(this.txtZoomFactor.Text, out result);
}
private void txtZoomFactor_TextChanged(object sender, EventArgs e)
{
float factor;
if (!float.TryParse(this.txtZoomFactor.Text, out factor))
factor = 100.0f;
factor /= 100;
this.ZoomFactor = factor;
}
}
}<file_sep>using System;
using System.Threading;
using System.Runtime.InteropServices;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Wraps the WaveHeaderEx structure
/// </summary>
internal class WaveOutBuffer : IDisposable
{
private WaveOutBuffer _NextBuffer;
public WaveOutBuffer NextBuffer
{
get{ return _NextBuffer; }
set{ _NextBuffer = value; }
}
private EventHandler _Completed;
public event EventHandler Completed
{
add{ _Completed += value; }
remove{ _Completed -= value; }
}
private ManualResetEvent _WaitForCompletion = new ManualResetEvent( false );
private ManualResetEvent _WaitForEmpty = new ManualResetEvent( true );
// private ManualResetEvent _PlayEvent = new ManualResetEvent( false );
IntPtr _DeviceHandle;
GCHandle _HeaderHandle;
GCHandle _DataHandle;
WaveHeader _Header;
byte[] _Data;
private bool _Disposing = false;
public bool Disposing
{
get{ return _Disposing; }
}
private bool _IsPlaying = false;
public bool IsPlaying
{
get{ return this._IsPlaying; }
}
public int Size
{
get{ return this._Header.BufferLength; }
}
public IntPtr Data
{
get{ return this._Header.Data; }
}
private bool _IsEmpty = true;
public bool IsEmpty
{
get{ return this._IsEmpty; }
set{ this._IsEmpty = value; }
}
WaveBufferEmptyHandler _FillDelegate;
/// <summary>
/// Initializes the buffer.
/// </summary>
/// <param name="device">Handle to the wave out device to use.</param>
/// <param name="size">Size of the buffer to allocate.</param>
public WaveOutBuffer( IntPtr device, int size, WaveBufferEmptyHandler fillDelegate )
{
if ( device == IntPtr.Zero )
throw new ArgumentException( "Device must be a a valid pointer to a wave out device.", "device" );
if ( size < 1 )
throw new ArgumentOutOfRangeException( "size", size, "Size must be greater than zero." );
if ( fillDelegate == null )
throw new ArgumentNullException( "fillDelegate" );
_FillDelegate = fillDelegate;
_DeviceHandle = device;
// Allocate memory for the buffer, and set up a GCHandle pointed to it.
_Data = new byte[size];
_DataHandle = GCHandle.Alloc( _Data, GCHandleType.Pinned );
// Create the header and a GC handle pointed to it.
_Header = new WaveHeader();
_HeaderHandle = GCHandle.Alloc( _Header, GCHandleType.Pinned );
_Header.Data = _DataHandle.AddrOfPinnedObject();
_Header.BufferLength = size;
_Header.UserData = (IntPtr)GCHandle.Alloc( this );
_Header.Loops = 0;
_Header.Flags = 0;
int result = WaveFormNative.waveOutPrepareHeader( _DeviceHandle,
ref _Header, Marshal.SizeOf( _Header ) );
if ( result != WaveError.MMSYSERR_NOERROR )
throw new SoundCoreException( WaveError.GetMessage( result ), result );
}
~WaveOutBuffer()
{
Dispose();
}
#region IDisposable Members
public void Dispose()
{
if ( Disposing )
return;
_Disposing = true;
WaveFormNative.waveOutUnprepareHeader( this._DeviceHandle, ref _Header, Marshal.SizeOf( _Header ) );
if ( _HeaderHandle.IsAllocated )
_HeaderHandle.Free();
if ( _DataHandle.IsAllocated )
_DataHandle.Free();
this._WaitForCompletion.Close();
}
#endregion
public virtual void Play()
{
this._WaitForCompletion.Reset();
// this._PlayEvent.WaitOne();
// this._PlayEvent.Reset();
this._IsPlaying = true;
int result = WaveFormNative.waveOutWrite( this._DeviceHandle, ref this._Header, Marshal.SizeOf( this._Header ) );
if ( result != WaveError.MMSYSERR_NOERROR )
throw new SoundCoreException( WaveError.GetMessage( result ), result );
}
protected virtual void OnCompleted( EventArgs e )
{
if ( this.IsPlaying )
{
// this._IsEmpty = true;
// this._WaitForCompletion.Set();
////
//// this._NextBuffer.Play();
//
// WaveBufferEmptyEventArgs args = new WaveBufferEmptyEventArgs( this.Data, this.Size );
//// this._FillDelegate( this, args );
_IsPlaying = false;
_IsEmpty = true;
this._WaitForCompletion.Set();
this._WaitForEmpty.Set();
if ( this._Completed != null )
this._Completed( this, e );
}
}
public void BufferFilled()
{
this._IsEmpty = false;
this._WaitForEmpty.Reset();
}
/// <summary>
/// Allows a thread to wait until this buffer block is finished playing
/// </summary>
public void WaitUntilCompleted()
{
// Verify we're playing. If we're not, cause a context switch.
if ( this.IsPlaying )
{
this._WaitForCompletion.WaitOne(); // Wait for block to finish
}
else
Thread.Sleep( 0 ); // Allow context switch
}
/// <summary>
/// Waits until the buffer has been marked as empty.
/// </summary>
public void WaitUntilEmpty()
{
if ( this.IsEmpty )
Thread.Sleep( 0 );
else
this._WaitForEmpty.WaitOne();
}
/// <summary>
/// Callback that receives signal when completed
/// </summary>
/// <param name="audioDevice">Device that signaled the event</param>
/// <param name="message">Message passed back to us.</param>
/// <param name="instance">Not used</param>
/// <param name="header">Header that is being signalled</param>
/// <param name="reserved">Not used</param>
internal static void WaveOutProcCallback(IntPtr audioDevice, int message, int instance, ref WaveHeader header, int reserved)
{
// Make sure that we're signalled done
if ( message == (int)WaveFormOutputMessage.Done )
{
// Get IntPtr to WaveOutBuffer
GCHandle handle = (GCHandle)header.UserData;
// Get buffer
WaveOutBuffer buffer = (WaveOutBuffer)handle.Target;
// Signal completed to buffer
buffer.OnCompleted( EventArgs.Empty );
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore
{
public class WaveReader
{
public Stream Stream { get; init; }
public WaveFormat Format { get; init; }
public long BasePosition { get; init; }
public long RiffLength { get; init; }
public long DataLength { get; init; }
public long NumberOfSamples { get; init; }
public WaveReader(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
this.Stream = stream;
var reader = new BinaryReader(stream);
SeekChunk("RIFF");
RiffLength = reader.ReadInt32();
//for (int i = 0; i < 4; ++i) // Skip length?
// Stream.ReadByte();
SeekChunk("WAVE");
Format = new WaveFormat(stream);
SeekChunk("data");
DataLength = reader.ReadInt32();
//for (int i = 0; i < 4; ++i) // Skip length?
// Stream.ReadByte();
this.NumberOfSamples = this.DataLength / (Format.Channels * Format.BitsPerSample / 8);
BasePosition = this.Stream.Position;
}
void SeekChunk(string id)
{
const int idSize = 4;
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
if (id.Length != idSize)
throw new ArgumentException($"Expected ID length is 4. Got {id.Length}.", nameof(id));
var seek = Encoding.ASCII.GetBytes(id);
var buffer = new byte[idSize];
while (true)
{
if (Stream.Read(buffer, 0, idSize) != idSize)
throw new SoundCoreException($"Failed to find chunk '{id}'");
if (seek.SequenceEqual(buffer))
break;
}
}
IEnumerable<byte[]> GetEnumerator(short channel)
{
if (channel < 0 || channel >= this.Format.Channels)
throw new ArgumentOutOfRangeException(nameof(channel), channel, $"Channel must be in range [0, {this.Format.Channels}).");
var numBytes = Format.BitsPerSample switch
{
8 => 1,
16 => 2,
32 => 4,
_ => throw new SoundCoreException($"Invalid BitsPerSample. Got '{Format.BitsPerSample}', expected 8, 16, or 32.")
};
var buf = new byte[numBytes];
var skipCount = (this.Format.Channels - 1 ) * numBytes;
Debug.Assert(skipCount >= 0);
// Queue the stream to the first byte of the channel
this.Stream.Position = this.BasePosition + channel * numBytes;
while (this.Stream.Position < this.Stream.Length)
{
int count = this.Stream.Read(buf);
if (count != buf.Length)
throw new SoundCoreException($"Failed to read entire sample from channel {channel}. Got {count} bytes, expected {buf.Length}.");
yield return buf;
this.Stream.Position += skipCount;
}
}
public IEnumerable<byte> GetChannelInt8(short channel)
{
foreach (var buf in GetEnumerator(channel))
yield return (byte)buf[0];
}
public IEnumerable<short> GetChannelInt16(short channel)
{
foreach (var buf in GetEnumerator(channel))
yield return BitConverter.ToInt16(buf);
}
public IEnumerable<int> GetChannelInt32(short channel)
{
foreach (var buf in GetEnumerator(channel))
yield return BitConverter.ToInt32(buf);
}
public IEnumerable<float> GetChannelFloat(short channel)
{
if (this.Format.FormatTag != FormatTag.WAVE_FORMAT_IEEE_FLOAT)
throw new SoundCoreException($"GetChannelFloat can only be used in WAVE_FORMAT_IEEE_FLOAT format.");
foreach (var buf in GetEnumerator(channel))
yield return BitConverter.ToSingle(buf);
}
}
}
<file_sep>using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace ErnstTech.SynthesizerControls
{
/// <summary>
/// Summary description for BeatLoop.
/// </summary>
[Designer( typeof( BeatLoop.BeatLoopDesigner ) ) ]
public class BeatLoop : System.Windows.Forms.Control
{
public static readonly Color DefaultOnColor = Color.Green;
public static readonly Color DefaultOffColor = Color.Transparent;
public static readonly Color DefaultHalfColor = Color.Orange;
public static readonly Color DefaultBorderColor = Color.Black;
public class BeatLoopDesigner : System.Windows.Forms.Design.ControlDesigner
{
}
private BeatCollection _Beats = new BeatCollection();
protected virtual BeatCollection Beats
{
get{ return _Beats; }
}
#region BeatCount Property
private int _BeatCount = 16;
public int BeatCount
{
get{ return _BeatCount; }
set
{
if ( value < 1 )
throw new ArgumentOutOfRangeException( "value", value, "BeatCount must be a positive integer." );
if ( this._BeatCount == value )
return;
this._BeatCount = value;
this.OnBeatCountChanged( EventArgs.Empty );
}
}
#region BeatCountChanged Event
private static readonly object BeatCountChangedEvent = new object();
public event EventHandler BeatCountChanged
{
add{ this.Events.AddHandler( BeatCountChangedEvent, value ); }
remove{ this.Events.RemoveHandler( BeatCountChangedEvent, value ); }
}
protected virtual void OnBeatCountChanged( EventArgs arguments )
{
EventHandler handler = this.Events[BeatCountChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
#endregion
#region BeatWidth Property
private int _BeatWidth;
public int BeatWidth
{
get{ return this._BeatWidth; }
}
private void SetBeatWidth()
{
int width = this.Width;
width -= ( this.BeatCount * ( this.BorderWidth - 1 + this.BeatSpacing ) );
width /= this.BeatCount;
if ( width == this._BeatWidth )
return;
this._BeatWidth = width;
this.OnBeatWidthChanged( EventArgs.Empty );
}
#region BeatWidthChanged Event
private static readonly object BeatWidthChangedEvent = new object();
/// <summary>
/// Raised when <see cref="BeatWidth"/> has changed.
/// </summary>
public event EventHandler BeatWidthChanged
{
add{ this.Events.AddHandler( BeatWidthChangedEvent, value ); }
remove{ this.Events.RemoveHandler( BeatWidthChangedEvent, value ); }
}
/// <summary>
/// Raises the <see cref="BeatWidthChanged"/> event.
/// </summary>
/// <param name="arguments">
/// Event arguments.
/// </param>
protected virtual void OnBeatWidthChanged( EventArgs arguments )
{
EventHandler handler = this.Events[BeatWidthChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
#endregion
#region BorderWidth Property
private int _BorderWidth = 1;
public int BorderWidth
{
get{ return this._BorderWidth; }
set
{
if ( value < 0 )
value = 0;
if ( this._BorderWidth == value )
return;
this._BorderWidth = value;
this.OnBorderWidthChanged( EventArgs.Empty );
}
}
#region BorderWidthChanged Event
private static readonly object BorderWidthChangedEvent = new object();
public event EventHandler BorderWidthChanged
{
add{ this.Events.AddHandler( BorderWidthChangedEvent, value ); }
remove{ this.Events.RemoveHandler( BorderWidthChangedEvent, value ); }
}
protected virtual void OnBorderWidthChanged( EventArgs arguments )
{
EventHandler handler = this.Events[BorderWidthChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
#endregion
#region BeatSpacing Property
private int _BeatSpacing = -1;
/// <summary>
/// The number of pixels of padding to place between <see cref="Beat"/> controls.
/// </summary>
public int BeatSpacing
{
get{ return _BeatSpacing; }
set
{
if ( this._BeatSpacing == value )
return;
_BeatSpacing = value;
this.OnBeatSpacingChanged( EventArgs.Empty );
}
}
#region BeatSpacingChanged Event
private static readonly object BeatSpacingChangedEvent = new object();
/// <summary>
/// Raised when <see cref="BeatSpacing"/> has changed.
/// </summary>
public event EventHandler BeatSpacingChanged
{
add{ this.Events.AddHandler( BeatSpacingChangedEvent, value ); }
remove{ this.Events.RemoveHandler( BeatSpacingChangedEvent, value ); }
}
/// <summary>
/// Raises the <see cref="BeatSpacingChanged"/> event.
/// </summary>
/// <param name="arguments">
/// Event arguments.
/// </param>
protected virtual void OnBeatSpacingChanged( EventArgs arguments )
{
EventHandler handler = this.Events[BeatSpacingChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
#endregion
private Color _OnColor = DefaultOnColor;
[Category("Appearance")]
public Color OnColor
{
get{ return _OnColor; }
set
{
if ( object.Equals( this._OnColor, value ) )
return;
this._OnColor = value;
this.OnOnColorChanged( EventArgs.Empty );
}
}
#region OnColorChanged Event
private static readonly object OnColorChangedEvent = new object();
public event EventHandler OnColorChanged
{
add{ this.Events.AddHandler( OnColorChangedEvent, value ); }
remove{ this.Events.RemoveHandler( OnColorChangedEvent, value ); }
}
protected virtual void OnOnColorChanged( EventArgs arguments )
{
EventHandler handler = this.Events[OnColorChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
private Color _HalfColor = DefaultHalfColor;
[Category("Appearance")]
public Color HalfColor
{
get{ return _HalfColor; }
set
{
if ( object.Equals( this._HalfColor, value ) )
return;
this._HalfColor = value;
this.OnHalfColorChanged( EventArgs.Empty );
}
}
#region HalfColorChanged Event
private static readonly object HalfColorChangedEvent = new object();
public event EventHandler HalfColorChanged
{
add{ this.Events.AddHandler( HalfColorChangedEvent, value ); }
remove{ this.Events.RemoveHandler( HalfColorChangedEvent, value ); }
}
protected virtual void OnHalfColorChanged( EventArgs arguments )
{
EventHandler handler = this.Events[HalfColorChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
private Color _OffColor = DefaultOffColor;
[Category("Appearance")]
public Color OffColor
{
get{ return _OffColor; }
set
{
if ( object.Equals( this._OffColor, value ) )
return;
this._OffColor = value;
this.OnOffColorChanged( EventArgs.Empty );
}
}
#region OffColorChanged Event
private static readonly object OffColorChangedEvent = new object();
public event EventHandler OffColorChanged
{
add{ this.Events.AddHandler( OffColorChangedEvent, value ); }
remove{ this.Events.RemoveHandler( OffColorChangedEvent, value ); }
}
protected virtual void OnOffColorChanged( EventArgs arguments )
{
EventHandler handler = this.Events[OffColorChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
private Color _BorderColor = DefaultBorderColor;
[Category("Appearance")]
public Color BorderColor
{
get{ return _BorderColor; }
set
{
if ( object.Equals( this._BorderColor, value ) )
return;
_BorderColor = value;
this.OnBorderColorChanged(EventArgs.Empty);
}
}
#region BorderColorChanged Event
private static readonly object BorderColorChangedEvent = new object();
public event EventHandler BorderColorChanged
{
add{ this.Events.AddHandler( BorderColorChangedEvent, value ); }
remove{ this.Events.RemoveHandler( BorderColorChangedEvent, value ); }
}
protected virtual void OnBorderColorChanged( EventArgs arguments )
{
EventHandler handler = this.Events[BorderColorChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
protected override Size DefaultSize
{
get
{
int width = this.BeatCount * ( this.BeatSpacing + this.BeatWidth ) + this.BeatSpacing ;
int height = 2 * this.BeatSpacing + this.BeatWidth;
return new Size( width, height );
}
}
public BeatLoop()
{
this.ControlAdded += new ControlEventHandler(BeatLoop_ControlAdded);
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
this.ResizeBeatsCollection();
this.BorderColorChanged += new EventHandler(BeatLoop_ColorChanged);
this.OnColorChanged += new EventHandler(BeatLoop_ColorChanged);
this.OffColorChanged += new EventHandler(BeatLoop_ColorChanged);
this.HalfColorChanged += new EventHandler(BeatLoop_ColorChanged);
this.SizeChanged += new EventHandler(BeatLoop_SizeChanged);
this.BeatSpacingChanged += new EventHandler(BeatLoop_BeatSpacingChanged);
this.BeatCountChanged += new EventHandler(BeatLoop_BeatCountChanged);
this.BeatWidthChanged += new EventHandler(BeatLoop_BeatWidthChanged);
this.BorderWidthChanged += new EventHandler(BeatLoop_BorderWidthChanged);
this.BorderWidth = 1;
this.PositionControls();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
private void BeatLoop_ControlAdded(object sender, ControlEventArgs e)
{
if ( !( e.Control is Beat ) )
throw new ApplicationException( "BeatLoop can only host Beat controls." );
if ( this.Beats.Count > this.BeatCount )
throw new ApplicationException( "BeatLoop cannot host more controls than BeatCount." );
}
private void ResizeBeatsCollection()
{
int oldSize = this.Beats.Count;
int newSize = this.BeatCount;
if ( oldSize == newSize )
return;
if ( oldSize > newSize )
{
for( int i = oldSize - 1; i >= newSize; --i )
{
Beat b = this.Beats[i];
this.Controls.Remove( b );
this.Beats.RemoveAt( i );
b.Dispose();
}
}
else
{
for( int i = oldSize; i < newSize; ++i )
{
Beat b = new Beat( this );
this.Beats.Add( b );
}
}
this.PositionControls();
}
private void PositionControls()
{
if ( this.BeatCount <= 0 )
return;
Beats[0].Location = new Point( 0, 0 );
Beats[0].Size = new Size( this.BeatWidth, this.Height );
int width = 0;
for ( int i = 1; i < this.BeatCount; i++ )
{
width += this.BeatWidth;
this.Beats[i].Location = new Point( width + this.BeatSpacing, 0 );
this.Beats[i].Size = new Size( this.BeatWidth, this.Height );
}
}
public BeatState[] GetLoopState()
{
BeatState[] ret = new BeatState[ this.BeatCount ];
for ( int i = 0; i < this.BeatCount; i++ )
ret[i] = Beats[i].State;
return ret;
}
public void SetLoopState( BeatState[] state )
{
if ( state == null )
throw new ArgumentNullException( "state" );
if ( state.Length != this.BeatCount )
throw new ArgumentOutOfRangeException( "state", state.Length, "State length must equal BeatCount." );
for( int i = 0; i < this.BeatCount; i++ )
this.Beats[i].State = state[i];
this.Refresh();
}
public void SetLoopState( byte[] state )
{
if ( state == null )
throw new ArgumentNullException( "state" );
if ( state.Length != this.BeatCount )
throw new ArgumentOutOfRangeException( "state", state.Length, "State length must equal BeatCount." );
for( int i = 0; i < this.BeatCount; i++ )
this.Beats[i].State = (BeatState)state[i];
this.Refresh();
}
private void BeatLoop_ColorChanged(object sender, EventArgs e)
{
this.Invalidate();
}
private void BeatLoop_SizeChanged(object sender, EventArgs e)
{
this.SetBeatWidth();
this.Invalidate();
}
private void BeatLoop_BeatSpacingChanged(object sender, EventArgs e)
{
this.SetBeatWidth();
this.Invalidate();
}
private void BeatLoop_BeatCountChanged(object sender, EventArgs e)
{
this.ResizeBeatsCollection();
}
private void BeatLoop_BeatWidthChanged(object sender, EventArgs e)
{
this.PositionControls();
}
private void BeatLoop_BorderWidthChanged(object sender, EventArgs e)
{
this.PositionControls();
}
}
}
<file_sep>using ErnstTech.SoundCore.Synthesis.Expressions.AST;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis.Expressions.Optimizations
{
internal class ConstantFolder : IOptimizer
{
public ExpressionNode Optimize(ExpressionNode expression)
{
return expression switch
{
UnaryOpNode unaryOp => Optimize(unaryOp),
BinaryOpNode binOp => Optimize(binOp),
FunctionNode func => Optimize(func),
_ => expression
};
}
ExpressionNode Optimize(UnaryOpNode unaryOpNode)
{
unaryOpNode.InnerNode = Optimize(unaryOpNode.InnerNode);
if (unaryOpNode.InnerNode is NumberNode numberNode)
{
double result;
switch(unaryOpNode)
{
case NegateNode:
result = -numberNode.Value;
break;
case AbsoluteValueNode:
result = Math.Abs(numberNode.Value);
break;
default:
throw new InvalidOperationException($"Unexpected UnaryOpNode type: {unaryOpNode.GetType().Name}");
}
return new NumberNode(result);
}
return unaryOpNode;
}
ExpressionNode Optimize(BinaryOpNode binaryOpNode)
{
binaryOpNode.Left = Optimize(binaryOpNode.Left);
binaryOpNode.Right = Optimize(binaryOpNode.Right);
if (binaryOpNode.Left is NumberNode lhs && binaryOpNode.Right is NumberNode rhs)
{
var left = lhs.Value;
var right = rhs.Value;
double result;
switch(binaryOpNode)
{
case AddNode:
result = left + right;
break;
case SubtractNode:
result = left - right;
break;
case MultiplyNode:
result = left * right;
break;
case DivideNode:
result = left / right;
break;
case ExponentiationNode:
result = Math.Pow(left, right);
break;
default:
throw new InvalidOperationException($"Unexpected BinaryOpNode type: {binaryOpNode.GetType().Name}");
}
return new NumberNode(result);
}
return binaryOpNode;
}
ExpressionNode Optimize(FunctionNode functionNode)
{
functionNode.Arguments = functionNode.Arguments.Select(x => Optimize(x)).ToList();
return functionNode;
}
}
}
<file_sep>using System;
using System.Runtime.InteropServices;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for SoundCoreException.
/// </summary>
public class SoundCoreException : Exception
{
private int _NativeError;
public int NativeError
{
get { return _NativeError; }
}
private string _Detail = string.Empty;
public string Detail
{
get { return _Detail; }
}
public override string Message
{
get
{
return string.Format("{0}\n{1}", base.Message, Detail);
}
}
public SoundCoreException(string message) : this(message, 0)
{
}
public SoundCoreException(string message, int nativeError) : base(message)
{
_NativeError = nativeError;
if (nativeError != 0)
{
byte[] buffer = new byte[512];
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
WaveFormNative.waveOutGetErrorText(nativeError, ptr, buffer.Length);
_Detail = System.Text.Encoding.ASCII.GetString(buffer);
handle.Free();
}
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnaryFunc = System.Func<double, double>;
namespace ErnstTech.SoundCore.Synthesis
{
public class Sampler : IWaveFormGenerator
{
public long SamplesPerSecond { get; set; } = 44_100;
public UnaryFunc Function { get; set; }
public Sampler(UnaryFunc func)
{
if (func == null)
throw new ArgumentNullException(nameof(func));
this.Function = func;
}
public double[] Generate(long nSamples)
{
return this.Take((int)nSamples).ToArray();
}
public IEnumerator<double> GetEnumerator()
{
var delta = 1.0 / SamplesPerSecond;
long sample = 0;
while (true)
yield return this.Function(delta * sample++);
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis
{
public class SawWave
{
/// <summary>
/// Period, in seconds.
/// </summary>
public double Period { get; init; } = 1.0;
public double MaxValue { get; init; } = 1.0;
public double MinValue { get; init; } = -1.0;
public SawWave()
{ }
public double Sample(double time)
{
var local = time - Math.Truncate(time);
var slope = (MaxValue - MinValue) / Period;
return local * slope + MinValue;
}
public Func<double, double> Adapt() => (double t) => Sample(t);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis
{
public static class Waves
{
static readonly TriWave _Tri = new TriWave();
static readonly SawWave _Saw = new SawWave();
public static double Tri(double time) => _Tri.Sample(time);
public static double Saw(double time) => _Saw.Sample(time);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis.Expressions
{
/// <summary>
/// Interface for an audio synthesis expression parser.
/// Taking a mathematical expression creating an abstract syntax tree.
/// </summary>
public interface IExpressionParser
{
AST.ExpressionNode Parse(string expression);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Sampler
{
public class Beat
{
public const double Off = 0.0;
public const double Half = 0.5;
public const double Full = 1.0;
public ISampler? Sampler { get; set; }
public double Level { get; set; } = Off;
public long? QueuePoint { get; set; } = null;
public double Sample(long nSample) => Level * Sampler!.Sample(nSample - QueuePoint.GetValueOrDefault());
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Specialized;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using ErnstTech.SoundCore.Sampler;
namespace Synthesizer.Views
{
public class BeatLoopView : ObservableObject
{
public BeatLoop BeatLoop { get; init; }
public ObservableCollection<BeatView> Beats { get; init; }
public ISampler Sampler
{
get => BeatLoop.Sampler;
set => SetProperty(BeatLoop.Sampler, value, BeatLoop, (o, v) => o.Sampler = v);
}
public double BeatsPerMinute
{
get => BeatLoop.BeatsPerMinute;
set => SetProperty(BeatLoop.BeatsPerMinute, value, BeatLoop, (o, v) => o.BeatsPerMinute = v);
}
public double BeatDuration => BeatLoop.BeatDuration;
public double FullHeight
{
get => BeatLoop.FullHeight;
set => SetProperty(BeatLoop.FullHeight, value, BeatLoop, (o, v) => o.FullHeight = v);
}
public double HalfHeight
{
get => BeatLoop.HalfHeight;
set => SetProperty(BeatLoop.HalfHeight, value, BeatLoop, (o, v) => o.HalfHeight = v);
}
public Stream WAVStream => BeatLoop.WAVStream;
public BeatLoopView()
{
this.BeatLoop = new BeatLoop();
this.Beats = new ObservableCollection<BeatView>(Enumerable.Range(0, BeatLoop.BeatCount).Select(i => new BeatView(this.BeatLoop, i)));
this.Beats.CollectionChanged += OnBeatsChanged;
this.PropertyChanged += (o, e) => BeatLoop.InvalidateWAVStream();
}
private void OnBeatsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using ErnstTech.SoundCore.Synthesis;
using ErnstTech.SoundCore.Synthesis.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AntlrParser = ErnstTech.SoundCore.Synthesis.Expressions.Antlr.ExpressionParser;
namespace ErnstTech.SoundCore.Tests
{
[TestClass]
public class SynthExpressionGrammarTest
{
const double Epsilon = 1e-6;
readonly ExpressionBuilder _Builder = new ExpressionBuilder(new AntlrParser());
Func<double, double> Parse(string expression) => _Builder.Compile(expression);
[TestMethod]
public void TestConstant()
{
string expression = "2";
var func = Parse(expression);
Assert.IsNotNull(func);
Assert.AreEqual(2, func(0), Epsilon);
Assert.AreEqual(2, func(0.1), Epsilon);
Assert.AreEqual(2, func(2), Epsilon);
Assert.AreEqual(2, func(3.1), Epsilon);
}
[TestMethod]
public void TestPi()
{
var func = Parse("pi");
Assert.IsNotNull(func);
Assert.AreEqual(Math.PI, func(0), Epsilon);
Assert.AreEqual(Math.PI, func(1), Epsilon);
Assert.AreEqual(Math.PI, func(-1), Epsilon);
}
[TestMethod]
public void TestEuler()
{
var func = Parse("e");
Assert.IsNotNull(func);
Assert.AreEqual(Math.E, func(0), Epsilon);
Assert.AreEqual(Math.E, func(1), Epsilon);
Assert.AreEqual(Math.E, func(-1), Epsilon);
}
[TestMethod]
public void TestSimpleAdd()
{
var func = Parse("2+3");
Assert.IsNotNull(func);
Assert.AreEqual(5, func(0), Epsilon);
Assert.AreEqual(5, func(1), Epsilon);
Assert.AreEqual(5, func(-1), Epsilon);
}
[TestMethod]
public void TestSimpleSub()
{
var func = Parse("2-3");
Assert.IsNotNull(func);
Assert.AreEqual(-1, func(0), Epsilon);
Assert.AreEqual(-1, func(1), Epsilon);
Assert.AreEqual(-1, func(-1), Epsilon);
}
[TestMethod]
public void TestSimpleMul()
{
var func = Parse("2*3");
Assert.IsNotNull(func);
Assert.AreEqual(6, func(0), Epsilon);
Assert.AreEqual(6, func(1), Epsilon);
Assert.AreEqual(6, func(-1), Epsilon);
}
[TestMethod]
public void TestSimpleDiv()
{
var func = Parse("2/3");
Assert.IsNotNull(func);
Assert.AreEqual(2.0 / 3, func(0), Epsilon);
Assert.AreEqual(2.0 / 3, func(1), Epsilon);
Assert.AreEqual(2.0 / 3, func(-1), Epsilon);
}
[TestMethod]
public void TestTimeVar()
{
var func = Parse("t");
Assert.IsNotNull(func);
Assert.AreEqual(1, func(1), Epsilon);
Assert.AreEqual(2, func(2), Epsilon);
Assert.AreNotEqual(1, func(2), Epsilon);
}
[TestMethod]
public void TestSimpleExp()
{
var func = Parse("2^3");
Assert.IsNotNull(func);
Assert.AreEqual(8, func(0), Epsilon);
Assert.AreEqual(8, func(1), Epsilon);
Assert.AreEqual(8, func(2), Epsilon);
}
[TestMethod]
public void TestAddMul()
{
var func = Parse("2+3*4");
Assert.IsNotNull(func);
Assert.AreEqual(14, func(0), Epsilon);
Assert.AreEqual(14, func(1), Epsilon);
Assert.AreEqual(14, func(-1), Epsilon);
}
[TestMethod]
public void TestSubDiv()
{
var func = Parse("2-3/4");
Assert.IsNotNull(func);
Assert.AreEqual(1.25, func(0), Epsilon);
Assert.AreEqual(1.25, func(1), Epsilon);
Assert.AreEqual(1.25, func(-1), Epsilon);
}
[TestMethod]
public void TestTimeExpr()
{
var func = Parse("2*t");
Assert.IsNotNull(func);
Assert.AreEqual(0, func(0), Epsilon);
Assert.AreEqual(2, func(1), Epsilon);
Assert.AreEqual(-2, func(-1), Epsilon);
}
[TestMethod]
public void TestComplexExpression()
{
string expression = "2*cos(2*pi*t)";
var func = Parse(expression);
Assert.IsNotNull(func);
Assert.AreEqual(2, func(0), Epsilon);
Assert.AreEqual(1.618033988749895, func(0.1), Epsilon);
Assert.AreEqual(2, func(2), Epsilon);
Assert.AreEqual(1.6180339887498958, func(3.1), Epsilon);
}
[TestMethod]
public void TestSubExpression()
{
// string expression = "cos(2 * PI * (220 + 4 * cos(2 * PI * 10 * t)) * t) * 0.5";
string expression = "(2 + 4) * 2";
var func = Parse(expression);
Assert.IsNotNull(func);
Assert.AreEqual(12, func(0), Epsilon);
}
[TestMethod]
public void TestADSREnvelope()
{
string expression = "adsr()";
var func = Parse(expression);
Assert.IsNotNull(func);
Assert.AreEqual(0, func(0), Epsilon);
Assert.AreEqual(1, func(0.01), Epsilon);
Assert.AreEqual(0.95, func(0.02), Epsilon);
Assert.AreEqual(0.5, func(0.25), Epsilon);
Assert.AreEqual(0.5, func(0.26), Epsilon);
Assert.AreEqual(0.5, func(0.27), Epsilon);
Assert.AreEqual(0, func(0.50), Epsilon);
Assert.AreEqual(0, func(0.75), Epsilon);
}
[TestMethod]
public void TestSawWave()
{
string expression = "saw(t)";
var func = Parse(expression);
Assert.IsNotNull(func);
Assert.AreEqual(-1.0, func(0.0), Epsilon);
Assert.AreEqual(1.0, func(0.999_999_999), Epsilon);
Assert.AreEqual(0.0, func(0.5), Epsilon);
Assert.AreEqual(-1.0, func(1.0), Epsilon);
Assert.AreEqual(1.0, func(1.999_999_999), Epsilon);
Assert.AreEqual(0.0, func(1.5), Epsilon);
}
[TestMethod]
public void TestTriWave()
{
string expression = "tri(t)";
var func = Parse(expression);
Assert.IsNotNull(func);
Assert.AreEqual(-1.0, func(0.0), Epsilon);
Assert.AreEqual(1.0, func(0.50), Epsilon);
Assert.AreEqual(0.0, func(0.25), Epsilon);
Assert.AreEqual(0.0, func(0.75), Epsilon);
Assert.AreEqual(-1.0, func(1.0), Epsilon);
Assert.AreEqual(1.0, func(1.50), Epsilon);
Assert.AreEqual(0.0, func(1.25), Epsilon);
Assert.AreEqual(0.0, func(1.75), Epsilon);
}
[TestMethod]
public void TestSquareWave()
{
string expresion = "square(t)";
var func = Parse(expresion);
Assert.IsNotNull(func);
Assert.AreEqual(1.0, func(0.0), Epsilon);
Assert.AreEqual(1.0, func(0.25), Epsilon);
Assert.AreEqual(1.0, func(0.5), Epsilon);
Assert.AreEqual(-1.0, func(0.51), Epsilon);
Assert.AreEqual(-1.0, func(0.9999), Epsilon);
Assert.AreEqual(1.0, func(1.0), Epsilon);
Assert.AreEqual(1.0, func(1.25), Epsilon);
Assert.AreEqual(1.0, func(1.5), Epsilon);
Assert.AreEqual(-1.0, func(1.51), Epsilon);
Assert.AreEqual(-1.0, func(1.9999), Epsilon);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis.Expressions.AST
{
public abstract class BinaryOpNode : ExpressionNode
{
public ExpressionNode Left { get; set; }
public ExpressionNode Right { get; set; }
public BinaryOpNode(ExpressionNode left, ExpressionNode right)
{
Left = left;
Right = right;
}
}
public class AddNode : BinaryOpNode
{
public AddNode(ExpressionNode left, ExpressionNode right) : base(left, right) { }
}
public class SubtractNode : BinaryOpNode
{
public SubtractNode(ExpressionNode left, ExpressionNode right) : base(left, right) { }
}
public class MultiplyNode : BinaryOpNode
{
public MultiplyNode(ExpressionNode left, ExpressionNode right) : base(left, right) { }
}
public class DivideNode : BinaryOpNode
{
public DivideNode(ExpressionNode left, ExpressionNode right) : base(left, right) { }
}
public class ExponentiationNode : BinaryOpNode
{
public ExponentiationNode(ExpressionNode left, ExpressionNode right) : base(left, right) { }
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace ErnstTech.SynthesizerControls
{
/// <summary>
/// Summary description for GraphControl.
/// </summary>
public class GraphControl : System.Windows.Forms.Control
{
BindingList<PointF> _Points = new BindingList<PointF>();
/// <summary>
/// The list of points to draw.
/// </summary>
/// <value>An ordered list of points.</value>
public IList<PointF> Points
{
get { return this._Points; }
}
private List<PointF> _ScaledPoints = new List<PointF>(new List<PointF> ());
/// <summary>
/// <see cref="Points"/> scaled, flipped and translated
/// to fit within the drawing area.
/// </summary>
/// <remarks>
/// Provide and X and Y scale-factor.
/// </remarks>
/// <value>
/// A list of <seealso cref="PointF"/>.
/// </value>
protected List<PointF> ScaledPoints
{
get { return this._ScaledPoints; }
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public GraphControl()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
this._Points.ListChanged += new ListChangedEventHandler(_Points_ListChanged);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
void _Points_ListChanged(object sender, ListChangedEventArgs e)
{
this.ScalePoints();
this.Invalidate();
}
private void ScalePoints()
{
List<PointF> list = new List<PointF>(this.Points.Count);
if (this.Points.Count == 0)
goto end;
PointF pt = this.Points[0];
float min_x = pt.X;
float max_x = pt.X;
float min_y = pt.Y;
float max_y = pt.Y;
// Find the extremes
for (int i = 0; i < this.Points.Count; ++i)
{
pt = this.Points[i];
if (pt.X < min_x)
min_x = pt.X;
else if (pt.X > max_x)
max_x = pt.X;
if (pt.Y < min_y)
min_y = pt.Y;
else if (pt.Y > max_y)
max_y = pt.Y;
}
float height = Convert.ToSingle(this.Height);
float x_scale = this.Width / (max_x - min_x);
float y_scale = -height / (max_y - min_y);
foreach (PointF point in this.Points)
{
list.Add(new PointF(point.X * x_scale, (point.Y * y_scale + height)));
}
end:
this._ScaledPoints = new List<PointF>(list);
}
}
}
<file_sep>using System;
using ErnstTech.SoundCore.Synthesis.Expressions;
using ErnstTech.SoundCore.Synthesis.Expressions.Optimizations;
namespace ErnstTech.SoundCore.Synthesis
{
public class ExpressionBuilder
{
private readonly IExpressionParser _Parser;
private readonly IExpressionCompiler _Compiler;
private static readonly IOptimizer[] optimizers = new IOptimizer[]
{
new ConstantFolder(),
};
readonly IOptimizer[] _Optimizers = optimizers;
public ExpressionBuilder(IExpressionParser parser, IExpressionCompiler? compiler = null)
{
_Parser = parser;
_Compiler = compiler ?? new ExpressionEvaluator();
}
public Func<double, double> Compile(string expression)
{
expression = expression.ToLower();
var tree = _Parser.Parse(expression);
foreach (var opt in _Optimizers)
tree = opt.Optimize(tree);
return _Compiler.Compile(tree);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis
{
public class DrumGenerator
{
public double BaseFrequency { get; set; } = 111.0;
public double PhaseShift1 { get; set; } = 175.0;
public double PhaseShift2 { get; set; } = 224.0;
public Func<double, double>? Source { get; set; } = null;
public ADSREnvelope Envelope { get; init; } = new ADSREnvelope();
public DrumGenerator()
{ }
public Func<double, double> Adapt()
{
if (this.Source == null)
throw new InvalidOperationException("Source cannot be null.");
return Envelope.Adapt((double t) => Source(BaseFrequency * t + PhaseShift1) + Source(BaseFrequency * t + PhaseShift2));
}
}
}
<file_sep>using System;
using System.IO;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for RiffChunk.
/// </summary>
public sealed class RiffChunk : Chunk
{
public override string ID => "RIFF";
public WaveChunk Wave { get; init; }
internal RiffChunk(byte[] data) : base(data)
{
using var ms = new MemoryStream(Data);
using var reader = new BinaryReader(ms);
Wave = (WaveChunk)Chunk.GetChunk(reader);
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace ErnstTech.SoundCore.Synthesis
{
class SineWave : IWaveFormGenerator
{
/// <summary>
/// The frequency (in Hertz) of the sine wave.
/// </summary>
public double Frequency { get; private set; }
/// <summary>
/// The number of samples per second of the generator, floored.
/// </summary>
public long SampleRate { get; private set; } = 44_000;
public double Magnitude { get; private set; }
public SineWave(double frequency) : this(frequency, 1.0)
{ }
public SineWave(double frequency, double magnitude)
{
if (frequency <= 0.0)
throw new ArgumentException("Frequency must be positive.", "frequency");
this.Frequency = frequency;
this.Magnitude = magnitude;
}
public double[] Generate(long nSample)
{
if (nSample < 0)
throw new ArgumentOutOfRangeException("nSample", nSample, "Number of samples must be non-negative.");
long idx = 0;
double[] wave = new double[nSample];
foreach( double s in this )
{
wave[idx++] = s;
if (idx >= nSample)
break;
}
return wave;
}
public IEnumerator<double> GetEnumerator()
{
long pos = -1;
while (true)
{
pos = ++pos % this.SampleRate;
yield return Math.Sin(2 * Math.PI * pos / this.Frequency);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
<file_sep>// 'blah' is supported on 'windows'
#pragma warning disable CA1416
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpDX.XAudio2;
using System.Media;
namespace ErnstTech.DXSoundCore
{
public class WavePlayer : IDisposable
{
private bool disposedValue;
internal XAudio2 XAudio2 { get; init; }
internal MasteringVoice MasteringVoice { get; init; }
public WavePlayer()
{
XAudio2 = new XAudio2();
MasteringVoice = new MasteringVoice(XAudio2);
}
public void Play(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var player = new SoundPlayer(stream);
player.Play();
}
public void Stop()
{
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
this.MasteringVoice.Dispose();
this.XAudio2.Dispose();
}
disposedValue = true;
}
}
// // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
// ~WavePlayer()
// {
// // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
// Dispose(disposing: false);
// }
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Sampler
{
public class FuncSampler : ISampler
{
public int SampleRate { get; init; } = 48_000;
public double TimeDelta => 1.0 / SampleRate;
public int BitsPerSample { get; init; } = 32;
public long Length { get; set; } = -1;
public Func<double, double>? SampleFunc { get; init; }
public long GetSamples(double[] destination, long destOffset, long sampleStartOffset, long numSamples)
{
if (destination == null)
throw new ArgumentNullException(nameof(destination));
long count = 0;
for (long offset = sampleStartOffset; destOffset < destination.LongLength && numSamples > 0; ++destOffset, --numSamples, ++offset, ++count)
destination[destOffset] = Sample(offset);
return count;
}
public double Sample(long sampleOffset) => SampleFunc!.Invoke(sampleOffset * TimeDelta);
}
}
<file_sep>using System;
using System.Linq;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for FormatChunk.
/// </summary>
public sealed class FormatChunk : Chunk
{
public override string ID => "fmt ";
public short CompressionCode { get; private set; }
public short Channels { get; private set; }
public int SampleRate { get; private set; }
public int AverageBytesPerSecond { get; private set; }
public short BlockAlign { get; private set; }
public short SignificantBitsPerSample { get; private set; }
public short ExtraFormatBytesLength { get; private set; }
public byte[] ExtraFormatBytes { get; private set; }
internal FormatChunk(byte[] data) : base(data)
{
this.CompressionCode = ReadInt16(0);
this.Channels = ReadInt16(2);
this.SampleRate = ReadInt32(4);
this.AverageBytesPerSecond = ReadInt32(8);
this.BlockAlign = ReadInt16(10);
this.SignificantBitsPerSample = ReadInt16(12);
this.ExtraFormatBytesLength = ReadInt16(14);
this.ExtraFormatBytes = data.Skip(16).ToArray();
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveError.
/// </summary>
public sealed class WaveError
{
private const int MMSYSERR_BASE = 0;
public const int MMSYSERR_NOERROR = 0; /* no error */
public const int MMSYSERR_ERROR = (MMSYSERR_BASE + 1); /* unspecified error */
public const int MMSYSERR_BADDEVICEID = (MMSYSERR_BASE + 2); /* device ID out of range */
public const int MMSYSERR_NOTENABLED = (MMSYSERR_BASE + 3); /* driver failed enable */
public const int MMSYSERR_ALLOCATED = (MMSYSERR_BASE + 4); /* device already allocated */
public const int MMSYSERR_INVALHANDLE = (MMSYSERR_BASE + 5); /* device handle is invalid */
public const int MMSYSERR_NODRIVER = (MMSYSERR_BASE + 6); /* no device driver present */
public const int MMSYSERR_NOMEM = (MMSYSERR_BASE + 7); /* memory allocation error */
public const int MMSYSERR_NOTSUPPORTED = (MMSYSERR_BASE + 8); /* function isn't supported */
public const int MMSYSERR_BADERRNUM = (MMSYSERR_BASE + 9); /* error value out of range */
public const int MMSYSERR_INVALFLAG = (MMSYSERR_BASE + 10); /* invalid flag passed */
public const int MMSYSERR_INVALPARAM = (MMSYSERR_BASE + 11); /* invalid parameter passed */
public const int MMSYSERR_HANDLEBUSY = (MMSYSERR_BASE + 12); /* handle being used */
/* simultaneously on another */
/* thread = (eg callback); */
public const int MMSYSERR_INVALIDALIAS = (MMSYSERR_BASE + 13); /* specified alias not found */
public const int MMSYSERR_BADDB = (MMSYSERR_BASE + 14); /* bad registry database */
public const int MMSYSERR_KEYNOTFOUND = (MMSYSERR_BASE + 15); /* registry key not found */
public const int MMSYSERR_READERROR = (MMSYSERR_BASE + 16); /* registry read error */
public const int MMSYSERR_WRITEERROR = (MMSYSERR_BASE + 17); /* registry write error */
public const int MMSYSERR_DELETEERROR = (MMSYSERR_BASE + 18); /* registry delete error */
public const int MMSYSERR_VALNOTFOUND = (MMSYSERR_BASE + 19); /* registry value not found */
public const int MMSYSERR_NODRIVERCB = (MMSYSERR_BASE + 20); /* driver does not call DriverCallback */
public const int MMSYSERR_MOREDATA = (MMSYSERR_BASE + 21); /* more data to be returned */
private WaveError()
{}
public static string GetMessage( int waveError )
{
switch(waveError)
{
case WaveError.MMSYSERR_NOERROR:
return "No Error";
case WaveError.MMSYSERR_ERROR:
return "Unspecified Error";
case WaveError.MMSYSERR_BADDEVICEID:
return "Device ID out of range.";
case WaveError.MMSYSERR_NOTENABLED:
return "Driver failed enable.";
case WaveError.MMSYSERR_ALLOCATED:
return "Device already allocated.";
case WaveError.MMSYSERR_INVALHANDLE:
return "Device handle is invalid.";
case WaveError.MMSYSERR_NODRIVER:
return "No device driver present.";
case WaveError.MMSYSERR_NOMEM:
return "Memory allocation error.";
case WaveError.MMSYSERR_NOTSUPPORTED:
return "Function is not supported.";
case WaveError.MMSYSERR_BADERRNUM:
return "Error value out of range.";
case WaveError.MMSYSERR_INVALFLAG:
return "Invalid flag passed.";
case WaveError.MMSYSERR_INVALPARAM:
return "Invalid parameter passed.";
case WaveError.MMSYSERR_HANDLEBUSY:
return "Handle is in use by another tread.";
case WaveError.MMSYSERR_INVALIDALIAS:
return "Specified alias not found.";
case WaveError.MMSYSERR_BADDB:
return "Bad registry database.";
case WaveError.MMSYSERR_KEYNOTFOUND:
return "Registry key not found.";
case WaveError.MMSYSERR_READERROR:
return "Registry read error.";
case WaveError.MMSYSERR_WRITEERROR:
return "Registry write error.";
case WaveError.MMSYSERR_DELETEERROR:
return "Registry delete error.";
case WaveError.MMSYSERR_VALNOTFOUND:
return "Registry value not found.";
case WaveError.MMSYSERR_NODRIVERCB:
return "Driver does not call DriverCallback.";
case WaveError.MMSYSERR_MOREDATA:
return "More data to be returned.";
default:
return string.Format( "Unknown error: Error number out of range.\nError Number: 0x{0:x8}", waveError);
}
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore.Synthesis.Expressions
{
interface IOptimizer
{
AST.ExpressionNode Optimize(AST.ExpressionNode expression);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using ErnstTech.SoundCore.Synthesis;
namespace Synthesizer.Views
{
public class BaseDrumView : ObservableObject
{
public ObservableCollection<double> Harmonics { get; init; } = new ObservableCollection<double>(BaseDrumGenerator.SampleHarmonics);
private BaseDrumGenerator _Generator;
public ADSREnvelope Envelope { get; init; } = new ADSREnvelope();
public BaseDrumView()
{
this._Generator = new BaseDrumGenerator(new TriWave().Sample, Harmonics);
}
public Func<double, double> Adapt() => Envelope.Adapt(_Generator.Adapt());
}
}
<file_sep>using System;
using System.Runtime.InteropServices;
namespace ErnstTech.SoundCore
{
/// <remarks>
/// <see>ms-help://MS.PSDK.1033/multimed/mmstr_625u.htm</see>
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
public struct WaveFormatEx
{
public FormatTag format;
public short nChannels;
public int nSamplesPerSec;
public int nAvgBytesPerSec;
public short nBlockAlign;
public short nBitsPerSample;
public int cbSize;
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis
{
public class SquareWave
{
public double DutyCycle { get; init; }
public SquareWave(double dutyCycle = 0.5)
{
if (dutyCycle < 0 || dutyCycle > 1.0)
throw new ArgumentOutOfRangeException(nameof(dutyCycle), dutyCycle, "dutyCycle must be in the closed range [0, 1.0].");
this.DutyCycle = dutyCycle;
}
public double Sample(double time)
{
time -= Math.Truncate(time);
return time <= DutyCycle ? 1.0 : -1.0;
}
public Func<double, double> Adapt() => Sample;
public Func<double, double> Adapt(Func<double, double> func) => (double t) => Sample(func(t));
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace ErnstTech.SoundCore.Synthesis
{
/// <summary>
/// Defines the minimum requirements for a class that
/// generates a wave form.
/// </summary>
interface IWaveFormGenerator : IEnumerable<double>
{
/// <summary>
/// Generates a waveform for the specified number of samples.
/// </summary>
/// <param name="nSamples">The number of samples to generate.</param>
/// <returns>An array of <seealso cref="double"/> containing the generated form.</returns>
double[] Generate(long nSamples);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ErnstTech.SoundCore.Synthesis.Expressions.AST;
namespace ErnstTech.SoundCore.Synthesis.Expressions
{
internal class ExpressionEvaluator : IExpressionCompiler
{
class Visitor : Visitor<Func<double, double>>
{
ExpressionEvaluator _Parent;
public Visitor(ExpressionEvaluator parent) => _Parent = parent;
public override Func<double, double> Visit(TimeVariableNode node) => (double t) => t;
public override Func<double, double> Visit(NumberNode node)
{
double value = node.Value;
return (double t) => value;
}
(Func<double, double>, Func<double,double>) GetChildren(BinaryOpNode node) => (Visit(node.Left), Visit(node.Right));
public override Func<double, double> Visit(AddNode node)
{
var (left, right) = GetChildren(node);
return (double t) => left(t) + right(t);
}
public override Func<double, double> Visit(SubtractNode node)
{
var (left, right) = GetChildren(node);
return (double t) => left(t) - right(t);
}
public override Func<double, double> Visit(MultiplyNode node)
{
var (left, right) = GetChildren(node);
return (double t) => left(t) * right(t);
}
public override Func<double, double> Visit(DivideNode node)
{
var (left, right) = GetChildren(node);
return (double t) => left(t) / right(t);
}
public override Func<double, double> Visit(ExponentiationNode node)
{
var (left, right) = GetChildren(node);
return (double t) => Math.Pow(left(t), right(t));
}
public override Func<double, double> Visit(AbsoluteValueNode node)
{
var child = Visit(node);
return (double t) => Math.Abs(child(t));
}
public override Func<double, double> Visit(NegateNode node)
{
var child = Visit(node);
return (double t) => -child(t);
}
public override Func<double, double> Visit(FunctionNode node)
{
if (_Parent.Handlers.TryGetValue(node.Name, out var handler))
{
var args = node.Arguments.Select(x => Visit(x)).ToList();
return handler.Handle(args);
}
throw new ArgumentException($"Unknown function: '{node.Name}'.", nameof(node));
}
}
public abstract class FunctionHandler
{
public abstract string Name { get; }
public virtual int MinArguments => 0;
public virtual int MaxArguments => -1;
public Func<double, double> Handle(List<Func<double, double>> arguments)
{
if (MinArguments >= 0 && arguments.Count < MinArguments)
throw new ArgumentException($"Function '{Name}' does not have minimum number '{MinArguments}' of arguments.", nameof(arguments));
if (MaxArguments >= 0 && arguments.Count > MaxArguments)
throw new ArgumentException($"Function '{Name}' exceeds the maximum number '{MaxArguments}' of arguments.", nameof(arguments));
return DoHandle(arguments);
}
protected abstract Func<double, double> DoHandle(List<Func<double, double>> arguments);
}
abstract class Func1Handler : FunctionHandler
{
public override int MinArguments => 1;
public override int MaxArguments => 1;
protected abstract Func<double, double> Impl { get; }
protected override Func<double, double> DoHandle(List<Func<double, double>> arguments)
{
var arg = arguments.First();
return (double t) => Impl(arg(t));
}
}
abstract class Func2Handler : FunctionHandler
{
public override int MinArguments => 2;
public override int MaxArguments => 2;
protected abstract Func<double, double, double> Impl { get; }
protected override Func<double, double> DoHandle(List<Func<double, double>> arguments)
{
var arg0 = arguments[0];
var arg1 = arguments[1];
return (double t) => Impl(arg0(t), arg1(t));
}
}
class SineHandler : Func1Handler
{
public override string Name => "sin";
protected override Func<double, double> Impl => Math.Sin;
}
class CosineHandler : Func1Handler
{
public override string Name => "cos";
protected override Func<double, double> Impl => Math.Cos;
}
class TangentHandler : Func1Handler
{
public override string Name => "tan";
protected override Func<double, double> Impl => Math.Tan;
}
class AbsoluteValueHandler : Func1Handler
{
public override string Name => "abs";
protected override Func<double, double> Impl => Math.Abs;
}
class Log2Handler : Func1Handler
{
public override string Name => "log2";
protected override Func<double, double> Impl => Math.Log2;
}
class Log10Handler : Func1Handler
{
public override string Name => "log10";
protected override Func<double, double> Impl => Math.Log10;
}
class NaturalLogHandler : Func1Handler
{
public override string Name => "ln";
protected override Func<double, double> Impl => Math.Log;
}
class SawHandler : Func1Handler
{
public override string Name => "saw";
readonly SawWave _Wave = new();
protected override Func<double, double> Impl => _Wave.Sample;
}
class TriHandler : Func1Handler
{
public override string Name => "tri";
readonly TriWave _Wave = new();
protected override Func<double, double> Impl { get => _Wave.Sample; }
}
class SquareWaveHandler : FunctionHandler
{
public override string Name => "square";
public override int MinArguments => 1;
public override int MaxArguments => 2;
protected override Func<double, double> DoHandle(List<Func<double, double>> arguments)
{
var arg = arguments[0];
var wave = arguments.Count == 2 ? new SquareWave(arguments[1](0)) : new SquareWave();
return (double t) => wave.Sample(arg(t));
}
}
class MovingAverageHandler : FunctionHandler
{
public override string Name => "movavg";
public override int MinArguments => 2;
public override int MaxArguments => 2;
protected override Func<double, double> DoHandle(List<Func<double, double>> arguments)
{
// First argument is expected to be a constant, number of samples to average over
var smoother = new Smoother((int)arguments[0](0));
// Second argument is the value to be sampled & averaged.
var arg = arguments[1];
return (double t) => smoother.Sample(arg(t));
}
}
class SquareRootHandler : Func1Handler
{
public override string Name => "sqrt";
protected override Func<double, double> Impl => Math.Sqrt;
}
class PowerHandler : Func2Handler
{
public override string Name => "pow";
protected override Func<double, double, double> Impl => Math.Pow;
}
class ADSRHandler : FunctionHandler
{
public override string Name => "adsr";
public override int MinArguments => 0;
public override int MaxArguments => 6;
protected override Func<double, double> DoHandle(List<Func<double, double>> arguments)
{
var adsr = new ADSREnvelope();
switch(arguments.Count)
{
case 6:
adsr.SustainHeight = arguments[5](0);
goto case 5;
case 5:
adsr.AttackHeight = arguments[4](0);
goto case 4;
case 4:
adsr.DecayTime = arguments[3](0);
goto case 3;
case 3:
adsr.SustainTime = arguments[2](0);
goto case 2;
case 2:
adsr.ReleaseTime = arguments[1](0);
goto case 1;
case 1:
adsr.AttackTime = arguments[0](0);
goto case 0;
case 0:
break;
default:
throw new InvalidOperationException(); // unreachable
}
return (double t) => adsr.Factor(t);
}
}
static readonly FunctionHandler[] _Builtins = new FunctionHandler[]
{
new SineHandler(),
new CosineHandler(),
new TangentHandler(),
new AbsoluteValueHandler(),
new Log2Handler(),
new Log10Handler(),
new NaturalLogHandler(),
new SawHandler(),
new TriHandler(),
new SquareWaveHandler(),
new MovingAverageHandler(),
new PowerHandler(),
new SquareRootHandler(),
new ADSRHandler(),
};
Dictionary<string, FunctionHandler> _Handlers = _Builtins.ToDictionary(x => x.Name);
/// <summary>
/// A read-only dictionary of registered function handlers.
/// </summary>
public IReadOnlyDictionary<string, FunctionHandler> Handlers { get => _Handlers; }
/// <summary>
/// Evaluate an abstract syntax tree represented by <paramref name="abstractSyntaxTree"/>.
/// </summary>
/// <param name="abstractSyntaxTree">The <see cref="ExpressionNode"/> to evaluate.</param>
/// <returns>
/// A <see cref="Func<double, double>"/> generated from <paramref name="abstractSyntaxTree"/> as a function of time.
/// </returns>
public Func<double, double> Compile(ExpressionNode abstractSyntaxTree) => new Visitor(this).Visit(abstractSyntaxTree);
/// <summary>
/// Registers a new function handler.
/// </summary>
/// <param name="handler">The <see cref="FunctionHandler" /> to register.</param>
/// <param name="overwrite">When <c>true</c>, overwrites an existing handler. Otherwise does not.</param>
/// <returns>Returns <c>true</c> when the handler was registered, <c>false</c> otherwise.</returns>
public bool RegisterHandler(FunctionHandler handler, bool overwrite = false)
{
if (_Handlers.TryAdd(handler.Name, handler))
return true;
if (!overwrite)
return false;
_Handlers[handler.Name] = handler;
return true;
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveHeaderFlags.
/// </summary>
[Flags]
public enum WaveHeaderFlags : int
{
Done = 0x00000001, /* done bit */
Prepared = 0x00000002, /* set if this header has been prepared */
BeginLoop = 0x00000004, /* loop start block */
EndLoop = 0x00000008, /* loop end block */
InQueue = 0x00000010 /* reserved for driver */
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis.Expressions.AST
{
public abstract class UnaryOpNode : ExpressionNode
{
public ExpressionNode InnerNode { get; set; }
public UnaryOpNode(ExpressionNode innerNode)
{
InnerNode = innerNode;
}
}
public class NegateNode : UnaryOpNode
{
public NegateNode(ExpressionNode innerNode) : base(innerNode) { }
}
public class AbsoluteValueNode : UnaryOpNode
{
public AbsoluteValueNode(ExpressionNode innerNode) : base(innerNode) { }
}
}
<file_sep>using System;
namespace ConduciveTech.Math
{
/// <summary>
/// Summary description for Complex.
/// </summary>
public struct Complex
{
public double Real { get; init set; }
public double Imaginary { get; set; }
public double Magnitude { get; set; }
public double Angle { get; set; }
private Complex()
{
}
public Complex(double real, double imaginary)
{
this._Real = real;
this._Imaginary = imaginary;
}
public static Complex FromPolarCoordinates( double magnitude, double angle )
{
Complex comp = new Complex();
comp._Magnitude = magnitude;
comp._Angle = angle;
comp._Real = (magnitude * System.Math.Cos(angle));
comp._Imaginary = (magnitude * System.Math.Sin(angle));
comp._State[MAGNITUDE_CALCULATED | ANGLE_CALCULATED] = true;
return comp;
}
private void CalculateMagnitude()
{
this._Magnitude = System.Math.Sqrt(
System.Math.Pow(this.Real, 2.0) +
System.Math.Pow(this.Imaginary, 2.0));
this._State[MAGNITUDE_CALCULATED] = true;
}
private void CalculateAngle()
{
this._Angle = System.Math.Atan(this.Imaginary / this.Real);
this._State[ANGLE_CALCULATED] = true;
}
public static Complex operator !( Complex left )
{
return new Complex(left.Real, -left.Imaginary);
}
public static Complex operator +( Complex left, Complex right )
{
return new Complex(
(left.Real + right.Real),
(left.Imaginary + right.Imaginary) );
}
public static Complex operator -( Complex left, Complex right )
{
return new Complex(
(left.Real - right.Real),
(left.Imaginary - right.Imaginary) );
}
public static Complex operator *( Complex left, Complex right )
{
return new Complex(
( left.Real * right.Real - left.Imaginary * right.Imaginary ),
( left.Real * right.Imaginary + left.Imaginary * right.Real ) );
}
public static Complex operator /( Complex quotient, Complex divisor )
{
if ( divisor.Magnitude == 0 )
throw new DivideByZeroException( "Divisor's magnitude is zero." );
return Complex.FromPolarCoordinates(
(quotient.Magnitude / divisor.Magnitude),
(quotient.Angle - divisor.Angle ) );
}
public override int GetHashCode()
{
return (Real.GetHashCode() ^ Imaginary.GetHashCode());
}
public static bool operator ==( Complex left, Complex right )
{
return ((left.Real == right.Real) && (left.Imaginary == right.Imaginary));
}
public static bool operator !=( Complex left, Complex right )
{
return !(left == right);
}
public bool Equals(Complex complex)
{
return this == complex;
}
public override bool Equals(object obj)
{
if (!(obj is Complex))
return false;
return this.Equals((Complex)obj);
}
public override string ToString()
{
return string.Format( "{0} j{1}", this.Real, this.Imaginary );
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
public enum AudioMode : short
{
Mono = 1,
Stereo = 2
}
}<file_sep>#region Using directives
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
#endregion
namespace ErnstTech.SynthesizerControls
{
public class LineGraph : GraphControl
{
public LineGraph()
{
this.BackColor = Color.White;
this.ForeColor = Color.Black;
}
protected override void OnPaint(PaintEventArgs e)
{
using (Brush b = new SolidBrush(this.BackColor))
{
e.Graphics.FillRectangle(b, e.ClipRectangle);
}
if (this.ScaledPoints.Count < 2)
return;
PointF[] points = new PointF[this.ScaledPoints.Count];
this.ScaledPoints.CopyTo(points, 0);
using (Pen p = new Pen( this.ForeColor, 1.0f ))
{
e.Graphics.DrawLines(p, points);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis.Expressions.AST
{
public class FunctionNode : ExpressionNode
{
public string Name { get; set; }
public List<ExpressionNode> Arguments { get; set; }
public FunctionNode(string name, List<ExpressionNode> arguments)
{
Name = name;
Arguments = arguments;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using ErnstTech.SoundCore;
namespace ErnstTech.SynthesizerControls
{
/// <summary>
/// Summary description for BeatBox.
/// </summary>
public class BeatBox : System.Windows.Forms.UserControl
{
private int MaxPointHeight
{
get
{
switch(this.SampleQuality)
{
case AudioBits.Bits8:
return byte.MaxValue;
case AudioBits.Bits16:
return ushort.MaxValue;
default:
throw new IndexOutOfRangeException( "SampleQuality is out of range." );
}
}
}
const int MaxPointWidth = 100;
private System.Windows.Forms.TrackBar tbTotalTime;
private System.Windows.Forms.Panel pnWaveForm;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.ListView lvPoints;
private System.Windows.Forms.Button btnAddPoint;
private System.Windows.Forms.Button btnRemovePoints;
private System.Windows.Forms.TrackBar tbPointWidth;
private System.Windows.Forms.TrackBar tbPointHeight;
private System.Windows.Forms.ColumnHeader chIndex;
private System.Windows.Forms.ColumnHeader chX;
private System.Windows.Forms.ColumnHeader chY;
// private BindingList<PointF> _Points = new BindingList<PointF>();
public IList<PointF> Points
{
get { return this.waveGraph.Points; }
}
int SelectedPointIndex = -1;
private AudioBits _SampleQuality = AudioBits.Bits16;
private LineGraph waveGraph;
private ThinSlider thinSlider1;
public AudioBits SampleQuality
{
get{ return _SampleQuality; }
set
{
if ( value != AudioBits.Bits16 && value != AudioBits.Bits8 )
throw new ArgumentOutOfRangeException( "SampleQuality", value, "Sample quality must be 8 or 16 bits." );
_SampleQuality = value;
}
}
private float _BaseFrequency = 200;
public float BaseFrequency
{
get{ return _BaseFrequency; }
set
{
if ( value <= 0 )
throw new ArgumentOutOfRangeException( "BaseFrequency", value, "BaseFrequency must be a positive number." );
_BaseFrequency = value;
}
}
public BeatBox()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
this.tbPointHeight.Enabled = false;
this.tbPointHeight.Maximum = MaxPointHeight;
this.tbPointWidth.Enabled = false;
this.tbPointWidth.Maximum = MaxPointWidth;
this.ParentChanged += new EventHandler(BeatBox_ParentChanged);
lvPoints.SelectedIndexChanged += new EventHandler(lvPoints_SelectedIndexChanged);
Points.Add( new PointF( 0.0f, 0.0f ) );
Points.Add( new PointF( (float)(MaxPointWidth / 4.0f), Convert.ToSingle( MaxPointHeight ) ) );
Points.Add( new PointF( (float)(MaxPointWidth / 2.0f), Convert.ToSingle( MaxPointHeight ) ) );
Points.Add( new PointF( Convert.ToSingle( MaxPointWidth ), 0.0f) );
BindPointsView();
pnWaveForm.Refresh();
this.btnRemovePoints.Enabled = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tbTotalTime = new System.Windows.Forms.TrackBar();
this.pnWaveForm = new System.Windows.Forms.Panel();
this.waveGraph = new ErnstTech.SynthesizerControls.LineGraph();
this.lvPoints = new System.Windows.Forms.ListView();
this.chIndex = new System.Windows.Forms.ColumnHeader("");
this.chX = new System.Windows.Forms.ColumnHeader("");
this.chY = new System.Windows.Forms.ColumnHeader("");
this.btnAddPoint = new System.Windows.Forms.Button();
this.btnRemovePoints = new System.Windows.Forms.Button();
this.tbPointWidth = new System.Windows.Forms.TrackBar();
this.tbPointHeight = new System.Windows.Forms.TrackBar();
this.thinSlider1 = new ErnstTech.SynthesizerControls.ThinSlider();
((System.ComponentModel.ISupportInitialize)(this.tbTotalTime)).BeginInit();
this.pnWaveForm.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.tbPointWidth)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tbPointHeight)).BeginInit();
this.SuspendLayout();
//
// tbTotalTime
//
this.tbTotalTime.Location = new System.Drawing.Point(0, 256);
this.tbTotalTime.Maximum = 100;
this.tbTotalTime.Name = "tbTotalTime";
this.tbTotalTime.Size = new System.Drawing.Size(464, 45);
this.tbTotalTime.TabIndex = 5;
this.tbTotalTime.TickFrequency = 10;
//
// pnWaveForm
//
this.pnWaveForm.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pnWaveForm.BackColor = System.Drawing.Color.Transparent;
this.pnWaveForm.Controls.Add(this.waveGraph);
this.pnWaveForm.Location = new System.Drawing.Point(0, 0);
this.pnWaveForm.Name = "pnWaveForm";
this.pnWaveForm.Size = new System.Drawing.Size(464, 120);
this.pnWaveForm.TabIndex = 7;
//
// waveGraph
//
this.waveGraph.BackColor = System.Drawing.Color.White;
this.waveGraph.Dock = System.Windows.Forms.DockStyle.Fill;
this.waveGraph.ForeColor = System.Drawing.Color.Black;
this.waveGraph.Location = new System.Drawing.Point(0, 0);
this.waveGraph.Name = "waveGraph";
this.waveGraph.Size = new System.Drawing.Size(464, 120);
this.waveGraph.TabIndex = 0;
this.waveGraph.Text = "lineGraph1";
//
// lvPoints
//
this.lvPoints.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.chIndex,
this.chX,
this.chY});
this.lvPoints.FullRowSelect = true;
this.lvPoints.Location = new System.Drawing.Point(0, 120);
this.lvPoints.MultiSelect = false;
this.lvPoints.Name = "lvPoints";
this.lvPoints.Size = new System.Drawing.Size(160, 97);
this.lvPoints.TabIndex = 8;
this.lvPoints.View = System.Windows.Forms.View.Details;
//
// chIndex
//
this.chIndex.Text = "Index";
//
// chX
//
this.chX.Text = "X";
//
// chY
//
this.chY.Text = "Y";
//
// btnAddPoint
//
this.btnAddPoint.Location = new System.Drawing.Point(0, 224);
this.btnAddPoint.Name = "btnAddPoint";
this.btnAddPoint.TabIndex = 9;
this.btnAddPoint.Text = "Add";
this.btnAddPoint.Click += new System.EventHandler(this.btnAddPoint_Click);
//
// btnRemovePoints
//
this.btnRemovePoints.Location = new System.Drawing.Point(80, 224);
this.btnRemovePoints.Name = "btnRemovePoints";
this.btnRemovePoints.TabIndex = 10;
this.btnRemovePoints.Text = "Remove";
this.btnRemovePoints.Click += new System.EventHandler(this.btnRemovePoints_Click);
//
// tbPointWidth
//
this.tbPointWidth.Location = new System.Drawing.Point(208, 176);
this.tbPointWidth.Margin = new System.Windows.Forms.Padding(2, 3, 3, 3);
this.tbPointWidth.Name = "tbPointWidth";
this.tbPointWidth.TabIndex = 11;
this.tbPointWidth.TickFrequency = 10;
this.tbPointWidth.Scroll += new System.EventHandler(this.tbPointWidth_Scroll);
//
// tbPointHeight
//
this.tbPointHeight.Location = new System.Drawing.Point(160, 120);
this.tbPointHeight.Margin = new System.Windows.Forms.Padding(3, 3, 1, 3);
this.tbPointHeight.Name = "tbPointHeight";
this.tbPointHeight.Orientation = System.Windows.Forms.Orientation.Vertical;
this.tbPointHeight.Size = new System.Drawing.Size(45, 104);
this.tbPointHeight.TabIndex = 12;
this.tbPointHeight.TickFrequency = 10;
this.tbPointHeight.Scroll += new System.EventHandler(this.tbPointHeight_Scroll);
//
// thinSlider1
//
this.thinSlider1.BackColor = System.Drawing.Color.White;
this.thinSlider1.ForeColor = System.Drawing.Color.Navy;
this.thinSlider1.Location = new System.Drawing.Point(340, 143);
this.thinSlider1.Maximum = 100;
this.thinSlider1.Minimum = 0;
this.thinSlider1.Name = "thinSlider1";
this.thinSlider1.Size = new System.Drawing.Size(10, 74);
this.thinSlider1.TabIndex = 13;
this.thinSlider1.Text = "thinSlider1";
this.thinSlider1.Value = 0;
//
// BeatBox
//
this.Controls.Add(this.thinSlider1);
this.Controls.Add(this.tbPointHeight);
this.Controls.Add(this.tbPointWidth);
this.Controls.Add(this.btnRemovePoints);
this.Controls.Add(this.btnAddPoint);
this.Controls.Add(this.lvPoints);
this.Controls.Add(this.pnWaveForm);
this.Controls.Add(this.tbTotalTime);
this.Name = "BeatBox";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Size = new System.Drawing.Size(464, 296);
((System.ComponentModel.ISupportInitialize)(this.tbTotalTime)).EndInit();
this.pnWaveForm.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.tbPointWidth)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tbPointHeight)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void BindPointsView()
{
this.lvPoints.Items.Clear();
this.lvPoints.BeginUpdate();
for( int i = 0, length = Points.Count; i < length; i++ )
{
ListViewItem item = new ListViewItem();
item.Text = i.ToString();
item.SubItems.Add( Points[i].X.ToString() );
item.SubItems.Add( Points[i].Y.ToString() );
lvPoints.Items.Add( item );
}
this.lvPoints.EndUpdate();
foreach (ColumnHeader ch in lvPoints.Columns)
{
ch.Width = -3;
}
lvPoints.Refresh();
}
private void tbPointHeight_Scroll(object sender, System.EventArgs e)
{
PointF p = this.Points[this.SelectedPointIndex];
p.Y = Convert.ToSingle( tbPointHeight.Value );
this.Points[this.SelectedPointIndex] = p;
this.BindPointsView();
}
private void tbPointWidth_Scroll(object sender, System.EventArgs e)
{
PointF p = this.Points[this.SelectedPointIndex];
p.X = Convert.ToSingle( tbPointWidth.Value );
this.Points[this.SelectedPointIndex] = p;
this.BindPointsView();
}
private void btnAddPoint_Click(object sender, System.EventArgs e)
{
this.Points.Add( new Point( 0, 0 ) );
BindPointsView();
}
private void lvPoints_SelectedIndexChanged(object sender, EventArgs e)
{
if ( lvPoints.SelectedIndices.Count <= 0 )
{
btnRemovePoints.Enabled = false;
tbPointHeight.Enabled = false;
tbPointWidth.Enabled = false;
this.SelectedPointIndex = -1;
}
else
{
btnRemovePoints.Enabled = ( this.Points.Count > 3 );
tbPointHeight.Enabled = true;
tbPointWidth.Enabled = true;
this.SelectedPointIndex = lvPoints.SelectedIndices[0];
PointF p = Points[this.SelectedPointIndex];
tbPointHeight.Value = Convert.ToInt32( p.Y );
tbPointWidth.Value = Convert.ToInt32( p.X );
}
}
private void btnRemovePoints_Click(object sender, System.EventArgs e)
{
Points.RemoveAt( this.SelectedPointIndex );
this.SelectedPointIndex = -1;
this.btnRemovePoints.Enabled = false;
BindPointsView();
}
private void BeatBox_ParentChanged(object sender, EventArgs e)
{
this.pnWaveForm.Refresh();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis.Expressions
{
public interface IExpressionCompiler
{
Func<double, double> Compile(AST.ExpressionNode tree);
}
}
<file_sep>using System;
using System.Runtime.InteropServices;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveOutDeviceCapabilities.
/// </summary>
public class WaveOutDeviceCapabilities
{
[StructLayout(LayoutKind.Sequential)]
private class WAVEOUTCAPS
{
private const int MAXPNAMELEN = 32;
public short ManufacturerID = 0;
public short ProductID = 0;
public short DriverVersion = 0;
public char[] ProductName = new char[MAXPNAMELEN];
public int Formats = 0;
public short Channels = 0;
public short Reserved = 0;
public int SupportedFunctionality = 0;
}
[DllImport( "winmm.dll", EntryPoint="waveOutGetDevCapsW", SetLastError=true, CharSet=CharSet.Unicode )]
private static extern int waveOutGetDevCaps( int device, WAVEOUTCAPS caps, int size );
private WAVEOUTCAPS _Capabilities;
public WaveOutDeviceCapabilities( int device )
{
this._Capabilities = new WAVEOUTCAPS();
int result = waveOutGetDevCaps( device, this._Capabilities, Marshal.SizeOf( this._Capabilities ) );
if ( result != WaveError.MMSYSERR_NOERROR )
throw new SoundCoreException( WaveError.GetMessage( result ), result );
}
}
}
<file_sep>using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WavePlayer.
/// </summary>
public class WavePlayer : IDisposable
{
private AutoResetEvent _DonePlaying = new AutoResetEvent(false);
private WaveBufferEmptyHandler _FillerDelegate;
private WaveFormat _Format;
public WaveFormat Format
{
get { return _Format; }
}
private bool _IsPlaying = false;
public bool IsPlaying
{
get { return _IsPlaying; }
}
private Stream _DataStream;
private BinaryReader _Reader;
private WaveOutBuffer _RootBuffer;
// private WaveOutBuffer[] _Buffers;
private long _StartPosition;
private int _Device = -1; // Default to system default
public int Device
{
get { return _Device; }
set
{
if (IsPlaying)
throw new SoundCoreException("Device ID cannot be set while device is in use.");
if (value < -1 || value >= NumDevices)
throw new ArgumentOutOfRangeException(string.Format("Device must be between -1 and {0}, inclusive.", NumDevices));
_Device = value;
}
}
#if DEBUG
private long _FillCount = 0;
#endif
public static int NumDevices
{
get { return WaveFormNative.waveOutGetNumDevs(); }
}
private IntPtr _DeviceHandle;
// private Thread _PlayThread;
// private Thread _FillThread;
private int _BufferLength = 4000;
/// <summary>
/// The length of the buffer in milliseconds.
/// </summary>
public int BufferLength
{
get { return _BufferLength; }
set
{
if (value <= 0)
throw new ArgumentException("BufferLength must be a positive integer.", "value");
_BufferLength = value;
}
}
public int BufferCount
{
get { return 4; }
}
/// <summary>
/// The calculated size of the buffer, in bytes.
/// </summary>
public int BufferSize
{
get
{
int length = Convert.ToInt32(Convert.ToDouble(_Format.AverageBytesPerSecond * BufferLength) / 1000.0);
int waste = length % _Format.BlockAlignment;
length += _Format.BlockAlignment - waste;
return length;
}
}
private byte[] _StreamBuffer;
private WaveOutProcDelegate _CallBack = new WaveOutProcDelegate(WaveOutBuffer.WaveOutCallback);
public WavePlayer(short channels, int rate, short bitsPerSample, WaveBufferEmptyHandler filler)
{
_Format = new WaveFormat(channels, rate, bitsPerSample);
if (filler == null)
throw new ArgumentNullException("filler");
_FillerDelegate = filler;
}
public WavePlayer(Stream s)
{
if (s == null)
throw new ArgumentNullException("s");
_DataStream = s;
_Reader = new BinaryReader(_DataStream, System.Text.Encoding.ASCII);
if (!SeekChunk("RIFF"))
throw new SoundCoreException("Could not find 'RIFF' Chunk.");
_Reader.ReadInt32();
if (!SeekChunk("WAVE"))
throw new SoundCoreException("Could not find 'WAVE' Chunk.");
_Format = new WaveFormat(_DataStream);
if (!SeekChunk("data"))
throw new SoundCoreException("Could not find 'fmt ' Chunk.");
_Reader.ReadInt32();
_StartPosition = _DataStream.Position;
_StreamBuffer = new byte[this.BufferSize];
this._FillerDelegate = new WaveBufferEmptyHandler(BufferFiller);
}
private bool SeekChunk(string id)
{
if (_DataStream == null)
throw new NullReferenceException("Cannot perform SeekChunk if _DataStream is null.");
byte[] buffer = new byte[4];
string temp;
while (_DataStream.Length != _DataStream.Position)
{
_Reader.Read(buffer, 0, 4);
temp = System.Text.Encoding.ASCII.GetString(buffer, 0, 4);
if (temp == id)
return true;
}
return false;
}
private void AllocateBuffers()
{
this._RootBuffer = new WaveOutBuffer(this, this._DeviceHandle, this.BufferSize);
var prev = this._RootBuffer;
for (int i = 1; i < this.BufferCount; i++)
{
prev.NextBuffer = new WaveOutBuffer(this, this._DeviceHandle, this.BufferSize);
prev = prev.NextBuffer;
}
prev.NextBuffer = _RootBuffer;
}
private void FreeBuffers()
{
this._RootBuffer?.Dispose();
}
public void Play()
{
#if DEBUG
this._FillCount = 0;
#endif
if (_DataStream != null)
{
_DataStream.Position = _StartPosition;
}
WaveFormatEx format = Format.GetFormat();
int result = WaveFormNative.waveOutOpen(out _DeviceHandle, Device, ref format, _CallBack, 0,
(int)DeviceOpenFlags.CallbackFunction);
if (result != WaveError.MMSYSERR_NOERROR)
throw new SoundCoreException(WaveError.GetMessage(result), result);
_IsPlaying = true;
AllocateBuffers();
// Perform Initial fill
WaveOutBuffer current = _RootBuffer;
do
{
FillBuffer(current);
current.BufferFilled();
current = current.NextBuffer;
} while (current != _RootBuffer);
_RootBuffer.Play();
//
// _FillThread = new Thread( new ThreadStart( FillProc ) );
//// _FillThread.Priority = ThreadPriority.Highest;
// _FillThread.Start();
//
// _PlayThread = new Thread( new ThreadStart( PlayProc ) );
// _PlayThread.Start();
}
public void Stop()
{
#if DEBUG
Debug.WriteLine(string.Format("FilleBuffer called {0} times.", this._FillCount));
#endif
if (IsPlaying)
{
_IsPlaying = false;
_DonePlaying.WaitOne();
// // Force all buffers to open mutexs
// foreach(WaveOutBuffer buffer in _Buffers)
// buffer.Stop();
//
// WaitForAllBuffers();
//
// _FillThread.Join();
// _PlayThread.Join();
FreeBuffers();
}
}
internal void FillBuffer(WaveOutBuffer buffer)
{
#if DEBUG
this._FillCount++;
#endif
WaveBufferEmptyEventArgs args = new WaveBufferEmptyEventArgs(buffer.Data, buffer.Length);
_FillerDelegate(buffer, args);
// Stop playing if we no longer have data.
if (args.BytesWritten == 0)
Stop();
}
private void BufferFiller(object sender, WaveBufferEmptyEventArgs args)
{
lock (_StreamBuffer)
{
args.BytesWritten = _Reader.Read(_StreamBuffer, 0, args.Length);
// int index = 0;
// int length = args.Length;
//
// while( index < length && _DataStream.Length != _DataStream.Position )
// _StreamBuffer[index++] = _Reader.ReadByte();
//
// args.BytesWritten = length;
//
for (int i = args.BytesWritten, length = args.Length; i < length; i++)
_StreamBuffer[i] = 0;
Marshal.Copy(_StreamBuffer, 0, args.Buffer, args.Length);
}
}
//
// private void WaitForAllBuffers()
// {
// for ( int i = 0; i < BufferCount; i++ )
// _Buffers[i].WaitUntilCompleted();
// }
internal void SignalDone()
{
this._DonePlaying.Set();
}
//
// private void PlayProc()
// {
// int index = 0;
//
// // Loop as long as we have data to play and we haven't been told to stop.
// while(IsPlaying)
// {
// // Play the buffer
// _Buffers[index].Play();
//
// // Wait until the buffer's done playing.
// _Buffers[index].WaitUntilCompleted();
//
// // Move to next buffer
// index = ++index % BufferCount;
// }
// }
//
//
// private void FillProc()
// {
// int index = 0;
//
// // Continue as long as we've got data.
// while ( IsPlaying )
// {
// // Wait until the buffer is empty
// _Buffers[index].WaitForBufferEmpty();
//
// // Fill the current buffer
// FillBuffer( _Buffers[index] );
//
// // Signal the buffer that it has data
// _Buffers[index].BufferFilled();
//// Thread.Sleep(0);
//
// // Move to the next buffer
// index = ++index % BufferCount;
// }
// }
//
#region IDisposable Members
public void Dispose()
{
Stop();
if (_DataStream != null)
_DataStream.Close();
}
#endregion
}
}
<file_sep># synth
Digital audio synthesis.
This is a repository of my exploration of digital audio synthesis. No pre-recorded samples, everything derived mathematically. This is not a production quality solution, nor is it intended to be so. There is no commitment to a stable API or ABI.
## Environment
The solution currently targets .Net Framework 5 (VS2019 Update 4) on Windows. Most of the core synthesis parts (ErnstTech.SoundCore) should work cross-platform. The test application (Synthesizer) requires Windows for audio playback. It is otherwise a basic WinForms application.
## Dependencies
The only external dependency other than the .Net Framework is Antlr4. There is a soft dependency on SharpDX for exploratory work with DirectX playback limited to the XAudioDynSample application. This will likely go away in the future.
## Testing
Test coverage, at this point, is minimal. The only automated testing is around expression parsing and signal generation. The automated tests in ErnstTech.SoundCore.Tests should not require Windows to run.
## History
This repository was a recently resurfaced old project, originally targetting .Net 1.x and managed DirectX. Work on modernizing it is on going, but on an as-needed basis.
<file_sep>using System;
using System.Drawing;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using ErnstTech.SynthesizerControls;
#if ERNST_DX_AUDIO
using ErnstTech.DXSoundCore;
#else
using System.Media;
#pragma warning disable CA1416
#endif
namespace ErnstTech.Synthesizer
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnTestWaveStream;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Button btnPlay;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.Button btnCapTest;
private BeatLoop blLoop;
private System.Windows.Forms.Button btnTestSynthesis;
private ThinSlider testSlider;
private Track track1;
private BeatBox beatBox1;
private Button btnShowWaveForm;
private Button btnViewWaveForm;
private Label label1;
private TextBox txtExpression;
private Button btnParse;
private TextBox txtDuration;
private Label label2;
private Button btnExprShow;
#if ERNST_DX_AUDIO
WavePlayer _Player;
#else
SoundPlayer _Player;
#endif
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
blLoop = new BeatLoop();
this.Controls.Add(blLoop);
blLoop.Left = 0;
blLoop.Top = 0;
blLoop.SetLoopState(new byte[16] { 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0 });
this.testSlider = new ThinSlider();
this.Controls.Add(this.testSlider);
this.testSlider.Left = 5;
this.testSlider.Top = 30;
this.testSlider.Size = new Size(10, 100);
this.testSlider.BackColor = Color.White;
this.testSlider.ForeColor = Color.Navy;
this._Player = new SoundPlayer();
this.Refresh();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
#if ERNST_DX_AUDIO
#else
_Player?.Stop();
_Player?.Dispose();
#endif
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnTestWaveStream = new System.Windows.Forms.Button();
this.btnPlay = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.btnCapTest = new System.Windows.Forms.Button();
this.btnTestSynthesis = new System.Windows.Forms.Button();
this.btnShowWaveForm = new System.Windows.Forms.Button();
this.track1 = new ErnstTech.SynthesizerControls.Track();
this.beatBox1 = new ErnstTech.SynthesizerControls.BeatBox();
this.btnViewWaveForm = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.txtExpression = new System.Windows.Forms.TextBox();
this.btnParse = new System.Windows.Forms.Button();
this.txtDuration = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.btnExprShow = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnTestWaveStream
//
this.btnTestWaveStream.Location = new System.Drawing.Point(112, 64);
this.btnTestWaveStream.Margin = new System.Windows.Forms.Padding(2, 3, 3, 3);
this.btnTestWaveStream.Name = "btnTestWaveStream";
this.btnTestWaveStream.Size = new System.Drawing.Size(112, 23);
this.btnTestWaveStream.TabIndex = 1;
this.btnTestWaveStream.Text = "Test Wave Stream";
this.btnTestWaveStream.Click += new System.EventHandler(this.btnTestWaveStream_Click);
//
// btnPlay
//
this.btnPlay.Location = new System.Drawing.Point(232, 64);
this.btnPlay.Name = "btnPlay";
this.btnPlay.Size = new System.Drawing.Size(75, 23);
this.btnPlay.TabIndex = 2;
this.btnPlay.Text = "Play";
this.btnPlay.Click += new System.EventHandler(this.btnPlay_Click);
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(320, 64);
this.btnStop.Name = "btnStop";
this.btnStop.Size = new System.Drawing.Size(75, 23);
this.btnStop.TabIndex = 2;
this.btnStop.Text = "Stop";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// btnCapTest
//
this.btnCapTest.Location = new System.Drawing.Point(402, 64);
this.btnCapTest.Name = "btnCapTest";
this.btnCapTest.Size = new System.Drawing.Size(112, 23);
this.btnCapTest.TabIndex = 3;
this.btnCapTest.Text = "Capabilities Test";
this.btnCapTest.Click += new System.EventHandler(this.btnCapTest_Click);
//
// btnTestSynthesis
//
this.btnTestSynthesis.Location = new System.Drawing.Point(13, 64);
this.btnTestSynthesis.Margin = new System.Windows.Forms.Padding(3, 3, 1, 3);
this.btnTestSynthesis.Name = "btnTestSynthesis";
this.btnTestSynthesis.Size = new System.Drawing.Size(96, 23);
this.btnTestSynthesis.TabIndex = 4;
this.btnTestSynthesis.Text = "Test Synthesizer";
this.btnTestSynthesis.Click += new System.EventHandler(this.button1_Click);
//
// btnShowWaveForm
//
this.btnShowWaveForm.Location = new System.Drawing.Point(13, 93);
this.btnShowWaveForm.Name = "btnShowWaveForm";
this.btnShowWaveForm.Size = new System.Drawing.Size(96, 23);
this.btnShowWaveForm.TabIndex = 7;
this.btnShowWaveForm.Text = "Show Waveform";
this.btnShowWaveForm.Click += new System.EventHandler(this.btnShowWaveForm_Click);
//
// track1
//
this.track1.BeatCount = 16;
this.track1.Location = new System.Drawing.Point(16, 144);
this.track1.Name = "track1";
this.track1.Size = new System.Drawing.Size(176, 144);
this.track1.TabIndex = 6;
//
// beatBox1
//
this.beatBox1.BaseFrequency = 200F;
this.beatBox1.Location = new System.Drawing.Point(224, 192);
this.beatBox1.Name = "beatBox1";
this.beatBox1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.beatBox1.SampleQuality = ErnstTech.SoundCore.AudioBits.Bits16;
this.beatBox1.Size = new System.Drawing.Size(480, 296);
this.beatBox1.TabIndex = 0;
//
// btnViewWaveForm
//
this.btnViewWaveForm.Location = new System.Drawing.Point(112, 93);
this.btnViewWaveForm.Name = "btnViewWaveForm";
this.btnViewWaveForm.Size = new System.Drawing.Size(112, 23);
this.btnViewWaveForm.TabIndex = 8;
this.btnViewWaveForm.Text = "View Wave Form";
this.btnViewWaveForm.Click += new System.EventHandler(this.btnViewWaveForm_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(232, 94);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(89, 15);
this.label1.TabIndex = 9;
this.label1.Text = "Expression Test:";
//
// txtExpression
//
this.txtExpression.Location = new System.Drawing.Point(232, 113);
this.txtExpression.Name = "txtExpression";
this.txtExpression.Size = new System.Drawing.Size(309, 23);
this.txtExpression.TabIndex = 10;
this.txtExpression.Text = "cos(2 * PI * (220 + 4 * cos(2 * PI * 10 * t)) * t) * 0.5";
//
// btnParse
//
this.btnParse.Location = new System.Drawing.Point(483, 143);
this.btnParse.Name = "btnParse";
this.btnParse.Size = new System.Drawing.Size(75, 23);
this.btnParse.TabIndex = 11;
this.btnParse.Text = "Test";
this.btnParse.UseVisualStyleBackColor = true;
this.btnParse.Click += new System.EventHandler(this.btnParse_Click);
//
// txtDuration
//
this.txtDuration.Location = new System.Drawing.Point(232, 142);
this.txtDuration.Name = "txtDuration";
this.txtDuration.Size = new System.Drawing.Size(51, 23);
this.txtDuration.TabIndex = 12;
this.txtDuration.Text = "1.0";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(289, 147);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(109, 15);
this.label2.TabIndex = 9;
this.label2.Text = "Test Duration (secs)";
//
// btnExprShow
//
this.btnExprShow.Location = new System.Drawing.Point(402, 142);
this.btnExprShow.Name = "btnExprShow";
this.btnExprShow.Size = new System.Drawing.Size(75, 23);
this.btnExprShow.TabIndex = 13;
this.btnExprShow.Text = "Show";
this.btnExprShow.UseVisualStyleBackColor = true;
this.btnExprShow.Click += new System.EventHandler(this.btnExprShow_Click);
//
// Form1
//
this.ClientSize = new System.Drawing.Size(712, 486);
this.Controls.Add(this.btnExprShow);
this.Controls.Add(this.txtDuration);
this.Controls.Add(this.btnParse);
this.Controls.Add(this.txtExpression);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnViewWaveForm);
this.Controls.Add(this.btnShowWaveForm);
this.Controls.Add(this.track1);
this.Controls.Add(this.btnTestSynthesis);
this.Controls.Add(this.btnCapTest);
this.Controls.Add(this.btnPlay);
this.Controls.Add(this.btnTestWaveStream);
this.Controls.Add(this.beatBox1);
this.Controls.Add(this.btnStop);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnTestWaveStream_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open Wave Audio...";
ofd.Filter = "Wave Files (*.wav)|*.wav";
ofd.FilterIndex = 1;
if (ofd.ShowDialog() == DialogResult.OK)
{
var stream = new System.IO.FileStream(ofd.FileName,
System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read, 16 * 1024);
#if ERNST_DX_AUDIO
_Player = new WavePlayer();
_Player = new WavePlayer( this, stream );
_Player.BufferLength = 1000;
#else
_Player.Stream = stream;
_Player.Play();
#endif
}
}
private void btnPlay_Click(object sender, System.EventArgs e)
{
_Player?.Play();
}
private void btnStop_Click(object sender, System.EventArgs e)
{
_Player?.Stop();
}
private void btnCapTest_Click(object sender, System.EventArgs e)
{
// MessageBox.Show( WavePlayer.NumDevices.ToString() );
//
// WaveOutDeviceCapabilities cap = new WaveOutDeviceCapabilities( 0 );
}
private void button1_Click(object sender, System.EventArgs e)
{
ErnstTech.SoundCore.WaveForm form = new ErnstTech.SoundCore.WaveForm(new ErnstTech.SoundCore.WaveFormat(2, 44100, 16));
form.BaseFrequency = 200;
Point[] points = new Point[this.beatBox1.Points.Count];
for (int i = 0, length = points.Length; i < length; ++i)
{
PointF pt = this.beatBox1.Points[i];
points[i] = new Point(Convert.ToInt32(pt.X), Convert.ToInt32(pt.Y));
}
form.Points.AddRange(points);
System.IO.Stream s = form.GenerateWave();
#if ERNST_DX_AUDIO
System.Diagnostics.Debug.Assert(false);
WavePlayer player = new WavePlayer( this, s );
player.Play();
#else
this._Player.Stop();
this._Player.Stream = s;
this._Player.Play();
#endif
}
private void Form1_Load(object sender, System.EventArgs e)
{
}
private void beatLoop1_Click(object sender, System.EventArgs e)
{
}
private void btnShowWaveForm_Click(object sender, EventArgs e)
{
ErnstTech.SoundCore.WaveForm form = new ErnstTech.SoundCore.WaveForm(new ErnstTech.SoundCore.WaveFormat(2, 44100, 16));
form.BaseFrequency = 100;
System.IO.Stream s = form.GenerateWave();
using (WaveFormView view = new WaveFormView(s))
{
view.ZoomFactor = 0.25f;
view.ShowDialog();
}
s.Close();
}
private void btnViewWaveForm_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
System.IO.Stream s = ofd.OpenFile();
using (WaveFormView view = new WaveFormView(s))
{
//view.ZoomFactor = 0.25f;
view.ShowDialog();
}
s.Close();
}
}
}
static IEnumerable<float> ToEnumerable(int sampleRate, Func<double, double> func)
{
var count = 0;
var delta = 1.0 / sampleRate;
while (true)
yield return (float)func(count++ * delta);
}
Stream GenerateFromExpression()
{
const int sampleRate = 44100;
var parser = new SoundCore.Synthesis.ExpressionParser();
var func = parser.Parse(txtExpression.Text);
var duration = double.Parse(this.txtDuration.Text);
int nSamples = (int)(sampleRate * duration);
var dataSize = nSamples * sizeof(float);
var format = new SoundCore.WaveFormat(1, sampleRate, 32);
var ms = new MemoryStream(dataSize + SoundCore.WaveFormat.HeaderSize);
new SoundCore.WaveWriter(ms, sampleRate).Write(nSamples, ToEnumerable(sampleRate, func));
ms.Position = 0;
return ms;
}
private void btnParse_Click(object sender, EventArgs e) =>
new SoundPlayer(GenerateFromExpression()).Play();
private void btnExprShow_Click(object sender, EventArgs e)
{
using var s = GenerateFromExpression();
//using var v = new global::Synthesizer.WaveFormView2(s);
using var v = new WaveFormView(s);
v.ShowDialog();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ErnstTech.SoundCore.Synthesis
{
public class DigitalFilter
{
double[] _Source;
public DigitalFilter(double[] source)
{
if (source == null)
throw new ArgumentNullException("source");
_Source = source;
}
public double[] Process( double[] sourceFactors, double[] feedbackFactors )
{
double[] retvalue = new double[_Source.LongLength];
if (sourceFactors == null)
sourceFactors = new double[0];
if ( feedbackFactors == null )
feedbackFactors = new double[0];
long sourceCount = sourceFactors.LongLength;
long feedbackCount = feedbackFactors.LongLength;
for (long i = 0, length = _Source.LongLength; i < length; ++i )
{
double sample = this._Source[i];
double value = sample;
for (long h = 0; h < sourceCount; ++h)
{
if (i < h || ( i - h ) >= sourceCount)
break;
value += sample * sourceFactors[i - h] * sample;
}
for (long h = 0; h < feedbackCount; ++h)
{
if (i < h || ( i - h ) >= feedbackCount)
break;
value += sample * feedbackFactors[i - h] * sample;
}
retvalue[i] = value;
}
return retvalue;
}
double GetValue(int index, int offset)
{
long position = index - offset;
return ( position < 0 ) ? 0.0 : _Source[position];
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for Wave.
/// </summary>
public class WaveFormat
{
public const int HeaderSize = 44;
private WaveFormatEx _WaveFormat;
static readonly FormatTag[] _SupportedFormatTags = new[]
{
FormatTag.WAVE_FORMAT_PCM,
FormatTag.WAVE_FORMAT_IEEE_FLOAT,
};
public FormatTag FormatTag { get; set; } = FormatTag.WAVE_FORMAT_PCM;
private short _Channels = 2;
private const short MinChannels = 1;
private const short MaxChannels = 2;
public short Channels
{
get { return _Channels; }
set
{
if (value < MinChannels || value > MaxChannels)
throw new ArgumentOutOfRangeException("Channels", value, string.Format("Value must be greater than or equal to {0} and less than or equal to {1}.",
MinChannels, MaxChannels));
_Channels = value;
}
}
private readonly IList<int> AllowedSamplingRates = new int[]{
8000,
11025,
22050,
44100,
48000,
};
private int _SamplesPerSecond = 44100;
public int SamplesPerSecond
{
get { return _SamplesPerSecond; }
set
{
if (!AllowedSamplingRates.Contains(value))
throw new ArgumentOutOfRangeException("SamplesPerSecond", value, "Specified value is not an allowed sampling rate for PCM audio.");
_SamplesPerSecond = value;
}
}
static readonly IList<short> _SupportedBitsPerSample = new short[]{ 8, 16, 32 };
private short _BitsPerSample = 16;
public short BitsPerSample
{
get { return _BitsPerSample; }
set
{
if (!_SupportedBitsPerSample.Contains(value))
throw new ArgumentOutOfRangeException("BitsPerSample", value, "BitsPerSample must be 8, 16 or 32 for PCM audio.");
_BitsPerSample = value;
}
}
public short BlockAlignment
{
get
{
return Convert.ToInt16(this.Channels * this.BitsPerSample / 8);
}
}
public int AverageBytesPerSecond
{
get
{
return (int)(this.BlockAlignment * this.SamplesPerSecond);
}
}
public WaveFormat()
{
Init();
}
public WaveFormat(short channels, int samplesPerSecond, short bitsPerSample)
{
this.Channels = channels;
this.SamplesPerSecond = samplesPerSecond;
this.BitsPerSample = bitsPerSample;
Init();
}
private int ReadInt32(Stream stream)
{
short lo = ReadInt16(stream);
short hi = ReadInt16(stream);
return (((int)hi) << 16) | ((ushort)lo);
}
private short ReadInt16(Stream stream)
{
return (short)((stream.ReadByte()) | (stream.ReadByte() << 8));
}
public WaveFormat(Stream stream)
{
byte[] buffer = new byte[4];
stream.Read(buffer, 0, 4);
string id = Encoding.ASCII.GetString(buffer);
if (id != "fmt ")
throw new SoundCoreException(string.Format("Error reading format from BinaryReader: Unknown format 0x{0:X2}{1:X2}{2:X2}{3:X2} ('{4}').",
buffer[0], buffer[1], buffer[2], buffer[3], System.Text.Encoding.ASCII.GetString(buffer)));
int size = ReadInt32(stream);
this.FormatTag = (FormatTag)ReadInt16(stream);
if (!_SupportedFormatTags.Contains(this.FormatTag))
throw new SoundCoreException($"Unsupported format tag: {this.FormatTag}");
this.Channels = ReadInt16(stream);
this.SamplesPerSecond = ReadInt32(stream);
int avgBps = ReadInt32(stream);
short blockAlign = ReadInt16(stream);
this.BitsPerSample = ReadInt16(stream);
if (size > 16)
{
ushort extraBytes = (ushort)ReadInt16(stream);
while (extraBytes > 0)
{
stream.ReadByte();
--extraBytes;
}
}
}
private void Init()
{
_WaveFormat = new WaveFormatEx();
SetFormatValues();
}
private void SetFormatValues()
{
_WaveFormat.format = FormatTag.WAVE_FORMAT_PCM;
_WaveFormat.nSamplesPerSec = this.SamplesPerSecond;
_WaveFormat.nBitsPerSample = this.BitsPerSample;
_WaveFormat.nAvgBytesPerSec = this.AverageBytesPerSecond;
_WaveFormat.nBlockAlign = this.BlockAlignment;
_WaveFormat.nChannels = this.Channels;
_WaveFormat.cbSize = 0; // This member is ignored, anyway
}
public WaveFormatEx GetFormat()
{
SetFormatValues();
return this._WaveFormat;
}
static readonly byte[] _RIFF = Encoding.ASCII.GetBytes("RIFF");
static readonly byte[] _WAVE = Encoding.ASCII.GetBytes("WAVE");
static readonly byte[] _FMT = Encoding.ASCII.GetBytes("fmt ");
static readonly byte[] _DATA = Encoding.ASCII.GetBytes("data");
public void WriteHeader(Stream stream, int dataSize)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanWrite)
throw new ArgumentException("Stream is not writable.", nameof(stream));
if (dataSize < 0)
throw new ArgumentOutOfRangeException(nameof(dataSize), dataSize, "dataSize must be a nonnegative integer.");
const int chunkSize = 36;
const int fmtSize = 16;
BinaryWriter writer = new BinaryWriter(stream, Encoding.ASCII);
writer.Write(_RIFF);
writer.Write(dataSize + chunkSize);
writer.Write(_WAVE);
writer.Write(_FMT);
writer.Write(fmtSize);
writer.Write((short)this.FormatTag);
writer.Write((short)this.Channels);
writer.Write((int)this.SamplesPerSecond);
writer.Write((int)this.AverageBytesPerSecond);
writer.Write((short)this.BlockAlignment);
writer.Write((short)this.BitsPerSample);
writer.Write(_DATA);
writer.Write(dataSize);
}
}
}
<file_sep>using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace ErnstTech.SynthesizerControls
{
/// <summary>
/// Summary description for Beat.
/// </summary>
public class Beat : System.Windows.Forms.Control
{
protected BeatLoop BeatLoop
{
get{ return this.Parent as BeatLoop; }
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private BeatState _State = BeatState.Off;
public BeatState State
{
get{ return _State; }
set
{
switch(value)
{
case BeatState.Half:
case BeatState.Off:
case BeatState.On:
break;
default:
throw new ArgumentOutOfRangeException( "value", value, "Value is does not correspond to a valid BeatState enum value." );
}
_State = value;
}
}
protected override Size DefaultSize
{
get
{
return new Size( 20, 20 );
}
}
/// <summary>
/// This constructor ensures that we are only ever contained
/// by a BeatLoop.
/// </summary>
/// <param name="parent">
/// The parent <see cref="BeatLoop"/> control.
///
/// Cannot be null.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when <see cref="parent"/> is null.
/// </exception>
internal Beat( BeatLoop parent )
{
if ( parent == null )
throw new ArgumentNullException( "parent" );
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
this.MouseDown += new MouseEventHandler(Beat_MouseDown);
parent.Controls.Add( this );
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
protected override void OnPaint(PaintEventArgs pe)
{
Rectangle r = new Rectangle( 0, 0, this.Width - 1, this.Height - 1 );
using( Brush b = new SolidBrush( this.GetFillColor() ) )
{
pe.Graphics.FillRectangle( b, r );
}
int border = this.BeatLoop.BorderWidth;
if ( border > 0 )
{
using( Pen p = new Pen( this.BeatLoop.BorderColor, Convert.ToSingle( border ) ) )
{
pe.Graphics.DrawRectangle( p, r );
}
}
// Calling the base class OnPaint
base.OnPaint(pe);
}
protected virtual Color GetFillColor()
{
switch(this.State)
{
case BeatState.On:
return this.BeatLoop.OnColor;
case BeatState.Off:
return this.BeatLoop.OffColor;
case BeatState.Half:
return this.BeatLoop.HalfColor;
default:
throw new IndexOutOfRangeException( "State has an unknown or unsupported value." );
}
}
private void Beat_ParentChanged(object sender, EventArgs e)
{
if ( this.Parent != null )
{
if ( !( this.Parent is BeatLoop ) )
throw new InvalidOperationException( "Beat control may only be contained by a BeatLoop." );
this.Height = this.Parent.Height;
}
}
private void Beat_MouseDown(object sender, MouseEventArgs e)
{
switch( this.State )
{
case BeatState.Off:
this.State = BeatState.Half;
break;
case BeatState.Half:
this.State = BeatState.On;
break;
case BeatState.On:
this.State = BeatState.Off;
break;
default:
this.State = BeatState.Off;
break;
}
this.Refresh();
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
public enum WaveFormOutputMessage : int
{
Open = 0x3BB,
Close = 0x3BC,
Done = 0x3BD
}
}
<file_sep>using System;
using System.Runtime.InteropServices;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveOutCapabilities.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct WaveOutCapabilities
{
public short ManufacturerID;
public short ProductID;
public WaveDeviceDriverVersion DriverVersion;
public string Product;
public int Formats;
public short Channels;
public short Reserved;
public int Support;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ErnstTech.SoundCore
{
/// <summary>
/// </summary>
public class WaveWriter
{
public Stream Stream { get; init; }
public int SampleRate { get; init; }
public WaveWriter(Stream stream, int sampleRate)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanWrite)
throw new ArgumentException("Stream must be writable.", nameof(stream));
if (sampleRate <= 0)
throw new ArgumentException("SampleRate must be positive.", nameof(sampleRate));
this.Stream = stream;
this.SampleRate = sampleRate;
}
/// <summary>
/// Write the channels to the stream.
/// </summary>
/// <param name="length">The length of the longest channel, in number of samples.</param>
/// <param name="channels">The channels to be written.</param>
public void Write(long length, params IEnumerable<float>[] channels)
{
if (length < 0)
throw new ArgumentException("Length must be non-negative.", nameof(length));
if (channels.Length <= 0)
throw new ArgumentException("Must have at least one channel.");
var format = new WaveFormat
{
BitsPerSample = 32,
Channels = (short)channels.Length,
SamplesPerSecond = this.SampleRate,
FormatTag = FormatTag.WAVE_FORMAT_IEEE_FLOAT,
};
var dataSize = (long)(length * sizeof(float) * channels.Length);
format.WriteHeader(this.Stream, (int)dataSize);
var enumerators = channels.Select(c => c.GetEnumerator()).ToArray<IEnumerator<float>?>();
for (; length > 0; --length)
{
for (int i = 0; i < enumerators.Length; ++i)
{
if (!enumerators[i]?.MoveNext() ?? false)
enumerators[i] = null;
this.Stream.Write(BitConverter.GetBytes(enumerators[i]?.Current ?? 0));
}
}
}
/// <summary>
/// Write the channels to the stream.
/// </summary>
/// <param name="length">The length of the longest channel, in number of samples.</param>
/// <param name="channels">The channels to be written.</param>
public void Write(long length, params IEnumerable<short>[] channels)
{
if (length < 0)
throw new ArgumentException("Length must be non-negative.", nameof(length));
if (channels.Length <= 0)
throw new ArgumentException("Must have at least one channel.");
var format = new WaveFormat
{
BitsPerSample = 16,
Channels = (short)channels.Length,
SamplesPerSecond = this.SampleRate
};
var dataSize = (long)(length * sizeof(float) * channels.Length);
format.WriteHeader(this.Stream, (int)dataSize);
var enumerators = channels.Select(c => c.GetEnumerator()).ToArray<IEnumerator<short>?>();
for (; length > 0; --length)
{
for (int i = 0; i < enumerators.Length; ++i)
{
if (!enumerators[i]?.MoveNext() ?? false)
enumerators[i] = null;
this.Stream.Write(BitConverter.GetBytes(enumerators[i]?.Current ?? (short)0));
}
}
}
/// <summary>
/// Write the channels to the stream.
/// </summary>
/// <param name="length">The length of the longest channel, in number of samples.</param>
/// <param name="channels">The channels to be written.</param>
public void Write(long length, params IEnumerable<byte>[] channels)
{
if (length < 0)
throw new ArgumentException("Length must be non-negative.", nameof(length));
if (channels.Length <= 0)
throw new ArgumentException("Must have at least one channel.");
var format = new WaveFormat
{
BitsPerSample = 8,
Channels = (short)channels.Length,
SamplesPerSecond = this.SampleRate
};
var dataSize = (long)(length * sizeof(byte) * channels.Length);
format.WriteHeader(this.Stream, (int)dataSize);
var enumerators = channels.Select(c => c.GetEnumerator()).ToArray<IEnumerator<byte>?>();
for (; length > 0; --length)
{
for (int i = 0; i < enumerators.Length; ++i)
{
if (!enumerators[i]?.MoveNext() ?? false)
enumerators[i] = null;
this.Stream.WriteByte(enumerators[i]?.Current ?? (byte)0);
}
}
}
public static Stream Write(int sampleRate, int numSamples, Func<double, double> func)
{
var ms = new MemoryStream();
var writer = new WaveWriter(ms, sampleRate);
var samples = Enumerable.Range(0, numSamples).Select(i => (float)func(i / (double)sampleRate));
writer.Write(numSamples, samples);
ms.Position = 0;
return ms;
}
}
}
<file_sep>using System;
using System.IO;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveChunk.
/// </summary>
public sealed class WaveChunk : Chunk
{
public override string ID => "WAVE";
public FormatChunk Format { get; init; }
public DataChunk WaveData { get; init; }
internal WaveChunk(byte[] data ) : base(data)
{
using var ms = new MemoryStream(Data);
using var reader = new BinaryReader(ms);
Format = (FormatChunk)GetChunk(reader);
WaveData = (DataChunk)GetChunk(reader);
}
}
}
<file_sep>using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace ErnstTech.SynthesizerControls
{
/// <summary>
/// Summary description for Track.
/// </summary>
[Designer(typeof(Track.TrackDesigner))]
public class Track : System.Windows.Forms.UserControl
{
public class TrackDesigner : ControlDesigner
{
}
private int _BeatCount = 16;
private System.Windows.Forms.Panel panel1;
private ErnstTech.SynthesizerControls.BeatLoop beatLoop;
public int BeatCount
{
get{ return this._BeatCount; }
set
{
if ( value < 1 )
throw new ArgumentOutOfRangeException( "value", value, "BeatCount must be a positive integer." );
if ( this._BeatCount != value )
{
this._BeatCount = value;
this.OnBeatCountChanged( EventArgs.Empty );
}
}
}
#region BeatCountChanged Event
private static readonly object BeatCountChangedEvent = new object();
public event EventHandler BeatCountChanged
{
add{ this.Events.AddHandler( BeatCountChangedEvent, value ); }
remove{ this.Events.RemoveHandler( BeatCountChangedEvent, value ); }
}
protected virtual void OnBeatCountChanged( EventArgs arguments )
{
EventHandler handler = this.Events[BeatCountChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
private System.Windows.Forms.Label lblName;
private System.Windows.Forms.LinkLabel lblEdit;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Track()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
this.BeatCountChanged += new EventHandler(Track_BeatCountChanged);
this.TextChanged += new EventHandler(Track_TextChanged);
this.Text = "Track";
this.OnBeatCountChanged( EventArgs.Empty );
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lblName = new System.Windows.Forms.Label();
this.lblEdit = new System.Windows.Forms.LinkLabel();
this.beatLoop = new ErnstTech.SynthesizerControls.BeatLoop();
this.panel1 = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// lblName
//
this.lblName.Location = new System.Drawing.Point(0, 0);
this.lblName.Name = "lblName";
this.lblName.Size = new System.Drawing.Size(100, 16);
this.lblName.TabIndex = 0;
this.lblName.Text = "label1";
//
// lblEdit
//
this.lblEdit.Location = new System.Drawing.Point(96, 0);
this.lblEdit.Name = "lblEdit";
this.lblEdit.Size = new System.Drawing.Size(40, 16);
this.lblEdit.TabIndex = 1;
this.lblEdit.TabStop = true;
this.lblEdit.Text = "Edit...";
this.lblEdit.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lblEdit_LinkClicked);
//
// beatLoop
//
this.beatLoop.BackColor = System.Drawing.Color.Black;
this.beatLoop.BeatCount = 16;
this.beatLoop.BeatSpacing = 0;
this.beatLoop.BorderColor = System.Drawing.Color.Black;
this.beatLoop.BorderWidth = 1;
this.beatLoop.HalfColor = System.Drawing.Color.Cornsilk;
this.beatLoop.Location = new System.Drawing.Point(0, 16);
this.beatLoop.Name = "beatLoop";
this.beatLoop.OffColor = System.Drawing.Color.Bisque;
this.beatLoop.OnColor = System.Drawing.Color.Green;
this.beatLoop.Size = new System.Drawing.Size(177, 12);
this.beatLoop.TabIndex = 2;
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.Location = new System.Drawing.Point(0, 32);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(176, 112);
this.panel1.TabIndex = 3;
//
// Track
//
this.Controls.Add(this.panel1);
this.Controls.Add(this.beatLoop);
this.Controls.Add(this.lblEdit);
this.Controls.Add(this.lblName);
this.Name = "Track";
this.Size = new System.Drawing.Size(176, 144);
this.ResumeLayout(false);
}
#endregion
private void lblEdit_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
// TODO: Show waveform edit
}
private void Track_BeatCountChanged(object sender, EventArgs e)
{
BeatState[] states = this.beatLoop.GetLoopState();
BeatState[] newstates = new BeatState[ this.BeatCount ];
if ( states.Length <= newstates.Length )
{
Array.Copy( states, 0, newstates, 0, states.Length );
for( int i = states.Length; i < newstates.Length; ++i )
newstates[i] = BeatState.Off;
}
else
{
Array.Copy( states, 0, newstates, 0, newstates.Length );
}
this.beatLoop.BeatCount = this.BeatCount;
this.beatLoop.SetLoopState( newstates );
this.SetupSliders();
}
private void SetupSliders()
{
foreach( Control control in this.panel1.Controls )
{
control.Dispose();
}
this.panel1.Controls.Clear();
int count = this.BeatCount;
int width = this.Width % count - 1;
const int offset = 1;
for( int i = 0; i < count; ++i )
{
ThinSlider slider = new ThinSlider();
slider.Width = width;
slider.Top = this.beatLoop.Bottom + offset;
slider.Height = 100;
slider.Left = ( width + offset ) * i + offset;
this.panel1.Controls.Add( slider );
}
}
void Track_TextChanged(object sender, EventArgs e)
{
this.lblName.Text = this.Text;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ErnstTech.SoundCore;
namespace Synthesizer.Controls
{
/// <summary>
/// Interaction logic for DrumControl.xaml
/// </summary>
public partial class DrumControl : UserControl
{
public static readonly DependencyProperty SampleRateProperty = DependencyProperty.Register("SampleRate", typeof(int), typeof(DrumControl), new PropertyMetadata(48_000));
public static readonly RoutedUICommand ShowCommand = new RoutedUICommand("Show Waveform", "Show", typeof(DrumControl));
public static readonly RoutedUICommand PlayCommand = new RoutedUICommand("Play Waveform", "Show", typeof(DrumControl));
public int SampleRate
{
get { return (int)GetValue(SampleRateProperty); }
set { SetValue(SampleRateProperty, value); }
}
public Views.DrumView View
{
get { return this.DataContext as Views.DrumView; }
set { this.DataContext = value; }
}
public DrumControl()
{
InitializeComponent();
this.CommandBindings.Add(new CommandBinding(
ShowCommand,
(o, e) => { }
));
this.CommandBindings.Add(new CommandBinding(
PlayCommand,
(o, e) => { new System.Media.SoundPlayer(WaveWriter.Write(SampleRate, (int)(SampleRate * View.EffectTime), View.Adapt())).Play(); }
));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore
{
public class Mixer
{
public IEnumerable<double> Mix(IList<IEnumerable<double>> sources, IList<double>? levels = null)
{
if (levels == null)
levels = Enumerable.Range(0, sources.Count).Select(_ => 1.0).ToArray();
if (sources.Count <= 0)
throw new ArgumentException("There must be at least one source.", nameof(sources));
if (levels.Count != sources.Count)
throw new ArgumentException("The number of levels must match the number of sources.", nameof(levels));
var enumerators = sources.Select(s => s.GetEnumerator()).ToArray<IEnumerator<double>?>();
while (true)
{
ulong flags = 0;
double sum = 0.0;
for (int i = 0; i < enumerators.Length; ++i)
{
bool flag = enumerators[i]?.MoveNext() ?? false;
if (flag)
flags |= 1ul << i;
else
enumerators[i] = null;
sum += levels[i] * enumerators[i]?.Current ?? 0.0;
}
yield return sum;
if (flags != 0)
yield break;
}
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Adapted from Microsoft's MMReg.h in the Platform SDK
///
/// TODO: Verify the values. This is > 10 years old...
/// </summary>
public enum FormatTag : short
{
WAVE_FORMAT_UNKNOWN = 0x0000, /* Microsoft Corporation */
WAVE_FORMAT_PCM = 0x0001,
WAVE_FORMAT_ADPCM = 0x0002, /* Microsoft Corporation */
WAVE_FORMAT_IEEE_FLOAT = 0x0003, /* Microsoft Corporation */
WAVE_FORMAT_VSELP = 0x0004, /* Compaq Computer Corp. */
WAVE_FORMAT_IBM_CVSD = 0x0005, /* IBM Corporation */
WAVE_FORMAT_ALAW = 0x0006, /* Microsoft Corporation */
WAVE_FORMAT_MULAW = 0x0007, /* Microsoft Corporation */
WAVE_FORMAT_DTS = 0x0008, /* Microsoft Corporation */
WAVE_FORMAT_DRM = 0x0009, /* Microsoft Corporation */
WAVE_FORMAT_OKI_ADPCM = 0x0010, /* OKI */
WAVE_FORMAT_DVI_ADPCM = 0x0011, /* Intel Corporation */
WAVE_FORMAT_IMA_ADPCM = 0x0011, /* Intel Corporation */
WAVE_FORMAT_MEDIASPACE_ADPCM = 0x0012, /* Videologic */
WAVE_FORMAT_SIERRA_ADPCM = 0x0013, /* Sierra Semiconductor Corp */
WAVE_FORMAT_G723_ADPCM = 0x0014, /* Antex Electronics Corporation */
WAVE_FORMAT_DIGISTD = 0x0015, /* DSP Solutions, Inc. */
WAVE_FORMAT_DIGIFIX = 0x0016, /* DSP Solutions, Inc. */
WAVE_FORMAT_DIALOGIC_OKI_ADPCM = 0x0017, /* Dialogic Corporation */
WAVE_FORMAT_MEDIAVISION_ADPCM = 0x0018, /* Media Vision, Inc. */
WAVE_FORMAT_CU_CODEC = 0x0019, /* Hewlett-Packard Company */
WAVE_FORMAT_YAMAHA_ADPCM = 0x0020, /* Yamaha Corporation of America */
WAVE_FORMAT_SONARC = 0x0021, /* Speech Compression */
WAVE_FORMAT_DSPGROUP_TRUESPEECH = 0x0022, /* DSP Group, Inc */
WAVE_FORMAT_ECHOSC1 = 0x0023, /* Echo Speech Corporation */
WAVE_FORMAT_AUDIOFILE_AF36 = 0x0024, /* Virtual Music, Inc. */
WAVE_FORMAT_APTX = 0x0025, /* Audio Processing Technology */
WAVE_FORMAT_AUDIOFILE_AF10 = 0x0026, /* Virtual Music, Inc. */
WAVE_FORMAT_PROSODY_1612 = 0x0027, /* Aculab plc */
WAVE_FORMAT_LRC = 0x0028, /* Merging Technologies S.A. */
WAVE_FORMAT_DOLBY_AC2 = 0x0030, /* Dolby Laboratories */
WAVE_FORMAT_GSM610 = 0x0031, /* Microsoft Corporation */
WAVE_FORMAT_MSNAUDIO = 0x0032, /* Microsoft Corporation */
WAVE_FORMAT_ANTEX_ADPCME = 0x0033, /* Antex Electronics Corporation */
WAVE_FORMAT_CONTROL_RES_VQLPC = 0x0034, /* Control Resources Limited */
WAVE_FORMAT_DIGIREAL = 0x0035, /* DSP Solutions, Inc. */
WAVE_FORMAT_DIGIADPCM = 0x0036, /* DSP Solutions, Inc. */
WAVE_FORMAT_CONTROL_RES_CR10 = 0x0037, /* Control Resources Limited */
WAVE_FORMAT_NMS_VBXADPCM = 0x0038, /* Natural MicroSystems */
WAVE_FORMAT_CS_IMAADPCM = 0x0039, /* Crystal Semiconductor IMA ADPCM */
WAVE_FORMAT_ECHOSC3 = 0x003A, /* Echo Speech Corporation */
WAVE_FORMAT_ROCKWELL_ADPCM = 0x003B, /* Rockwell International */
WAVE_FORMAT_ROCKWELL_DIGITALK = 0x003C, /* Rockwell International */
WAVE_FORMAT_XEBEC = 0x003D, /* Xebec Multimedia Solutions Limited */
WAVE_FORMAT_G721_ADPCM = 0x0040, /* Antex Electronics Corporation */
WAVE_FORMAT_G728_CELP = 0x0041, /* Antex Electronics Corporation */
WAVE_FORMAT_MSG723 = 0x0042, /* Microsoft Corporation */
WAVE_FORMAT_MPEG = 0x0050, /* Microsoft Corporation */
WAVE_FORMAT_RT24 = 0x0052, /* InSoft, Inc. */
WAVE_FORMAT_PAC = 0x0053, /* InSoft, Inc. */
WAVE_FORMAT_MPEGLAYER3 = 0x0055, /* ISO/MPEG Layer3 Format Tag */
WAVE_FORMAT_LUCENT_G723 = 0x0059, /* Lucent Technologies */
WAVE_FORMAT_CIRRUS = 0x0060, /* Cirrus Logic */
WAVE_FORMAT_ESPCM = 0x0061, /* ESS Technology */
WAVE_FORMAT_VOXWARE = 0x0062, /* Voxware Inc */
WAVE_FORMAT_CANOPUS_ATRAC = 0x0063, /* Canopus, co., Ltd. */
WAVE_FORMAT_G726_ADPCM = 0x0064, /* APICOM */
WAVE_FORMAT_G722_ADPCM = 0x0065, /* APICOM */
WAVE_FORMAT_DSAT_DISPLAY = 0x0067, /* Microsoft Corporation */
WAVE_FORMAT_VOXWARE_BYTE_ALIGNED = 0x0069, /* Voxware Inc */
WAVE_FORMAT_VOXWARE_AC8 = 0x0070, /* Voxware Inc */
WAVE_FORMAT_VOXWARE_AC10 = 0x0071, /* Voxware Inc */
WAVE_FORMAT_VOXWARE_AC16 = 0x0072, /* Voxware Inc */
WAVE_FORMAT_VOXWARE_AC20 = 0x0073, /* Voxware Inc */
WAVE_FORMAT_VOXWARE_RT24 = 0x0074, /* Voxware Inc */
WAVE_FORMAT_VOXWARE_RT29 = 0x0075, /* Voxware Inc */
WAVE_FORMAT_VOXWARE_RT29HW = 0x0076, /* Voxware Inc */
WAVE_FORMAT_VOXWARE_VR12 = 0x0077, /* Voxware Inc */
WAVE_FORMAT_VOXWARE_VR18 = 0x0078, /* Voxware Inc */
WAVE_FORMAT_VOXWARE_TQ40 = 0x0079, /* Voxware Inc */
WAVE_FORMAT_SOFTSOUND = 0x0080, /* Softsound, Ltd. */
WAVE_FORMAT_VOXWARE_TQ60 = 0x0081, /* Voxware Inc */
WAVE_FORMAT_MSRT24 = 0x0082, /* Microsoft Corporation */
WAVE_FORMAT_G729A = 0x0083, /* AT&T Labs, Inc. */
WAVE_FORMAT_MVI_MVI2 = 0x0084, /* Motion Pixels */
WAVE_FORMAT_DF_G726 = 0x0085, /* DataFusion Systems (Pty) (Ltd) */
WAVE_FORMAT_DF_GSM610 = 0x0086, /* DataFusion Systems (Pty) (Ltd) */
WAVE_FORMAT_ISIAUDIO = 0x0088, /* Iterated Systems, Inc. */
WAVE_FORMAT_ONLIVE = 0x0089, /* OnLive! Technologies, Inc. */
WAVE_FORMAT_SBC24 = 0x0091, /* Siemens Business Communications Sys */
WAVE_FORMAT_DOLBY_AC3_SPDIF = 0x0092, /* Sonic Foundry */
WAVE_FORMAT_MEDIASONIC_G723 = 0x0093, /* MediaSonic */
WAVE_FORMAT_PROSODY_8KBPS = 0x0094, /* Aculab plc */
WAVE_FORMAT_ZYXEL_ADPCM = 0x0097, /* ZyXEL Communications, Inc. */
WAVE_FORMAT_PHILIPS_LPCBB = 0x0098, /* Philips Speech Processing */
WAVE_FORMAT_PACKED = 0x0099, /* Studer Professional Audio AG */
WAVE_FORMAT_MALDEN_PHONYTALK = 0x00A0, /* Malden Electronics Ltd. */
WAVE_FORMAT_RHETOREX_ADPCM = 0x0100, /* Rhetorex Inc. */
WAVE_FORMAT_IRAT = 0x0101, /* BeCubed Software Inc. */
WAVE_FORMAT_VIVO_G723 = 0x0111, /* Vivo Software */
WAVE_FORMAT_VIVO_SIREN = 0x0112, /* Vivo Software */
WAVE_FORMAT_DIGITAL_G723 = 0x0123, /* Digital Equipment Corporation */
WAVE_FORMAT_SANYO_LD_ADPCM = 0x0125, /* Sanyo Electric Co., Ltd. */
WAVE_FORMAT_SIPROLAB_ACEPLNET = 0x0130, /* Sipro Lab Telecom Inc. */
WAVE_FORMAT_SIPROLAB_ACELP4800 = 0x0131, /* Sipro Lab Telecom Inc. */
WAVE_FORMAT_SIPROLAB_ACELP8V3 = 0x0132, /* Sipro Lab Telecom Inc. */
WAVE_FORMAT_SIPROLAB_G729 = 0x0133, /* Sipro Lab Telecom Inc. */
WAVE_FORMAT_SIPROLAB_G729A = 0x0134, /* Sipro Lab Telecom Inc. */
WAVE_FORMAT_SIPROLAB_KELVIN = 0x0135, /* Sipro Lab Telecom Inc. */
WAVE_FORMAT_G726ADPCM = 0x0140, /* Dictaphone Corporation */
WAVE_FORMAT_QUALCOMM_PUREVOICE = 0x0150, /* Qualcomm, Inc. */
WAVE_FORMAT_QUALCOMM_HALFRATE = 0x0151, /* Qualcomm, Inc. */
WAVE_FORMAT_TUBGSM = 0x0155, /* Ring Zero Systems, Inc. */
WAVE_FORMAT_MSAUDIO1 = 0x0160, /* Microsoft Corporation */
WAVE_FORMAT_UNISYS_NAP_ADPCM = 0x0170, /* Unisys Corp. */
WAVE_FORMAT_UNISYS_NAP_ULAW = 0x0171, /* Unisys Corp. */
WAVE_FORMAT_UNISYS_NAP_ALAW = 0x0172, /* Unisys Corp. */
WAVE_FORMAT_UNISYS_NAP_16K = 0x0173, /* Unisys Corp. */
WAVE_FORMAT_CREATIVE_ADPCM = 0x0200, /* Creative Labs, Inc */
WAVE_FORMAT_CREATIVE_FASTSPEECH8 = 0x0202, /* Creative Labs, Inc */
WAVE_FORMAT_CREATIVE_FASTSPEECH10 = 0x0203, /* Creative Labs, Inc */
WAVE_FORMAT_UHER_ADPCM = 0x0210, /* UHER informatic GmbH */
WAVE_FORMAT_QUARTERDECK = 0x0220, /* Quarterdeck Corporation */
WAVE_FORMAT_ILINK_VC = 0x0230, /* I-link Worldwide */
WAVE_FORMAT_RAW_SPORT = 0x0240, /* Aureal Semiconductor */
WAVE_FORMAT_ESST_AC3 = 0x0241, /* ESS Technology, Inc. */
WAVE_FORMAT_IPI_HSX = 0x0250, /* Interactive Products, Inc. */
WAVE_FORMAT_IPI_RPELP = 0x0251, /* Interactive Products, Inc. */
WAVE_FORMAT_CS2 = 0x0260, /* Consistent Software */
WAVE_FORMAT_SONY_SCX = 0x0270, /* Sony Corp. */
WAVE_FORMAT_FM_TOWNS_SND = 0x0300, /* Fujitsu Corp. */
WAVE_FORMAT_BTV_DIGITAL = 0x0400, /* Brooktree Corporation */
WAVE_FORMAT_QDESIGN_MUSIC = 0x0450, /* QDesign Corporation */
WAVE_FORMAT_VME_VMPCM = 0x0680, /* AT&T Labs, Inc. */
WAVE_FORMAT_TPC = 0x0681, /* AT&T Labs, Inc. */
WAVE_FORMAT_OLIGSM = 0x1000, /* Ing C. Olivetti & C., S.p.A. */
WAVE_FORMAT_OLIADPCM = 0x1001, /* Ing C. Olivetti & C., S.p.A. */
WAVE_FORMAT_OLICELP = 0x1002, /* Ing C. Olivetti & C., S.p.A. */
WAVE_FORMAT_OLISBC = 0x1003, /* Ing C. Olivetti & C., S.p.A. */
WAVE_FORMAT_OLIOPR = 0x1004, /* Ing C. Olivetti & C., S.p.A. */
WAVE_FORMAT_LH_CODEC = 0x1100, /* Lernout & Hauspie */
WAVE_FORMAT_NORRIS = 0x1400, /* Norris Communications, Inc. */
WAVE_FORMAT_SOUNDSPACE_MUSICOMPRESS = 0x1500, /* AT&T Labs, Inc. */
WAVE_FORMAT_DVM = 0x2000 /* FAST Multimedia AG */
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
public enum AudioBits : short
{
Bits8 = 8,
Bits16 = 16,
Bits32 = 32,
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis.Expressions.AST
{
public class TimeVariableNode : ExpressionNode
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis
{
public class Smoother
{
double[] _Samples;
int _Index = 0;
public Smoother(int sampleCount)
{
if (sampleCount <= 0)
throw new ArgumentException("SampleCount must be positive.", nameof(sampleCount));
_Samples = new double[sampleCount];
Array.Fill(_Samples, 0.0);
}
public double Sample(double value)
{
_Samples[_Index] = value;
_Index = (_Index + 1) % _Samples.Length;
return _Samples.Average();
}
public IEnumerable<double> Wrap(IEnumerable<double> source)
{
var e = source.GetEnumerator();
while (e.MoveNext())
yield return Sample(e.Current);
}
public Func<double, double> Wrap(Func<double, double> source) => (double t) => Sample(source(t));
public static Func<double, double> Wrap(int sampleCount, Func<double, double> source) => new Smoother(sampleCount).Wrap(source);
}
}
<file_sep>using System;
using System.Runtime.InteropServices;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveHeader.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct WaveHeader
{
public IntPtr Data; // WaveForm buffer
public int BufferLength; // Length, in bytes, of the buffer
public int BytesRecorded; // When header is used as input, specifies how much data is in the buffer
public IntPtr UserData; // User data
public WaveHeaderFlags Flags; // Flags supplying info about the buffer
public int Loops; // Number of times to play loop
public IntPtr Next; // Reserved
public int Reserved; // Reserved
}
}
<file_sep>using System;
using System.Threading;
using System.Runtime.InteropServices;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveOutBuffer.
/// </summary>
public class WaveOutBuffer : IDisposable
{
private AutoResetEvent _HasData = new AutoResetEvent( false );
private GCHandle _DataHandle;
private GCHandle _HeaderHandle;
private WaveHeader _Header;
public IntPtr Data
{
get{ return _DataHandle.AddrOfPinnedObject(); }
}
private int _Length;
public int Length
{
get{ return _Length; }
}
private bool _IsEmpty = true;
public bool IsEmpty
{
get{ return _IsEmpty; }
}
private IntPtr _DeviceHandle;
private WavePlayer _Player;
private WaveOutBuffer _NextBuffer = null;
public WaveOutBuffer NextBuffer
{
get{ return _NextBuffer; }
set{ _NextBuffer = value; }
}
/// <summary>
/// Creates and prepares a WaveOutBuffer.
/// </summary>
/// <param name="device">Handle to WaveOut device to prepare the buffer for</param>
/// <param name="size">Size of the buffer, in bytes</param>
public WaveOutBuffer( WavePlayer player, IntPtr device, int size )
{
if ( player == null )
throw new ArgumentNullException( "player" );
_Player = player;
if ( device == IntPtr.Zero )
throw new ArgumentException( "Device must be a a valid pointer to a wave out device.", "device" );
if ( size < 1 )
throw new ArgumentOutOfRangeException( "size", size, "Size must be greater than zero." );
_Length = size;
_DeviceHandle = device;
// Allocate memory for the buffer, and set up a GCHandle pointed to it.
byte[] buffer = new byte[Length];
_DataHandle = GCHandle.Alloc( buffer, GCHandleType.Pinned );
// Create the header and a GC handle pointed to it.
_Header = new WaveHeader();
_HeaderHandle = GCHandle.Alloc( _Header, GCHandleType.Pinned );
_Header.Data = this.Data;
_Header.BufferLength = Length;
_Header.UserData = (IntPtr)GCHandle.Alloc( this );
_Header.Loops = 0;
_Header.Flags = 0;
int result = WaveFormNative.waveOutPrepareHeader( _DeviceHandle,
ref _Header, Marshal.SizeOf( _Header ) );
if ( result != WaveError.MMSYSERR_NOERROR )
throw new SoundCoreException( WaveError.GetMessage( result ), result );
}
public void Play()
{
// Make sure we have data
this.WaitForBufferFull();
WaveFormNative.waveOutWrite( _DeviceHandle, ref _Header, Marshal.SizeOf( _Header ) );
_IsEmpty = true;
}
public static void WaveOutCallback(IntPtr hdrvr, int uMsg, int dwUser, ref WaveHeader wavhdr, int dwParam2)
{
if ( uMsg == (int)WaveFormOutputMessage.Done )
{
GCHandle handle = (GCHandle)wavhdr.UserData;
WaveOutBuffer buffer = (WaveOutBuffer)handle.Target;
if ( buffer._Player.IsPlaying )
{
buffer.NextBuffer.Play();
#if DEBUG
System.Diagnostics.Debug.WriteLine( string.Format( "FillBuffer start at {0} ticks.", DateTime.Now.Ticks ) );
#endif
buffer._Player.FillBuffer( buffer );
#if DEBUG
System.Diagnostics.Debug.WriteLine( string.Format( "FillBuffer end at {0} ticks.", DateTime.Now.Ticks ) );
#endif
buffer._IsEmpty = false;
buffer._HasData.Set();
}
else
{
buffer._Player.SignalDone();
}
}
}
public void WaitForBufferFull()
{
if ( IsEmpty )
_HasData.WaitOne();
else
Thread.Sleep(0);
}
/// <summary>
/// Allows an external object to signal that it has filled the buffer.
/// </summary>
public void BufferFilled()
{
this._IsEmpty = false;
this._HasData.Set();
}
#region IDisposable Members
public void Dispose()
{
this.NextBuffer?.Dispose();
WaveFormNative.waveOutUnprepareHeader( _DeviceHandle, ref _Header, Marshal.SizeOf( _Header ) );
_DataHandle.Free();
_HeaderHandle.Free();
}
#endregion
}
}
<file_sep>using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using ErnstTech.SoundCore.Sampler;
using Synthesizer.Views;
namespace Synthesizer.Controls
{
/// <summary>
/// Interaction logic for BeatControl.xaml
/// </summary>
public partial class BeatControl : UserControl
{
public static readonly RoutedUICommand ToggleStateCommand = new RoutedUICommand("Toggle State", "ToggleState", typeof(BeatControl));
public BeatView View
{
get { return ((BeatView)DataContext); }
}
public Views.BeatState State
{
get { return View?.State ?? BeatState.Off; }
set { View.State = value; }
}
#region FullColor Property
public static readonly DependencyProperty FullColorProperty = DependencyProperty.Register(
"FullColor",
typeof(Color),
typeof(BeatControl),
new PropertyMetadata(Colors.Red)
);
public Color FullColor
{
get { return (Color)GetValue(FullColorProperty); }
set { SetValue(FullColorProperty, value); }
}
#endregion
#region HalfColor Property
public static readonly DependencyProperty HalfColorProperty = DependencyProperty.Register(
"HalfColor",
typeof(Color),
typeof(BeatControl),
new PropertyMetadata(Colors.Orange)
);
public Color HalfColor
{
get { return (Color)GetValue(HalfColorProperty); }
set { SetValue(HalfColorProperty, value); }
}
#endregion
#region OffColor Property
public static readonly DependencyProperty OffColorProperty = DependencyProperty.Register(
"OffColor",
typeof(Color),
typeof(BeatControl),
new PropertyMetadata(Colors.Gray)
);
public Color OffColor
{
get { return (Color)GetValue(OffColorProperty); }
set { SetValue(OffColorProperty, value); }
}
#endregion
#region BeatBrush Property
public static readonly DependencyProperty BeatBrushProperty = DependencyProperty.Register(
"BeatBrush",
typeof(Brush),
typeof(BeatControl)
);
public Brush BeatBrush
{
get { return (Brush)GetValue(BeatBrushProperty); }
set { SetValue(BeatBrushProperty, value); }
}
#endregion
#region CustomColor Property
public static readonly DependencyProperty CustomColorProperty = DependencyProperty.Register(
"CustomColor",
typeof(Color),
typeof(BeatControl),
new PropertyMetadata(Colors.Yellow));
public Color CustomColor
{
get { return (Color)GetValue(CustomColorProperty); }
set { SetValue(CustomColorProperty, value); }
}
#endregion
public BeatControl()
{
InitializeComponent();
this.CommandBindings.Add(new CommandBinding(
ToggleStateCommand,
(o, e) => {
this.State = this.State switch
{
BeatState.Off => BeatState.Full,
BeatState.Full => BeatState.Half,
BeatState.Half => BeatState.Off,
_ => throw new InvalidOperationException("Unknown Beat value.")
};
e.Handled = true;
},
(o, e) => e.CanExecute = true
));
DataContextChanged += (o, e) =>
{
View.PropertyChanged += (o, e) => { if (e.PropertyName?.Equals("State") ?? true) SetBeatBrushState(); };
this.SetBeatBrushState();
};
}
void SetBeatBrushState()
{
this.BeatBrush = new SolidColorBrush(this.State switch
{
BeatState.Off => this.OffColor,
BeatState.Half => this.HalfColor,
BeatState.Full => this.FullColor,
BeatState.Custom => this.CustomColor,
_ => throw new InvalidOperationException("Unknown Beat value.")
});
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ErnstTech.SoundCore.Sampler
{
public class WAVSampler : ISampler
{
WaveReader _waveReader;
short _channel = 0;
double[] _data;
public WAVSampler(Stream stream, short channel = 0)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
_waveReader = new WaveReader(stream);
if (channel >= _waveReader.Format.Channels)
throw new ArgumentOutOfRangeException(nameof(channel), channel, $"Channel must be in range [0, {_waveReader.Format.Channels}).");
_channel = channel;
_data = _waveReader.GetChannelFloat(channel).Select(f => (double)f).ToArray();
this.Length = _data.LongLength;
}
public int SampleRate => _waveReader.Format.SamplesPerSecond;
public int BitsPerSample => _waveReader.Format.BitsPerSample;
public long Length { get; set; }
public long GetSamples(double[] destination, long destOffset, long sampleStartOffset, long numSamples)
{
var length = Math.Min(Math.Min(destination.LongLength - destOffset, numSamples), _data.LongLength - sampleStartOffset);
Array.Copy(_data, sampleStartOffset, destination, destOffset, length);
return length;
}
public double Sample(long sampleOffset)
{
try
{
return _data[sampleOffset];
}
catch (IndexOutOfRangeException)
{
throw new ArgumentOutOfRangeException(nameof(sampleOffset), sampleOffset, $"sampleOffset must be in range [0, {_data.LongLength}).");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Antlr4.Runtime.Misc;
using ErnstTech.SoundCore.Synthesis.Expressions.AST;
namespace ErnstTech.SoundCore.Synthesis.Expressions.Antlr
{
public class AudioSynthesisVisitor : AudioSynthesisGrammarBaseVisitor<ExpressionNode>
{
public override ExpressionNode VisitTimeVarExpr([NotNull] AudioSynthesisGrammarParser.TimeVarExprContext context)
{
return new TimeVariableNode();
}
public override ExpressionNode VisitSubExpr([NotNull] AudioSynthesisGrammarParser.SubExprContext context)
{
return Visit(context.inner);
}
public override ExpressionNode VisitUnaryExpr([NotNull] AudioSynthesisGrammarParser.UnaryExprContext context)
{
var child = Visit(context.child);
switch(context.op.Type)
{
case AudioSynthesisGrammarLexer.OP_ADD:
return new AbsoluteValueNode(child);
case AudioSynthesisGrammarLexer.OP_SUB:
return new NegateNode(child);
default:
throw new ArgumentException($"Unexpected 'op' type: {context.op.Type}", nameof(context));
}
}
public override ExpressionNode VisitBinaryExpr([NotNull] AudioSynthesisGrammarParser.BinaryExprContext context)
{
var left = Visit(context.leftChild);
var right = Visit(context.rightChild);
switch(context.op.Type)
{
case AudioSynthesisGrammarLexer.OP_ADD:
return new AddNode(left, right);
case AudioSynthesisGrammarLexer.OP_SUB:
return new SubtractNode(left, right);
case AudioSynthesisGrammarLexer.OP_MUL:
return new MultiplyNode(left, right);
case AudioSynthesisGrammarLexer.OP_DIV:
return new DivideNode(left, right);
case AudioSynthesisGrammarLexer.OP_EXP:
return new ExponentiationNode(left, right);
default:
throw new ArgumentException($"Unexpected 'op': {context.op.Type}", nameof(context));
}
}
public override ExpressionNode VisitValueExpr([NotNull] AudioSynthesisGrammarParser.ValueExprContext context)
{
var value = double.Parse(context.value.Text);
return new NumberNode(value);
}
public override ExpressionNode VisitEulerExpr([NotNull] AudioSynthesisGrammarParser.EulerExprContext context) => new EulerNode();
public override ExpressionNode VisitPiExpr([NotNull] AudioSynthesisGrammarParser.PiExprContext context) => new PiNode();
public override ExpressionNode VisitExprList([NotNull] AudioSynthesisGrammarParser.ExprListContext context)
{
var children = context.expr().Select(x => Visit(x)).ToList();
return new ExpressionListNode(children);
}
public override ExpressionNode VisitFunctionExpr([NotNull] AudioSynthesisGrammarParser.FunctionExprContext context)
{
var name = context.funcName.Text;
var children = context.arguments is null
? new List<ExpressionNode>()
: ((ExpressionListNode)Visit(context.arguments)).Children;
return new FunctionNode(name, children);
}
public override ExpressionNode VisitCompileUnit([NotNull] AudioSynthesisGrammarParser.CompileUnitContext context)
{
return Visit(context.finalUnit);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace ErnstTech.SoundCore.Sampler
{
public class BeatLoop
{
readonly object _SyncRoot = new object();
const int _DefaultBeats = 16;
public ISampler? Sampler { get; set; }
public double BeatsPerMinute { get; set; } = 165.0;
public double BeatDuration => 1.0 / (4 * BeatsPerMinute / 60); //BeatsPerMinute / 60 / 4;
public double FullHeight { get; set; } = 1.0;
public double HalfHeight { get; set; } = 0.5;
static double[] DefaultLevels = new[] { Beat.Full, Beat.Off, Beat.Half, Beat.Off, Beat.Full, Beat.Off, Beat.Off, Beat.Off, Beat.Full, Beat.Off, Beat.Half, Beat.Off, Beat.Full, Beat.Off, Beat.Off, Beat.Off };
public IList<Beat> Beats { get; init; } = DefaultLevels.Select(l => new Beat { Level = l }).ToList();
public int BeatCount => Beats.Count;
Stream? _WAVStream;
public Stream WAVStream
{
get
{
if (_WAVStream == null)
_WAVStream = GenerateStream();
return _WAVStream;
}
private set { _WAVStream = null; }
}
public BeatLoop(ISampler? sampler = null)
{
this.Sampler = sampler;
}
public void InvalidateWAVStream() => _WAVStream = null;
Stream GenerateStream()
{
if (Sampler == null)
throw new InvalidOperationException("Sampler has not been specified.");
if (BeatsPerMinute <= 0)
throw new InvalidOperationException("BeatsPerMinute must be positive.");
var samplesPerBeat = BeatDuration * Sampler.SampleRate;
long bufferSize = 0;
// Fixup all of the beats
for (int i = 0; i < Beats.Count; ++i)
{
var beat = Beats[i];
beat.Sampler ??= Sampler;
beat.QueuePoint ??= (long)(i * BeatDuration * Sampler.SampleRate);
if (beat.Sampler.SampleRate != Sampler.SampleRate)
throw new InvalidOperationException($"All samplers must have the sample sample rate. Sampler for beat {i} has value {beat.Sampler.SampleRate}. Base sampler has {Sampler.SampleRate}");
bufferSize = Math.Max(bufferSize, beat.QueuePoint.Value + beat.Sampler.Length);
}
var buffer = new double[bufferSize];
foreach (var beat in Beats)
{
for (long i = beat.QueuePoint ?? 0, len = i + beat.Sampler!.Length; i < len; ++i)
buffer[i] += beat.Sample(i);
}
var ms = new MemoryStream();
var writer = new WaveWriter(ms, Sampler.SampleRate);
writer.Write(buffer.Length, buffer.Select(s => (float)s));
ms.Position = 0;
return ms;
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
[Flags]
public enum DeviceOpenFlags : int
{
CallbackEvent = 0x00050000,
CallbackFunction = 0x00030000,
CallbackNull = 0x00000000,
CallbackThread = 0x00020000,
CallbackWindow = 0x00010000,
WaveAllowSync = 0x00000002,
WaveFormatDirect = 0x00000008,
WaveFormatQuery = 0x00000001,
WaveMapped = 0x00000004,
WaveFormatDirectQuery = WaveFormatQuery | WaveFormatDirect
}
}<file_sep>using System;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveOutProcDelegate.
/// </summary>
public delegate void WaveOutProcDelegate(IntPtr hdrvr, int uMsg, int dwUser, ref WaveHeader wavhdr, int dwParam2);
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveDeviceVersion.
/// </summary>
public struct WaveDeviceDriverVersion
{
public short Version;
public byte Major
{
get{ return (byte)(Version >> 8); }
}
public byte Minor
{
get{ return (byte)Version; }
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis
{
public class NoiseGenerator : IWaveFormGenerator
{
Random _Random;
public NoiseGenerator() : this((int)(DateTime.Now.Ticks / (double)int.MaxValue))
{ }
public NoiseGenerator(int seed) : this(new Random(seed)) { }
public NoiseGenerator(Random random)
{
this._Random = random;
}
/// <summary>
/// Generate a random sample in the range [-1.0, 1.0].
/// </summary>
/// <returns></returns>
public double Sample()
{
return 2.0 * (this._Random.NextDouble() - 0.5);
}
public Func<double, double> Adapt() => (double _) => Sample();
public double[] Generate(long nSamples)
{
return this.Take((int)nSamples).ToArray();
}
public IEnumerator<double> GetEnumerator()
{
while (true)
yield return Sample();
}
IEnumerator IEnumerable.GetEnumerator()
{
while (true)
yield return Sample();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using ErnstTech.SoundCore;
using ErnstTech.SoundCore.Synthesis;
namespace Synthesizer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static readonly RoutedCommand TestSynthCommand = new RoutedCommand("TestSynth", typeof(MainWindow));
public static readonly RoutedCommand ShowSynthCommand = new RoutedCommand("ShowSynth", typeof(MainWindow));
public static readonly RoutedCommand TestLoopCommand = new RoutedCommand("TestLoop", typeof(MainWindow));
public static readonly DependencyProperty ExpressionTextProperty = DependencyProperty.Register(
"ExpressionText",
typeof(string),
typeof(MainWindow),
new PropertyMetadata("cos(2 * PI * (220 + 4 * cos(2 * PI * 10 * t)) * t) * 0.5")
);
public string ExpressionText
{
get { return (string)GetValue(ExpressionTextProperty); }
set { SetValue(ExpressionTextProperty, value); }
}
static readonly ExpressionBuilder _Parser = new ExpressionBuilder(new ErnstTech.SoundCore.Synthesis.Expressions.Antlr.ExpressionParser());
Views.DrumView drumView = new Views.DrumView();
Views.BeatLoopView beatLoopView = new Views.BeatLoopView();
// readonly MediaPlayer _Player = new MediaPlayer();
public MainWindow()
{
InitializeComponent();
this.CommandBindings.Add(new CommandBinding(TestSynthCommand,
new ExecutedRoutedEventHandler(TestSynthCommandExecuted),
new CanExecuteRoutedEventHandler(TestSynthCommandCanExecute)));
this.CommandBindings.Add(new CommandBinding(ShowSynthCommand,
new ExecutedRoutedEventHandler(ShowSynthCommandExecuted),
new CanExecuteRoutedEventHandler(ShowSynthCommandCanExecute)));
this.CommandBindings.Add(new CommandBinding(TestLoopCommand,
(o, e) => TestLoopCommandExecute(o, e),
(o, e) => TestSynthCommandCanExecute(o, e)
));
drumControl.DataContext = drumView;
beatLoopControl.DataContext = beatLoopView;
}
static IEnumerable<float> ToEnumerable(int sampleRate, Func<double, double> func)
{
var count = 0;
var delta = 1.0 / sampleRate;
while (true)
yield return (float)func(count++ * delta);
}
Stream Generate(int sampleRate, double duration, Func<double, double> func)
{
int nSamples = (int)(sampleRate * duration);
var dataSize = nSamples * sizeof(float);
var format = new WaveFormat(1, sampleRate, 32);
var ms = new MemoryStream(dataSize + WaveFormat.HeaderSize);
new WaveWriter(ms, sampleRate).Write(nSamples, ToEnumerable(sampleRate, func));
ms.Position = 0;
return ms;
}
void TestSynthCommandExecuted(object sender, ExecutedRoutedEventArgs args)
{
const int sampleRate = 44100;
var func = _Parser.Compile(this.ExpressionText);
var sample = Generate(sampleRate, 1.0, func);
new System.Media.SoundPlayer(sample).Play();
}
void TestSynthCommandCanExecute(object sender, CanExecuteRoutedEventArgs args)
{
try
{
var expr = this.ExpressionText;
if (string.IsNullOrWhiteSpace(expr))
{
args.CanExecute = false;
return;
}
var func = _Parser.Compile(expr);
args.CanExecute = func != null;
}
catch
{
args.CanExecute = false;
}
}
void ShowSynthCommandExecuted(object sender, ExecutedRoutedEventArgs args)
{
const int sampleRate = 44100;
var func = _Parser.Compile(this.ExpressionText);
var sample = Generate(sampleRate, 1.0, func);
var delta = 1.0 / sampleRate;
var reader = new WaveReader(sample);
var fmt = reader.Format;
var xSeries = Enumerable.Range(0, (int)reader.NumberOfSamples).Select(i => i * delta);
var ySeries = reader.GetChannelFloat(0).Select(x => (double)x);
channel1.Plot(xSeries, ySeries);
}
void ShowSynthCommandCanExecute(object sender, CanExecuteRoutedEventArgs args) => TestSynthCommandCanExecute(sender, args);
void TestLoopCommandExecute(object sender, ExecutedRoutedEventArgs args)
{
const int sampleRate = 48_000;
var sampler = new ErnstTech.SoundCore.Sampler.FuncSampler()
{
SampleFunc = drumView.Adapt(),
BitsPerSample = 32,
SampleRate = sampleRate,
Length = (long)(drumView.EffectTime * sampleRate)
};
beatLoopView.Sampler = sampler;
var stream = beatLoopView.WAVStream;
stream.Position = 0;
new System.Media.SoundPlayer(stream).Play();
}
}
}
<file_sep>using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace ErnstTech.SynthesizerControls
{
/// <summary>
/// Summary description for ThinSlider.
/// </summary>
public class ThinSlider : System.Windows.Forms.Control
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private Orientation _Orientation;
public Orientation Orientation
{
get { return this._Orientation; }
set
{
switch( value )
{
case Orientation.Horizontal:
case Orientation.Vertical:
break;
default:
throw new ArgumentOutOfRangeException("value", value, "The specified value is not a valid Orientation.");
}
this._Orientation = value;
this.OnOrientationChanged(EventArgs.Empty);
}
}
#region OrientationChanged Event
private static readonly object OrientationChangedEvent = new object();
/// <summary>
/// Raised when <see cref="Orientation"/> has changed.
/// </summary>
/// <value>
/// The delegate to add or remove as an event handler.
/// </value>
public event EventHandler OrientationChanged
{
add { this.Events.AddHandler(OrientationChangedEvent, value); }
remove { this.Events.RemoveHandler(OrientationChangedEvent,value); }
}
/// <summary>
/// Raises the <see cref="OrientationChanged"/> event.
/// </summary>
/// <param name="arguments">
/// Event arguments.
/// </param>
protected virtual void OnOrientationChanged(EventArgs arguments)
{
EventHandler handler = this.Events[OrientationChangedEvent] as EventHandler;
if (handler != null)
handler(this, arguments);
}
#endregion
private int _Minimum;
private int _Maximum = 100;
private int _Value;
public int Minimum
{
get{ return this._Minimum; }
set
{
if ( this._Minimum != value )
{
this._Minimum = value;
this.OnMinimumChanged( EventArgs.Empty );
}
}
}
#region MinimumChanged Event
private static readonly object MinimumChangedEvent = new object();
public event EventHandler MinimumChanged
{
add{ this.Events.AddHandler( MinimumChangedEvent, value ); }
remove{ this.Events.RemoveHandler( MinimumChangedEvent, value ); }
}
protected virtual void OnMinimumChanged( EventArgs arguments )
{
EventHandler handler = this.Events[MinimumChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
public int Maximum
{
get{ return this._Maximum; }
set
{
if ( this._Maximum != value )
{
this._Maximum = value;
this.OnMaximumChanged( EventArgs.Empty );
}
}
}
#region MaximumChanged Event
private static readonly object MaximumChangedEvent = new object();
public event EventHandler MaximumChanged
{
add{ this.Events.AddHandler( MaximumChangedEvent, value ); }
remove{ this.Events.RemoveHandler( MaximumChangedEvent, value ); }
}
protected virtual void OnMaximumChanged( EventArgs arguments )
{
EventHandler handler = this.Events[MaximumChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
private double _SliderScale;
public double SliderScale
{
get{ return this._SliderScale; }
}
public int Value
{
get{ return this._Value; }
set
{
if ( value < this.Minimum )
value = this.Minimum;
else if ( value > this.Maximum )
value = this.Maximum;
if ( this._Value != value )
{
this._Value = value;
this.OnValueChanged( EventArgs.Empty );
}
}
}
private int _Range;
public int Range
{
get{ return this._Range; }
}
#region ValueChanged Event
private static readonly object ValueChangedEvent = new object();
public event EventHandler ValueChanged
{
add{ this.Events.AddHandler( ValueChangedEvent, value ); }
remove{ this.Events.RemoveHandler( ValueChangedEvent, value ); }
}
protected virtual void OnValueChanged( EventArgs arguments )
{
EventHandler handler = this.Events[ValueChangedEvent] as EventHandler;
if ( handler != null )
handler( this, arguments );
}
#endregion
public ThinSlider()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
this.MinimumChanged += new EventHandler(RangeChanged);
this.MaximumChanged += new EventHandler(RangeChanged);
this.ValueChanged += new EventHandler(ThinSlider_ValueChanged);
this.SizeChanged += new EventHandler(ThinSlider_SizeChanged);
this.MouseMove += new MouseEventHandler(ThinSlider_MouseMove);
this.CalculateScale();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
protected override void OnPaint(PaintEventArgs pe)
{
if ( double.IsInfinity( this.SliderScale ) )
return;
Graphics g = pe.Graphics;
Rectangle rect = new Rectangle( 0, 0, this.Width, this.Height );
using ( Brush b = new SolidBrush( this.BackColor ) )
{
g.FillRectangle( b, rect );
}
int drawHeight = Convert.ToInt32( this.SliderScale * ( this.Value - this.Minimum ) );
rect.Y = this.Height - drawHeight;
rect.Height = drawHeight;
using ( Brush b = new SolidBrush( this.ForeColor ) )
{
g.FillRectangle( b, rect );
}
}
private void ThinSlider_ValueChanged(object sender, EventArgs e)
{
this.Invalidate();
}
private void RangeChanged(object sender, EventArgs e)
{
this.CalculateScale();
}
private void CalculateScale()
{
this._Range = this.Maximum - this.Minimum;
this._SliderScale = Convert.ToDouble( this.Range ) /
Convert.ToDouble( this.Height );
}
private void ThinSlider_SizeChanged(object sender, EventArgs e)
{
this.CalculateScale();
}
private void ThinSlider_MouseMove(object sender, MouseEventArgs e)
{
if ( e.Button == MouseButtons.Left )
{
int pos = this.Range - e.Y;
this.Value = Convert.ToInt32( this.SliderScale * pos );
}
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for DataChunk.
/// </summary>
public class DataChunk : Chunk
{
public override string ID => "data";
internal DataChunk(byte[] data)
: base(data)
{ }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis.Expressions.AST
{
public abstract class ExpressionNode
{
}
}
<file_sep>
using System;
using System.Threading;
using SharpDX;
using SharpDX.Multimedia;
using SharpDX.XAudio2;
using SharpDX.XAudio2.Fx;
using BufferFlags = SharpDX.XAudio2.BufferFlags;
namespace PlayDynamicSound
{
class Program
{
/// <summary>
/// SharpDX XAudio2 sample. Plays a generated sound with some reverb.
/// </summary>
static void Main(string[] args)
{
var xaudio2 = new XAudio2();
var masteringVoice = new MasteringVoice(xaudio2);
var waveFormat = new WaveFormat(44100, 32, 2);
var sourceVoice = new SourceVoice(xaudio2, waveFormat);
int bufferSize = waveFormat.ConvertLatencyToByteSize(60000);
var dataStream = new DataStream(bufferSize, true, true);
int numberOfSamples = bufferSize / waveFormat.BlockAlign;
for (int i = 0; i < numberOfSamples; i++)
{
// cos(2 * PI * (220 + 4 * cos(2 * PI * 10 * t)) * t) * 0.5
double vibrato = Math.Cos(2 * Math.PI * 10.0 * i / waveFormat.SampleRate);
float value = (float)(Math.Cos(2 * Math.PI * (220.0 + 4.0 * vibrato) * i / waveFormat.SampleRate) * 0.5);
dataStream.Write(value);
dataStream.Write(value);
}
dataStream.Position = 0;
var audioBuffer = new AudioBuffer { Stream = dataStream, Flags = BufferFlags.EndOfStream, AudioBytes = bufferSize };
var reverb = new Reverb(xaudio2);
var effectDescriptor = new EffectDescriptor(reverb);
sourceVoice.SetEffectChain(effectDescriptor);
sourceVoice.EnableEffect(0);
sourceVoice.SubmitSourceBuffer(audioBuffer, null);
sourceVoice.Start();
Console.WriteLine("Play sound");
for (int i = 0; i < 60; i++)
{
Console.Write(".");
Console.Out.Flush();
Thread.Sleep(1000);
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using ErnstTech.SoundCore.Synthesis;
namespace Synthesizer.Views
{
public class DrumView : ObservableObject
{
DrumGenerator _Generator = new DrumGenerator() { Source = new SawWave().Adapt() };
public double BaseFrequency
{
get => _Generator.BaseFrequency;
set => SetProperty(_Generator.BaseFrequency, value, _Generator, (g, v) => g.BaseFrequency = v);
}
public double PhaseShift1
{
get => _Generator.PhaseShift1;
set => SetProperty(_Generator.PhaseShift1, value, _Generator, (g, v) => g.PhaseShift1 = v);
}
public double PhaseShift2
{
get => _Generator.PhaseShift2;
set => SetProperty(_Generator.PhaseShift2, value, _Generator, (g, v) => g.PhaseShift2 = v);
}
public double AttackTime
{
get => _Generator.Envelope.AttackTime;
set => SetProperty(_Generator.Envelope.AttackTime, value, _Generator.Envelope, (e, v) => e.AttackTime = v);
}
public double DecayTime
{
get => _Generator.Envelope.DecayTime;
set => SetProperty(_Generator.Envelope.DecayTime, value, _Generator.Envelope, (e, v) => e.DecayTime = v);
}
public double SustainHeight
{
get => _Generator.Envelope.SustainHeight;
set => SetProperty(_Generator.Envelope.SustainHeight, value, _Generator.Envelope, (e, v) => e.SustainHeight = v);
}
public double SustainTime
{
get => _Generator.Envelope.SustainTime;
set => SetProperty(_Generator.Envelope.SustainTime, value, _Generator.Envelope, (e, v) => e.SustainTime = v);
}
public double ReleaseTime
{
get => _Generator.Envelope.ReleaseTime;
set => SetProperty(_Generator.Envelope.ReleaseTime, value, _Generator.Envelope, (e, v) => e.ReleaseTime = v);
}
public double EffectTime => _Generator.Envelope.ReleaseEnd;
public Func<double, double> Adapt() => _Generator.Adapt();
}
}
<file_sep>using System;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using ErnstTech.SoundCore.Sampler;
namespace Synthesizer.Views
{
public class BeatView : ObservableObject
{
int _Index = -1;
public int Index
{
get => _Index;
set => SetProperty(ref _Index, value);
}
BeatState _State = BeatState.Off;
public BeatState State
{
get => _State;
set => SetProperty(ref _State, value);
}
public double Level
{
get => Parent.Beats[Index].Level;
set => SetProperty(Parent.Beats[Index].Level, value, Parent.Beats[Index], (o, v) => o.Level = v);
}
public BeatLoop Parent { get; init; }
public BeatView(BeatLoop parent, int index)
{
this.Parent = parent;
this._Index = index;
this._State = StateFromLevel(Level);
this.PropertyChanged += OnPropertyChanged; ;
}
private void OnPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (string.IsNullOrWhiteSpace(e.PropertyName) || e.PropertyName == "State")
Level = LevelFromState(State);
if (string.IsNullOrWhiteSpace(e.PropertyName) || e.PropertyName == "Level")
_State = StateFromLevel(Level);
}
static BeatState StateFromLevel(double level) => level switch
{
Beat.Full => BeatState.Full,
Beat.Half => BeatState.Half,
Beat.Off => BeatState.Off,
_ => BeatState.Custom
};
double LevelFromState(BeatState state) => state switch
{
BeatState.Off => Beat.Off,
BeatState.Half => Beat.Half,
BeatState.Full => Beat.Full,
_ => Parent.Beats[Index].Level
};
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ErnstTech.SoundCore;
namespace Synthesizer.Controls
{
/// <summary>
/// Interaction logic for BaseDrumControl.xaml
/// </summary>
public partial class BaseDrumControl : UserControl
{
public static readonly RoutedUICommand TestCommand = new RoutedUICommand("Test Base Drum", nameof(TestCommand), typeof(BaseDrumControl));
public Views.BaseDrumView View
{
get { return (Views.BaseDrumView)DataContext; }
set { DataContext = value; }
}
public BaseDrumControl()
{
InitializeComponent();
this.DataContext = new Views.BaseDrumView();
this.CommandBindings.Add(new CommandBinding(
TestCommand,
(o, a) => { new System.Media.SoundPlayer(WaveWriter.Write(48_000, 48_000, View.Adapt())).Play(); },
(o, a) => { a.CanExecute = true; }
));
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveBufferEmptyEvent.
/// </summary>
public class WaveBufferEmptyEventArgs : EventArgs
{
private IntPtr _Buffer;
public IntPtr Buffer
{
get{ return _Buffer; }
}
private int _Length;
public int Length
{
get{ return _Length; }
}
private int _BytesWritten = -1;
public int BytesWritten
{
get{ return _BytesWritten; }
set{ _BytesWritten = value; }
}
/// <summary>
/// Initializes the event arguments.
/// </summary>
/// <param name="buffer">Pointer to the data buffer that is empty.</param>
/// <param name="length">Length of the buffer, in bytes.</param>
public WaveBufferEmptyEventArgs( IntPtr buffer, int length )
{
if ( buffer == IntPtr.Zero )
throw new ArgumentException( "buffer", "Buffer must be a valid pointer." );
_Buffer = buffer;
_Length = length;
}
}
}
<file_sep>using System;
namespace ErnstTech.SynthesizerControls
{
/// <summary>
/// Summary description for BeatState.
/// </summary>
public enum BeatState : byte
{
On = 2,
Half = 1,
Off = 0
}
}
<file_sep>using System;
using System.IO;
using System.Text;
using Antlr4.Runtime;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;
using ErnstTech.SoundCore.Synthesis.Expressions.AST;
namespace ErnstTech.SoundCore.Synthesis.Expressions.Antlr
{
public class ParseError : Exception
{
public ParseError() : base()
{ }
public ParseError(string message) : base(message)
{ }
}
internal class ThrowingErrorListener<TSymbol> : IAntlrErrorListener<TSymbol>
{
#region IAntlrErrorListener<TSymbol> Implementation
public void SyntaxError(TextWriter output, IRecognizer recognizer, TSymbol offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
{
throw new ParseError($"line {line}:{charPositionInLine} {msg}");
}
#endregion
}
public class ExpressionParser : IExpressionParser
{
public ExpressionNode Parse(string expression)
{
var stream = CharStreams.fromString(expression);
var lexer = new AudioSynthesisGrammarLexer(stream);
var tokens = new CommonTokenStream(lexer);
var parser = new AudioSynthesisGrammarParser(tokens);
parser.BuildParseTree = true;
parser.RemoveErrorListeners();
parser.AddErrorListener(new ThrowingErrorListener<IToken>());
IParseTree tree = parser.compileUnit();
var visitor = new AudioSynthesisVisitor();
var res = tree.Accept(visitor);
if (res is null)
throw new ParseError("Unexpected null building AST.");
return res;
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveDevices.
/// </summary>
public sealed class WaveDevices
{
private WaveDevices()
{}
public int GetDeviceCount()
{
return WaveFormNative.waveOutGetNumDevs();
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore.Synthesis
{
public class TriWave
{
/// <summary>
/// Period, in seconds.
/// </summary>
public double Period { get; init; } = 1.0;
public double MaxValue { get; init; } = 1.0;
public double MinValue { get; init; } = -1.0;
public TriWave()
{ }
public double Sample(double time)
{
var local = time - Period * Math.Truncate(time / Period);
var half = this.Period / 2.0;
var slope = 2 * (MaxValue - MinValue) / Period;
if (local < half)
return local * slope + MinValue;
else if (local > half)
return MaxValue - (local - half) * slope;
return MaxValue;
}
public Func<double, double> Adapt() => (double t) => Sample(t);
}
}
<file_sep>using ErnstTech.SoundCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Synthesizer
{
public partial class WaveFormView2 : Form
{
WaveReader _Reader;
double xZoom = 1.0;
public WaveFormView2(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
InitializeComponent();
_Reader = new WaveReader(stream);
for (short i = 0; i < _Reader.Format.Channels; ++i)
{
switch (_Reader.Format.BitsPerSample)
{
case 8: this.wavePlot.plt.PlotSignalConst(_Reader.GetChannelInt8(i).Select(x => (float)x).ToArray()); break;
case 16: this.wavePlot.plt.PlotSignalConst(_Reader.GetChannelInt16(i).Select(x => (float)x).ToArray()); break;
case 32: this.wavePlot.plt.PlotSignalConst(_Reader.GetChannelFloat(i).ToArray()); break;
default:
throw new NotSupportedException($"Invalid sample size: {_Reader.Format.BitsPerSample}.");
};
}
this.wavePlot.MouseWheel += WavePlot_MouseWheel;
this.wavePlot.plt.AxisAuto(horizontalMargin: 0, verticalMargin: 0);
}
private void WavePlot_MouseWheel(object sender, MouseEventArgs e)
{
var delta = e.Delta / 120.0; // Windows constant
var existing = this.wavePlot.plt.AxisZoom();
if (e.Delta > 0)
xZoom = 10; // xZoom *= 10 * delta;
else if (e.Delta < 0)
xZoom = 0.1; // xZoom /= 10 * delta;
this.wavePlot.plt.AxisZoom(xFrac: xZoom, yFrac: 1.0);
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveBufferEmptyHandler.
/// </summary>
public delegate void WaveBufferEmptyHandler( object sender, WaveBufferEmptyEventArgs arguments );
}
<file_sep>using System;
using System.Runtime.InteropServices;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveFormNative.
/// </summary>
internal static class WaveFormNative
{
private const string WaveFormLibrary = "winmm.dll";
// Import Native Library Functions
[DllImport(WaveFormLibrary)]
public static extern int waveOutGetNumDevs();
[DllImport(WaveFormLibrary)]
public static extern int waveOutOpen(out IntPtr device, int deviceID, ref WaveFormatEx format, WaveOutProcDelegate callback, int instance, int flags);
[DllImport(WaveFormLibrary)]
public static extern int waveOutClose(IntPtr device);
[DllImport(WaveFormLibrary)]
public static extern int waveOutReset(IntPtr device);
[DllImport(WaveFormLibrary)]
public static extern int waveOutPrepareHeader(IntPtr device, ref WaveHeader header, int size);
[DllImport(WaveFormLibrary)]
public static extern int waveOutUnprepareHeader(IntPtr device, ref WaveHeader header, int size);
[DllImport(WaveFormLibrary)]
public static extern int waveOutWrite(IntPtr device, ref WaveHeader header, int size);
[DllImport(WaveFormLibrary)]
public static extern int waveOutPause(IntPtr device);
[DllImport(WaveFormLibrary)]
public static extern int waveOutRestart(IntPtr device);
[DllImport(WaveFormLibrary)]
public static extern int waveOutGetPosition(IntPtr device, out int info, int size);
[DllImport(WaveFormLibrary)]
public static extern int waveOutSetVolume(IntPtr device, int volume);
[DllImport(WaveFormLibrary)]
public static extern int waveOutGetVolume(IntPtr device, out int volume);
[DllImport(WaveFormLibrary)]
public static extern int waveOutGetErrorText( int errorNumber, IntPtr buffer, int size );
[DllImport(WaveFormLibrary)]
public static extern int waveOutGetDevCaps( int device, ref WaveOutCapabilities cap, int size );
[DllImport(WaveFormLibrary)]
public static extern int waveOutSetPlaybackRate( IntPtr device, int rate );
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Numerics;
namespace ErnstTech.Math
{
public class FastFourierTransform
{
public static void Transform(int sign, Complex[] data)
{
long length = data.LongLength;
double scale = System.Math.Sqrt(1.0 / length);
long i, j;
for (i = j = 0; i < length; ++i)
{
if (j >= i)
{
double tempr = data[j].Real * scale;
double tempi = data[j].Imaginary * scale;
data[j] = new Complex(data[i].Real * scale, data[i].Imaginary * scale);
data[i] = new Complex(tempr * scale, tempi * scale);
}
long m = length / 2;
while (m >= 1 && j >= m)
{
j -= m;
m /= 2;
}
j += m;
}
for (long mmax = 1, istep = 2;
mmax < length;
mmax = istep, istep *= 2)
{
double delta = sign * System.Math.PI / mmax;
for (long m = 0; m < mmax; ++m)
{
double w = m * delta;
double wr = System.Math.Cos(w);
double wi = System.Math.Sin(w);
for (i = m; i < length && j < length; i += istep, j = i + mmax)
{
double tr = wr * data[j].Real - wi * data[j].Imaginary;
double ti = wr * data[j].Imaginary + wi * data[j].Real;
data[j] = new Complex(data[i].Real - tr, data[i].Imaginary - ti);
data[i] = new Complex(data[i].Real + tr, data[i].Imaginary + ti);
}
}
mmax = istep;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Synthesizer.Views
{
public enum BeatState
{
Off,
Half,
Full,
Custom
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ErnstTech.SoundCore.Synthesis
{
public abstract class WaveFormStream : Stream
{
#region Public Properties
/// <summary>
/// Inidicates if the stream can be read.
/// </summary>
/// <value>
/// Always returns <i>true</i>.
/// </value>
public override bool CanRead
{
get { return true; }
}
/// <summary>
/// Indicates if the stream can timeout.
/// </summary>
/// <value>
/// Always returns <i>false</i>.
/// </value>
public override bool CanTimeout
{
get { return false; }
}
/// <summary>
/// Indicates if the stream can be written to.
/// </summary>
/// <value>
/// Always returns <i>false</i>.
/// </value>
public override bool CanWrite
{
get { return false; }
}
/// <summary>
/// Indiciates if seeking is allowed on the stream.
/// </summary>
/// <value>
/// Always returns <i>false</i>.
/// </value>
public override bool CanSeek
{
get { return false; }
}
#endregion
private long _Position = 0;
/// <summary>
/// Gets the position in the stream.
/// </summary>
/// <exception cref="NotSupportException">
/// Always thrown if the property is set.
/// </exception>
public override long Position
{
get
{
return _Position;
}
set
{
throw new NotSupportedException("Position cannot be set.");
}
}
private long _SampleNumber = 0;
public virtual long SampleNumber
{
get { return this._SampleNumber; }
}
private const int _BufferSize = 4096;
private byte[] _Buffer = new byte[_BufferSize];
private AudioMode _AudioMode;
public AudioMode AudioMode
{
get { return _AudioMode; }
}
private AudioBits _AudioBits;
public AudioBits AudioBits
{
get { return _AudioBits; }
}
protected WaveFormStream( AudioBits quality, AudioMode channels )
{
this._AudioBits = quality;
this._AudioMode = channels;
this.WriteHeader();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new Exception("The method or operation is not implemented.");
}
public override int ReadByte()
{
throw new Exception("The method or operation is not implemented.");
}
private void FillBuffer()
{
}
private void WriteHeader()
{
}
}
}
<file_sep>using System;
using System.IO;
using System.Runtime.InteropServices;
namespace ErnstTech.SoundCore
{
/// <summary>
/// Summary description for WaveOutStream.
/// </summary>
public class WaveOutStream : System.IO.BinaryWriter
{
const int DefaultBufferSize = 512 * 1024; // 512 KB
private Stream _BaseStream;
public override Stream BaseStream
{
get
{
return _BaseStream;
}
}
private bool _IsPlaying = false;
public bool IsPlaying
{
get{ return _IsPlaying; }
}
private bool _IsPaused = false;
public bool IsPaused
{
get{ return _IsPaused; }
}
private int _InitialCapacity = DefaultBufferSize;
public int InitialCapacity
{
get
{
return this._InitialCapacity;
}
}
public int Capacity
{
get
{
if ( _BaseStream is MemoryStream )
return ((MemoryStream)_BaseStream).Capacity;
return -1;
}
}
public long Length
{
get
{
return _BaseStream.Length;
}
}
public AudioBits Quality
{
get{ return (AudioBits)_Format.BitsPerSample; }
}
public AudioMode Mode
{
get{ return (AudioMode)_Format.Channels; }
}
public SampleRate Rate
{
get{ return (SampleRate)_Format.SamplesPerSecond; }
}
private int _Device = -1;
public int Device
{
get{ return _Device; }
}
private int _BufferCount = 8;
public int BufferCount
{
get{ return _BufferCount; }
}
public int BufferLength
{
get
{
int length = Convert.ToInt32(Convert.ToDouble( (int)Rate ) * 0.4 * Convert.ToDouble((int)this.Mode) * Convert.ToDouble((int)this.Quality) / 8.0 );
int waste = length % BlockAlign;
length += BlockAlign - waste;
return length;
}
}
public short BlockAlign
{
get
{
return _Format.BlockAlignment;
}
}
#pragma warning disable CS0649
// TODO
private WavePlayer _Player;
#pragma warning restore
private WaveFormat _Format;
/// <summary>
///
/// </summary>
/// <param name="waveIn"></param>
public WaveOutStream( int device, Stream waveIn ) : base()
{
if ( waveIn == null )
throw new ArgumentNullException( "waveIn" );
_Device = device;
_BaseStream = waveIn;
ReadWaveHeader( waveIn );
Init();
}
public WaveOutStream( int device, AudioBits quality, AudioMode mode, SampleRate rate ) : base()
{
_Format = new WaveFormat( (short)mode, (int)rate, (short)quality );
this._BaseStream = new MemoryStream( this.InitialCapacity );
Init();
}
private int ReadInt32( Stream stream )
{
if ( stream == null )
throw new ArgumentNullException( "stream " );
byte[] buffer = new byte[4];
stream.Read( buffer, 0, 4 );
return ((buffer[0])|(buffer[1] << 8)|(buffer[2] << 16)|(buffer[3] << 24));
}
private void ReadWaveHeader( Stream stream )
{
byte[] buffer = new byte[4];
stream.Read( buffer, 0, 4 );
string id = System.Text.ASCIIEncoding.ASCII.GetString( buffer );
if ( id != "RIFF" )
throw new SoundCoreException( "Expected Chunk type of 'RIFF'." );
int length = ReadInt32( stream );
if ( length != ( stream.Length - 8 ))
throw new SoundCoreException( string.Format( "Unexpected RIFF Chunk size.\nExpected: {0}\nRead from stream: {1}", (stream.Length - 8), length ) );
if ( !SeekToChunk( "WAVE" ) )
throw new SoundCoreException( "Could not find chunk type of 'WAVE'." );
_Format = new WaveFormat( stream );
switch( (SampleRate)_Format.SamplesPerSecond )
{
case SampleRate.Rate44100:
case SampleRate.Rate22050:
case SampleRate.Rate11025:
break;
default:
throw new SoundCoreException( "An unsupported sampling rate was encounted." );
}
if ( !SeekToChunk( "data" ) )
throw new SoundCoreException( "Could not find chunk type of 'data'." );
ReadInt32( _BaseStream );
}
private bool SeekToChunk( string id )
{
byte[] buffer = new byte[4];
bool found = false;
while( !found && _BaseStream.Position < _BaseStream.Length )
{
_BaseStream.Read( buffer, 0, 4 );
if ( System.Text.ASCIIEncoding.ASCII.GetString( buffer ) == id )
found = true;
}
return found;
}
/// <summary>
/// Initializes the playback stream
/// </summary>
private void Init()
{
}
public static int GetDevices()
{
return WavePlayer.NumDevices;
}
private void FillBufferHandler( object sender, WaveBufferEmptyEventArgs args )
{
byte[] buffer = new byte[args.Length];
int length = _BaseStream.Read( buffer, 0, args.Length );
for ( int i = length; i < args.Length; i++ )
{
buffer[i] = 0;
}
if ( length <= 0 )
{
_Player.Stop();
}
args.BytesWritten = length;
Marshal.Copy( buffer, 0, args.Buffer, length );
}
#region Audio Playback Controls
/// <summary>
/// Begins playing audio back from the current position.
/// </summary>
public virtual void Play()
{
this._IsPlaying = true;
this._IsPaused = false;
System.Diagnostics.Debug.Assert(false);
//_Player = new WavePlayer( this.Device, this.BufferLength, this.BufferCount,
// _Format, new WaveBufferEmptyHandler( FillBufferHandler ) );
}
/// <summary>
/// Pause playback from the last point written to wave buffer.
/// </summary>
public virtual void Pause()
{
this._IsPaused = true;
this._IsPlaying = false;
}
/// <summary>
/// Stops playback, returns to beginning of written data.
/// </summary>
public virtual void Stop()
{
this._IsPlaying = false;
this._IsPaused = false;
if ( _Player == null )
return;
if ( _Player.IsPlaying )
{
_Player.Stop();
_Player.Dispose();
}
}
#endregion
public override void Close()
{
if ( this.IsPlaying || this.IsPaused )
this.Stop();
base.Close ();
}
protected override void Dispose(bool disposing)
{
if ( disposing )
{
if ( this.IsPlaying || this.IsPaused )
this.Stop();
if ( _Player != null )
_Player.Dispose();
// TODO: Close wave output
this._BaseStream.Close();
}
base.Dispose (disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis.Expressions.AST
{
public abstract class Visitor<T>
{
// Time Variable
public abstract T Visit(TimeVariableNode node);
// Literals
public abstract T Visit(NumberNode node);
// Binary Operations
public abstract T Visit(AddNode node);
public abstract T Visit(SubtractNode node);
public abstract T Visit(MultiplyNode node);
public abstract T Visit(DivideNode node);
public abstract T Visit(ExponentiationNode node);
// Unary Operations
public abstract T Visit(AbsoluteValueNode node);
public abstract T Visit(NegateNode node);
// Function
public abstract T Visit(FunctionNode node);
public T Visit(ExpressionNode node) => Visit((dynamic)node);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErnstTech.SoundCore.Synthesis
{
public class BaseDrumGenerator
{
public Func<double, double> Source { get; set; }
public IList<double> Harmonics { get; set; }
public static IReadOnlyList<double> SampleHarmonics { get; private set; } = new List<double> { 43, 86, 129, 175, 218, 266 };
public BaseDrumGenerator(Func<double, double> source, IList<double> harmonics)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (harmonics == null)
throw new ArgumentNullException(nameof(harmonics));
if (harmonics.Count <= 0)
throw new ArgumentException("harmonics counts cannot be zero.", nameof(harmonics));
Source = source;
Harmonics = harmonics;
}
public BaseDrumGenerator()
: this(new TriWave().Sample, new List<double>(SampleHarmonics))
{ }
public Func<double, double> Adapt()
{
var source = Source;
var func = Harmonics
.Select<double, Func<double, double>>(h => (double t) => source(h * t))
.Aggregate((l, r) => (double t) => l(t) + r(t));
return func;
}
}
}
<file_sep>using System;
namespace ErnstTech.SoundCore.Synthesis
{
/// <summary>
/// Summary description for WaveForms.
/// </summary>
public sealed class WaveForms
{
private WaveForms()
{}
/// <summary>
///
/// </summary>
/// <param name="time"></param>
/// <param name="peak"></param>
/// <param name="frequency"></param>
/// <param name="dutyCycle"></param>
/// <returns></returns>
public static int TriangleWave( long sample, int sampleRate, int peak, int frequency, float dutyCycle )
{
int point = GetPoint( sample, frequency );
int period = GetPeriod( sampleRate, frequency );
return (int)( peak * (double)((double)point /(double)period));
}
public static int SquareWave( long sample, int sampleRate, int peak, int frequency, float dutyCycle )
{
if ( dutyCycle < 0 || dutyCycle > 1 )
throw new ArgumentOutOfRangeException( "dutyCycle", dutyCycle, "DutyCycle must be greater than or equal to zero and less than or equal to one." );
int point = GetPoint( sample, frequency );
int period = GetPeriod( sampleRate, frequency );
return (((double)point/(double)period) < dutyCycle ) ? peak : 0;
}
public static int SineWave( long sample, int sampleRate, int peak, int frequency, float dutyCycle )
{
int point = GetPoint( sample, frequency );
int period = GetPeriod( sampleRate, frequency );
double ratio = (double)point / (double)period;
double angle = 2.0 * Math.PI * ratio;
return (int)(peak * Math.Sin(angle));
}
/// <summary>
/// Returns the period, in the number of samples, of the specified frequency
/// </summary>
/// <param name="sampleRate">Sample rate to be used.</param>
/// <param name="frequency">Frequency to calculate the period for.</param>
/// <returns>The period corresponding to the passed frequency, in samples.</returns>
private static int GetPeriod( int sampleRate, int frequency )
{
return (int)((double)sampleRate / (double)frequency);
}
private static int GetPoint( long sample, int frequency )
{
if (frequency == 0)
throw new ArgumentException( "Frequency cannot be zero.", "frequency" );
return (int)( sample % frequency );
}
}
}
| 29e6aca6c769187e5b67a2fe74aca772ed35c2cb | [
"Markdown",
"C#"
] | 98 | C# | nernst/synth | 6251748f2c85ced35b1b742e85e14a03a12a8f03 | ca3a52b19f4d40fd75aff184787e4438be35b0c9 |
refs/heads/master | <repo_name>glpayson/pyhr<file_sep>/python/introduction/weird-if-else.py
#!/bin/python3
n = int(input())
if (n % 2 == 0) and (n == 2 or n == 4 or n > 20):
print("Not Weird")
else:
print("Weird")
<file_sep>/prep/warmup/jumping-on-clouds.py
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the jumpingOnClouds function below.
def jumpingOnClouds(c):
jumps = 0
for x in range(len(c)):
if x == len(c):
continue
elif x == len(c) - 1:
jumps += 1
elif c[x + 2] == 0:
continue
else:
jumps += 1
return jumps
foo = jumpingOnClouds([0, 0, 1, 0, 0, 1, 0])
bar = 11
<file_sep>/prep/warmup/counting-valleys.py
#!/bin/python3
import os
def counting_valleys(n, s):
elevation = 0
for c in s:
elevation = elevation + 1 if c == 'U' else elevation - 1
n = n if elevation == 0 and c == 'U' else n - 1
return n
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
result = counting_valleys(n, s)
fptr.write(str(result) + '\n')
fptr.close()
<file_sep>/prep/warmup/sock-merchant.py
#!/bin/python3
import os
def sock_merchant(n, ar):
seen = set()
for i in ar:
if i in seen:
seen.remove(i)
else:
n -= 1
seen.add(i)
return n
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
ar = list(map(int, input().rstrip().split()))
result = sock_merchant(n, ar)
fptr.write(str(result) + '\n')
fptr.close()
| 54d673cce11f1c63453bb36745db8330ff0a2975 | [
"Python"
] | 4 | Python | glpayson/pyhr | 1ed5e914dc7a5285d7b2ddf1b9ae29bf547e9e01 | 20e7d1e4ff2a0377538b594784c8049748873b16 |
refs/heads/master | <file_sep>#pragma once
#include "Scene.h"
#include "MainMenu.h"
class Map
{
protected:
int initialScore;
int highScore;
double gravity; //à diviser par l'ecart de temps
/*
enum ElementTypes {VIDE, MUR, ONEWAY, ONEWAY_HAUT, ONEWAY_BAS, ONEWAY_GAUCHE, ONEWAY_DROITE,
PIQUE, SWITCH, GOAL, ROCHER, BOUTEILLE, BOUTEILLE_VIVANTE, BOUTEILLE_COULEUR1, BOUTEILLE_COULEUR2,
BOUTEILLE_COULEUR3, BLOC, BLOC_VIVANT, BLOC_COULEUR1, BLOC_COULEUR2, BLOC_COULEUR3, ANIMAL,
ANIMAL_COULEUR1, ANIMAL_COULEUR2, ANIMAL_COULEUR3, PLAYER, SPAWN};
*/
vector <vector<enum ElementTypes>> matrice;
vector <Scene> sauvegardes;
bool isPlaying;
public:
/* CONSTRUCTEURS */
Map();//Constructeur standard
Map(vector <vector<enum ElementTypes>>);
Map(int, vector <vector<enum ElementTypes>>);
Map(int, double, vector <vector<enum ElementTypes>>, vector <Scene>);
/* FONCTIONS MEMBRES DE LA CLASSE */
void finish();
Scene generate();
void quickSave();
void loadSave();
void update(RenderWindow&, vector <Event>);
void draw(RenderWindow &);
void restart();
/* GETER SETER */
int getInitialScore();
void setInitialScore(int);
double getGravity();
void setGravity(double);
vector <vector<enum ElementTypes>> getMatrice();
void setMatrice(vector <vector<enum ElementTypes>>);
vector <Scene> getSauvegardes();
void setSauvegardes(vector <Scene>);
bool getIsPlaying();
void setIsPlaying(bool);
};
<file_sep>#pragma once
#include "MobileEntity.h"
class Scene;
class Player:public MobileEntity
{
protected:
bool bringSomething;
GameObject* bringElement;
GameColor bringColor = NOCOLOR;
FloatRect interactionBox = FloatRect(0, 0, 160, 160);
public:
/* CONSTRUCTEURS */
Player();//Constructeur standard
Player(Vector2f, Texture, IntRect);//Constructeur utilisé dans la génération de la scene
/* FONCTIONS MEMBRES DE LA CLASSE */
void update(Scene *);
FloatRect getInteractionBox();
/* GETER SETER */
void moveTo(Direction);
bool getBringSomething();
void setBringSomething(bool);
GameObject* getBringElement();
void setBringElement(GameObject*);
GameColor getBringColor();
void setBringColor(GameColor);
void placeBringElement();
bool goingLeft();
};
<file_sep>#include "Rocher.h"
#include "Scene.h"
Rocher::Rocher():MobileGameplayElement()
{
}
//bool hateW, bool heavii, bool fly, double Speed, bool TraverseBlock, bool TraverseMur, bool MarcheSurBlock, bool traversable, Vector2f position, Texture texture, IntRect textrect
Rocher::Rocher(Vector2f position, Texture texture, IntRect textrect):
MobileGameplayElement(true,true,false,15,false,false,false,false, position, texture, textrect, NOCOLOR)
{
}
<file_sep>#pragma once
#include "MobileGameplayElement.h"
class Scene;
class Rocher : public MobileGameplayElement
{
public:
/* CONSTRUCTEURS */
Rocher();//Constructeur standard
Rocher(Vector2f, Texture, IntRect);//Constructeur utilisé dans la génération de la scene
};
<file_sep>#pragma once
#include "GameEntity.h"
//On a besoin de déclarer la classe en amont pour que Switch puisse la manipuler
class Scene;
class Switch:public GameEntity//Element interactif changeant la couleur des bouteilles
{
public:
/* CONSTRUCTEURS */
Switch();//Constructeur standard
Switch(Vector2f, Texture, IntRect);//Constructeur utilisé dans la génération de la scene
/* FONCTIONS MEMBRES DE LA CLASSE */
void interact(Scene *);//changement des couleurs quand le player ou un animal interagie avec le switch
};
<file_sep>#pragma once
#include "Player.h"
#include "Scene.h"
Player::Player() :MobileEntity()
{
bringSomething = false;
bringElement = NULL;
bringColor = GameColor::NOCOLOR;
}
Player::Player(Vector2f pos, Texture tex, IntRect rect) :MobileEntity(false, 15, true, false, true, 2, pos, tex, rect)
{
bringSomething = false;
bringElement = NULL;
bringColor = GameColor::NOCOLOR;
}
void Player::update(Scene*scene)
{
//cout << endl;
/*
setup original :
--
if keyboard Haut && !TestCollide Haut
moveto Up
if keyboard Bas && !TestCollide Bas
moveto Down
if playerhauteur!=0 &&é && TestCollide Haut
Kill velocity
if playerhauteur!=0 && TestCollide Bas
Faire attérir le personnage
if playerhauteur==0 && !TestCollide Bas
Faire tomber le personnage
--
avantages = propreté
defaut = TestCollide est Très gourmand
La nouvelle architecture peut paraitre bordellique, mais elle a l'avantage de limiter les calls de TestCollide
*/
//Input dans les 4 directions
initDirection();
GameObject* testcollhaut, *testcollbas;
testcollhaut = scene->testCollide(this, Direction::HAUT);
if (getHauteur() == 0 && Keyboard::isKeyPressed(Keyboard::Up) && !testcollhaut) {
//cout << "Up" << endl;
scene->setScore(scene->getScore() -3);
moveTo(Direction::HAUT);
}
//si la hauteur du personnage est superieur à 0 et qu'il monte, on vérifie s'il ne s'est pas cogné la tete
//Attention, il faut etre sur que son mouvement est montant
if (getHauteur() != 0 && acceleration.y < 0 && testcollhaut) {
setAcceleration(Vector2f(0, 0));
float localY = getSprite()->getPosition().y, LocalDelta;
localY = (int(localY) % 160) + localY - int(localY);
//cout << "localy : " << localY << endl;
if (localY < 80) {
localY = -localY;
}
else {
localY = 160 - localY;
}
getSprite()->move(Vector2f(0, localY));
}
testcollbas = scene->testCollide(this, Direction::BAS);
if (testcollbas) {//s'il descendais, et qu'il est entré en collision avec le sol,
//alors on le colle au dessus de l'élément collidé
if (getHauteur() != 0 && acceleration.y > 0) {
setHauteur(0);
FloatRect colliderGB = testcollbas->getSprite()->getGlobalBounds();
FloatRect localGB = sprite.getGlobalBounds();
float LocalDelta = (colliderGB.top - localGB.height) - localGB.top;
sprite.move(Vector2f(0, LocalDelta));
}
}
else if (getHauteur() == 0) {
setHauteur(1);
}
if (Keyboard::isKeyPressed(Keyboard::Left) && !scene->testCollide(this, Direction::GAUCHE)) {
scene->setScore(scene->getScore() - 1);
//cout << "Left" << endl;
moveTo(Direction::GAUCHE);
}
if (Keyboard::isKeyPressed(Keyboard::Right) && !scene->testCollide(this, Direction::DROITE))
{
scene->setScore(scene->getScore() - 1);
//cout << "Right" << endl;
moveTo(Direction::DROITE);
}
updatePos(9.8 / 12);
}
FloatRect Player::getInteractionBox()
{
FloatRect gb = sprite.getGlobalBounds();
interactionBox.top = gb.top - ((interactionBox.height - gb.height)/2);
if (!goingLeft()) {
// right
interactionBox.left = gb.left + gb.width;
}
else {
//left
interactionBox.left = gb.left - interactionBox.width;
}
return interactionBox;
}
void Player::moveTo(Direction d)
{
MobileEntity::moveTo(d);
IntRect tr = this->sprite.getTextureRect();
if (d == Direction::DROITE) {
tr.top = this->textureRect.top;
}
else if (d == Direction::GAUCHE) {
tr.top = this->textureRect.top + 32;
}
this->sprite.setTextureRect(tr);
}
bool Player::getBringSomething()
{
return bringSomething;
}
void Player::setBringSomething(bool b)
{
bringSomething = b;
/**
bringElement = NULL;
bringColor = NOCOLOR;
sprite.setColor(getColorFromEnum(bringColor));
/**/
}
GameObject* Player::getBringElement()
{
return bringElement;
}
void Player::setBringElement(GameObject* be)
{
if (be != NULL)
{
bringElement = be;
bringSomething = true;
bringColor = NOCOLOR;
if (dynamic_cast<Rocher*>(bringElement)) {
textureRect.top = 3 * 2 * textureRect.height;
}
if (dynamic_cast<Block*>(bringElement)) {
textureRect.top = 2 * 2 * textureRect.height;
}
}
else {
if (bringElement != NULL) {// Si il y a un élément, on le replace dans la scene
placeBringElement();
}
bringElement = be;
bringSomething = false;
textureRect.top = 0 * 2 * textureRect.height;
}
}
GameColor Player::getBringColor()
{
return bringColor;
}
void Player::setBringColor(GameColor b)
{
bringColor = b;
sprite.setColor(getColorFromEnum(bringColor));
if( b == NOCOLOR)
bringSomething = false;
else
bringSomething = true;
}
void Player::placeBringElement()
{
Vector2f newPos = sprite.getPosition();
FloatRect gb = sprite.getGlobalBounds();
//on regarde le type de texture sur le joueur (si c'est la texture droite ou la texture gauche)
newPos.y = gb.top + (gb.height / 4);
if (!goingLeft()) {
// right
newPos.x = gb.left + gb.width;
}
else {
//
newPos.x = gb.left - bringElement->getSprite()->getGlobalBounds().width;
}
bringElement->getSprite()->setPosition(newPos);
}
bool Player::goingLeft()
{
//on regarde le type de texture sur le joueur (si c'est la texture droite ou la texture gauche)
return sprite.getTextureRect().top != this->textureRect.top;
}
<file_sep>#pragma once
#include "GameEntity.h"
class spike :public GameEntity//element qui tue le joueur s'il le touche
{
public:
/* CONSTRUCTEURS */
spike();//Constructeur standard
spike(Vector2f, Texture, IntRect);//Constructeur utilisé dans la génération de la scene
};
<file_sep>#include "spike.h"
spike::spike():GameEntity()
{
}
spike::spike(Vector2f pos, Texture tex, IntRect rect) : GameEntity(true, pos, tex, rect)
{
}
<file_sep>#include "GameEntity.h"
GameEntity::GameEntity():GameObject()
{
traversable = false;
}
GameEntity::GameEntity(bool t)
{
traversable = t;
}
bool GameEntity::getTraversable()
{
return traversable;
}
void GameEntity::setTraversable(bool t)
{
traversable= t;
}
GameEntity::GameEntity(bool t, Vector2f pos, Texture tex, IntRect rect) : GameObject(pos, tex, rect)
{
traversable = t;
}
GameEntity::GameEntity(bool t, int intervalFrame, Vector2f pos, Texture tex, IntRect rect) : GameObject(intervalFrame,pos, tex, rect)
{
traversable = t;
}
void GameEntity::interact()
{
//cout << "Interaction Yeah" << endl;
}
<file_sep>#pragma once
#include "PaintableElement.h"
class MobileGameplayElement: public PaintableElement
{
protected:
enum MovingState movingState = IDLE;
bool HateWalls;
bool heavy;
Clock SwitchMouvementClock;
double SwitchMouvementDelay = 2; //in seconds
/*
1/2 DUPLIQUE DE MobileEntity
propriétés
*/
bool flying;//pour les blocks
double speed;
Vector2f acceleration;
Vector2f direction;
bool TraverseBlock;// les animaux ne traversent pas les blocks
bool TraverseMur;// les Blocks traversent les murs
bool MarcheSurBlock;// le personnage en mode Rocher tombe au travers des blocks
double Hauteur;// 0 au sol, 1++ quand on est en air
Sprite Fantome;
public:
/* CONSTRUCTEURS */
MobileGameplayElement();//Constructeur standard
/*
Les constructeurs suivant servent pour etre intégrés dans la construction de classes filles
*/
MobileGameplayElement(bool, bool, GameColor);
MobileGameplayElement(bool, bool, bool, bool, GameColor);
MobileGameplayElement(bool, bool, bool, bool, bool, double, bool, bool, bool, GameColor);
MobileGameplayElement(bool, bool, bool, double, bool, bool, bool, bool, Vector2f, Texture, IntRect, GameColor);
MobileGameplayElement(bool, bool, bool, double, bool, bool, bool, bool, Vector2f, Texture, IntRect, bool, bool, GameColor);
MobileGameplayElement(bool, bool, bool, double, bool, bool, bool, bool, int, Vector2f, Texture, IntRect, GameColor);
MobileGameplayElement(bool, bool, bool, double, bool, bool, bool, bool, int, Vector2f, Texture, IntRect, bool, bool, GameColor);
/* FONCTIONS MEMBRES DE LA CLASSE */
void update(Scene*);
/* GETER SETER */
enum MovingState getMovingState();
void setMovingState(enum MovingState);
bool getHateWalls();
void setHateWalls(bool);
bool getHeavy();
void setHeavy(bool);
/*
2/2 DUPLIQUE DE MobileEntity
Fonctions
*/
/* FONCTIONS MEMBRES DE LA CLASSE */
void moveTo(Direction);
void updatePos(double);//Gravity
void initDirection();
Sprite getUpdatedFantome(Direction);
/* GETER SETER */
bool getFlying();
void setFlying(bool);
double getSpeed();
void setSpeed(double);
Vector2f getAcceleration();
void setAcceleration(Vector2f);
Vector2f getDirection();
void setDirection(Vector2f);
bool getTraverseBlock();
void setTraverseBlock(bool);
bool getTraverseMur();
void setTraverseMur(bool);
bool getMarcheSurBlock();
void setMarcheSurBlock(bool);
double getHauteur();
void setHauteur(double);
Sprite getFantome();
void setFantome(Sprite);
};
<file_sep>#pragma once
#include "MobileGameplayElement.h"
class Block :public MobileGameplayElement
{
protected:
bool vivant = false;
public:
/* CONSTRUCTEURS */
Block();//Constructeur standard
Block(Vector2f, Texture, IntRect);//Constructeurs utilisable dans la génération de la scene
Block(bool,Vector2f, Texture, IntRect);//Constructeurs utilisable dans la génération de la scene
Block(GameColor, Vector2f, Texture, IntRect);//Constructeurs utilisable dans la génération de la scene
Block(bool, GameColor,Vector2f, Texture, IntRect);//Constructeurs utilisable dans la génération de la scene
/* Constructeurs alternatifs */
Block(GameColor);
Block(bool);
Block(bool, GameColor);
/* FONCTIONS MEMBRES DE LA CLASSE */
void update(Scene*);
/* GETER SETER */
bool getVivant();
void setVivant(bool);
};
<file_sep>#pragma once
#include "GameObject.h"
class MobileEntity:public GameObject //désigne tout élément qui se déplace de manière autonome
{
protected:
bool flying;// vrai pour les blocks, définis si une entité subit la gravité ou pas
double speed;// vitesse de deplacement
Vector2f acceleration;// vecteur d'acceleration (utilisé principalement pour la gravité)
Vector2f direction;// vecteur de direction
bool TraverseBlock;// Si une entité peut traverser les blocks ou pas : les animaux ne traversent pas les blocks
bool TraverseMur;// Si une entité peut traverser les murs ou pas : les Blocks traversent les murs
bool MarcheSurBlock;// Si une entité peut marcher sur les blocks ou pas : le personnage en mode Rocher tombe au travers des blocks
double Hauteur;// 0 au sol, 1++ quand on est en air (utilisé pour activer la gravité ou pas
Sprite Fantome;// Sprite identique à la sprite de l'entité, elle est déplacée avant un vrai déplacement pour savoir si l'espace est libre
/*
Retour sur le système de collision fantome
Positif : Simple à mettre en place et adapté dans un jeu 2D ou les éléments ne se survolent pas
(Dans un jeu 3D classique, cette solution est parfaite)
Negatif : En 2D, Dés que l'on a des éléments que l'on peut traverser sans problème, on a des glitchs.
*/
public:
/* CONSTRUCTEURS */
MobileEntity();//Constructeur standard
/*
Les constructeurs suivant servent pour etre intégrés dans la construction de classes filles
*/
MobileEntity(Vector2f, Texture, IntRect);
MobileEntity(int, Vector2f, Texture, IntRect);
MobileEntity(bool, double, bool, bool,bool);
MobileEntity(bool, double, bool, bool, bool, Vector2f, Texture, IntRect);
MobileEntity(bool, double, bool, bool, bool, int, Vector2f, Texture, IntRect);
MobileEntity(bool, double, Vector2f, Vector2f, bool, bool, bool, double);
MobileEntity(bool, double, Vector2f, Vector2f, bool, bool, bool, double, Vector2f, Texture, IntRect);
MobileEntity(bool, double, Vector2f, Vector2f,bool, bool, bool, double, int, Vector2f, Texture, IntRect);
/* FONCTIONS MEMBRES DE LA CLASSE */
void moveTo(Direction);
void updatePos(double);//Gravity
void initDirection();
Sprite getUpdatedFantome(Direction);
/* GETER SETER */
bool getFlying();
void setFlying(bool);
double getSpeed();
void setSpeed(double);
Vector2f getAcceleration();
void setAcceleration(Vector2f);
Vector2f getDirection();
void setDirection(Vector2f);
bool getTraverseBlock();
void setTraverseBlock(bool);
bool getTraverseMur();
void setTraverseMur(bool);
bool getMarcheSurBlock();
void setMarcheSurBlock(bool);
double getHauteur();
void setHauteur(double);
Sprite getFantome();
void setFantome(Sprite);
};
<file_sep>#include "MainMenu.h"
MainMenu::MainMenu(int width, int height, Font *font)
{
for (size_t j = 0; j < 5; j++)
{
elements.push_back(Text());
}
for (int i = 0; i < elements.size(); i++)
{
elements.at(i).setFont(*font);
elements.at(i).setPosition(width / 2, height / (elements.size() + 1) * (i + 1.2));
if (i == 0)
elements.at(i).move(100,0);
elements.at(i).setFillColor(Color::White);
elements.at(i).setCharacterSize(40);
}
elements[0].setString("Play Level1");
elements[1].setString("Play Level2");
elements[2].setString("Play Level3");
elements[3].setString("Play Level4");
elements[4].setString("Exit/return");
titre.setFont(*font);
titre.setPosition(width / 2, 0);
titre.setCharacterSize(80);
titre.setFillColor(Color::Magenta);
titre.setString("Menu");
}
MainMenu::MainMenu(int width, int height, Font* font, String titreTexte)
{
for (size_t j = 0; j < 5; j++)
{
elements.push_back(Text());
}
for (int i = 0; i < elements.size(); i++)
{
elements.at(i).setFont(*font);
elements.at(i).setPosition(width / 2, height / (elements.size() + 1) * (i + 1.2));
if (i == 0)
elements.at(i).move(100, 0);
elements.at(i).setFillColor(Color::White);
elements.at(i).setCharacterSize(40);
}
elements[0].setString("Play Level1");
elements[1].setString("Play Level2");
elements[2].setString("Play Level3");
elements[3].setString("Play Level4");
elements[4].setString("Exit/return");
titre.setFont(*font);
titre.setPosition(width / 2, 0);
titre.setCharacterSize(80);
titre.setFillColor(Color::Magenta);
titre.setString(titreTexte);
}
MainMenu::MainMenu(int width, int height, Font *font, vector<String> texts)
{
for (size_t j = 0; j < texts.size(); j++)
{
elements.push_back(Text());
}
for (int i = 0; i < elements.size(); i++)
{
elements.at(i).setFont(*font);
elements.at(i).setPosition(width / 2, height / (elements.size() + 1) * (i + 1.2));
if (i == 0)
elements.at(i).move(100, 0);
elements.at(i).setFillColor(Color::White);
elements.at(i).setCharacterSize(40);
elements[i].setString(texts[i]);
}
titre.setFont(*font);
titre.setPosition(width / 2, 0);
titre.setCharacterSize(80);
titre.setFillColor(Color::Magenta);
titre.setString("Menu");
}
MainMenu::MainMenu(int width, int height, Font* font, vector<String> texts, String titreTexte)
{
for (size_t j = 0; j < texts.size(); j++)
{
elements.push_back(Text());
}
for (int i = 0; i < elements.size(); i++)
{
elements.at(i).setFont(*font);
elements.at(i).setPosition(width / 2, height / (elements.size() + 1) * (i + 1.2));
if (i == 0)
elements.at(i).move(100, 0);
elements.at(i).setFillColor(Color::White);
elements.at(i).setCharacterSize(40);
elements[i].setString(texts[i]);
}
titre.setFont(*font);
titre.setPosition(width / 2, 0);
titre.setCharacterSize(80);
titre.setFillColor(Color::Magenta);
titre.setString(titreTexte);
}
void MainMenu::drawMe(RenderWindow& GM)
{
View v = GM.getView();
IntRect centerBox = GM.getViewport(v);
centerBox.top = 0;
centerBox.left = 600;
Vector2f centre;
centre.y = centerBox.top + (centerBox.height / 2);
centre.x = centerBox.left + (centerBox.width / 2);
v.setCenter(centre);
GM.setView(v);
GM.clear();
for (int i = 0; i < elements.size(); i++)
{
//cout << i << endl;
GM.draw(elements[i]);
}
GM.draw(titre);
GM.display();
}
void MainMenu::MoveUp()
{
elements.at(SelectedItemIndex).move(-100, 0);
if (SelectedItemIndex == 0) {
SelectedItemIndex = elements.size() - 1;
}
else
SelectedItemIndex = (SelectedItemIndex - 1) % elements.size();
//cout << SelectedItemIndex << endl;
elements.at(SelectedItemIndex).move(100, 0);
}
void MainMenu::MoveDown()
{
elements.at(SelectedItemIndex).move(-100, 0);
SelectedItemIndex = (SelectedItemIndex + 1) % elements.size();
elements.at(SelectedItemIndex).move(100, 0);
}
bool MainMenu::getOpened()
{
return opened;
}
void MainMenu::setOpened(bool o)
{
opened = o;
}
int MainMenu::getSelectedItemIndex()
{
return SelectedItemIndex;
}
<file_sep>#include "ElementContainer.h"
<file_sep>#include "FocusableElement.h"
FocusableElement::FocusableElement():GameEntity(true)
{
focused = locked = false;
}
FocusableElement::FocusableElement(bool t): GameEntity(t)
{
focused = locked = false;
}
FocusableElement::FocusableElement(bool f, bool l, bool t):GameEntity(t)
{
focused = f;
locked = l;
}
FocusableElement::FocusableElement( bool trav, Vector2f pos, Texture tex, IntRect rect) : GameEntity(trav, pos, tex, rect)
{
}
FocusableElement::FocusableElement(bool trav, int interframe, Vector2f pos, Texture tex, IntRect rect) : GameEntity(trav, interframe, pos, tex, rect)
{
}
bool FocusableElement::getFocused()
{
return focused;
}
void FocusableElement::setFocused(bool f)
{
focused = f;
}
bool FocusableElement::getLocked()
{
return locked;
}
void FocusableElement::setLocked(bool l)
{
locked = l;
}
<file_sep>#include "Scene.h"
Scene::Scene()
{
score = 0;
ScoreString.setString(to_string(score));
ScoreString.setCharacterSize(60);
ScoreString.setStyle(Text::Regular);
ScoreString.setOutlineThickness(20);
}
Scene::Scene(int s, vector<vector<enum ElementTypes>> m)
{
//cout << "Generation" << endl;
score = s;
generate(m);
ScoreString.setString(to_string(score));
ScoreString.setCharacterSize(60);
ScoreString.setStyle(Text::Regular);
ScoreString.setOutlineThickness(20);
}
Scene::Scene(Scene*S2)
{
// cout << "Cpy" << endl;
//setup des valeurs simples a copier
score = S2->getScore();
spawnPoint = S2->getSpawnPoint();
ScoreString.setString(to_string(score));
ScoreString.setCharacterSize(60);
ScoreString.setStyle(Text::Regular);
ScoreString.setOutlineThickness(20);
//copie des entitées
#pragma region copyEntities
vector <GameObject*> oldgrabbablesETInhalables = S2->getGrabbablesETInhalables();
Bouteille* bo;
Rocher* r;
Block* bl;
for (int i = 0; i < oldgrabbablesETInhalables.size(); i++)
{
bo = dynamic_cast<Bouteille*>(oldgrabbablesETInhalables.at(i));
if (bo) {
Vector2f EntityScale = bo->getSprite()->getScale();
bool inhalab = bo->getInhalable();
Vector2f MyPosition = bo->getSprite()->getPosition();
Texture nonPlayerTex = *bo->getTexture();
IntRect MyEntityTextRect = *bo->getTextureRect();
Bouteille* btllptr = new Bouteille(inhalab, MyPosition, nonPlayerTex, MyEntityTextRect);
btllptr->getSprite()->setScale(EntityScale);
bouteilles.push_back(btllptr);
grabbablesETInhalables.push_back(btllptr);
continue;
}
r = dynamic_cast<Rocher*>(oldgrabbablesETInhalables.at(i));
if (r) {
Vector2f EntityScale = r->getSprite()->getScale();
Vector2f MyPosition = r->getSprite()->getPosition();
Texture nonPlayerTex = *r->getTexture();
IntRect MyEntityTextRect = *r->getTextureRect();
Rocher* rchptr = new Rocher(MyPosition, nonPlayerTex, MyEntityTextRect);
rchptr->getSprite()->setScale(EntityScale);
grabbablesETInhalables.push_back(rchptr);
continue;
}
bl = dynamic_cast<Block*>(oldgrabbablesETInhalables.at(i));
if (bl) {
GameColor mycolor = bl->getColor();
bool vivant = bl->getVivant();
Vector2f EntityScale = bl->getSprite()->getScale();
Vector2f MyPosition = bl->getSprite()->getPosition();
Texture nonPlayerTex = *bl->getTexture();
IntRect MyEntityTextRect = *bl->getTextureRect();
Block* blptr = new Block(vivant, mycolor, MyPosition, nonPlayerTex, MyEntityTextRect);
blptr->getSprite()->setScale(EntityScale);
grabbablesETInhalables.push_back(blptr);
continue;
}
}
vector <Goal*> oldGoals = S2->getGoals();
Goal* g;
for (int i = 0; i < oldGoals.size(); i++)
{
g = dynamic_cast<Goal*>(oldGoals.at(i));
if (g) {
Vector2f EntityScale = g->getSprite()->getScale();
Vector2f MyPosition = g->getSprite()->getPosition();
Texture nonPlayerTex = *g->getTexture();
IntRect MyEntityTextRect = *g->getTextureRect();
Goal* goalptr = new Goal(MyPosition, nonPlayerTex, MyEntityTextRect);
goalptr->getSprite()->setScale(EntityScale);
goals.push_back(goalptr);
}
}
vector <Switch*> oldSwitches = S2->getSwiches();
Switch* s;
for (int i = 0; i < oldSwitches.size(); i++)
{
s = dynamic_cast<Switch*>(oldSwitches.at(i));
if (s) {
Vector2f EntityScale = s->getSprite()->getScale();
Vector2f MyPosition = s->getSprite()->getPosition();
Texture nonPlayerTex = *s->getTexture();
IntRect MyEntityTextRect = *s->getTextureRect();
Switch* swptr = new Switch(MyPosition, nonPlayerTex, MyEntityTextRect);
swptr->getSprite()->setScale(EntityScale);
switches.push_back(swptr);
}
}
vector <spike*> oldSpikes = S2->getSpikes();
spike* sp;
for (int i = 0; i < oldSpikes.size(); i++)
{
sp = dynamic_cast<spike*>(oldSpikes.at(i));
if (sp) {
Vector2f EntityScale = sp->getSprite()->getScale();
Vector2f MyPosition = sp->getSprite()->getPosition();
Texture nonPlayerTex = *sp->getTexture();
IntRect MyEntityTextRect = *sp->getTextureRect();
spike* spptr = new spike(MyPosition, nonPlayerTex, MyEntityTextRect);
spptr->getSprite()->setScale(EntityScale);
spikes.push_back(spptr);
}
}
vector <OneWay*> oldOneWays = S2->getOneWays();
OneWay* ow;
for (int i = 0; i < oldOneWays.size(); i++)
{
ow = dynamic_cast<OneWay*>(oldOneWays.at(i));
if (ow) {
Vector2f EntityScale = ow->getSprite()->getScale();
Vector2f MyPosition = ow->getSprite()->getPosition();
Texture nonPlayerTex = *ow->getTexture();
IntRect MyEntityTextRect = *ow->getTextureRect();
Direction dir = ow->getBlockDirection();
OneWay* owptr = new OneWay(dir, MyPosition, nonPlayerTex, MyEntityTextRect);
owptr->getSprite()->setScale(EntityScale);
oneWays.push_back(owptr);
}
}
vector <Mur*> oldmurs = S2->getMurs();
Mur* m;
for (int i = 0; i < oldmurs.size(); i++)
{
m = dynamic_cast<Mur*>(oldmurs.at(i));
if (m) {
Vector2f EntityScale = m->getSprite()->getScale();
Vector2f MyPosition = m->getSprite()->getPosition();
Texture nonPlayerTex = *m->getTexture();
IntRect MyEntityTextRect = *m->getTextureRect();
Mur* Murptr = new Mur(MyPosition, nonPlayerTex, MyEntityTextRect);
Murptr->getSprite()->setScale(EntityScale);
murs.push_back(Murptr);
}
}
Player* p = &S2->getPlayer();
if (p){
Vector2f PlayerScale = p->getSprite()->getScale();
Texture PlayerTex = *p->getTexture();
IntRect MyPlayerTextRect = *p->getTextureRect();
Vector2f MyPosition = p->getSprite()->getPosition();
Player* pptr = new Player(MyPosition, PlayerTex, MyPlayerTextRect);
pptr->getSprite()->setScale(PlayerScale);
player = pptr;
}
#pragma endregion
}
void Scene::generate(vector<vector<enum ElementTypes>>myMatrice)
{
#pragma region GenerationSetup
Texture nonPlayerTex;
Texture PlayerTex;
if (!nonPlayerTex.loadFromFile("img/NonPlayer.png"))
{
cout << "failToLoad nonPlayerTex" << endl;
}
if (!PlayerTex.loadFromFile("img/Player.png"))
{
cout << "failToLoad PlayerTex" << endl;
}
IntRect MyEntityTextRect, MyPlayerTextRect;
//EntityScale = ratio de proportion des entitées;
//ArenaScale = Dimension de la case occupée par un élément
Vector2f EntityScale(20,20), PlayerScale(9, 9),ArenaScale(160,160), MyPosition;
#pragma endregion
/*
enum ElementTypes {VIDE, MUR, ONEWAY, ONEWAY_HAUT, ONEWAY_BAS, ONEWAY_GAUCHE, ONEWAY_DROITE,
PIQUE, SWITCH, GOAL, ROCHER, BOUTEILLE, BOUTEILLE_VIVANTE, BOUTEILLE_COULEUR1, BOUTEILLE_COULEUR2,
BOUTEILLE_COULEUR3, BLOC, BLOC_VIVANT, BLOC_COULEUR1, BLOC_COULEUR2, BLOC_COULEUR3, ANIMAL,
ANIMAL_COULEUR1, ANIMAL_COULEUR2, ANIMAL_COULEUR3, PLAYER, SPAWN };
*/
for (int y = 0; y < myMatrice.size(); y++) {
vector <enum ElementTypes> myLine = myMatrice.at(y);
for (int x = 0; x < myLine.size(); x++) {
if (myLine.at(x) != ElementTypes::VIDE) {
MyEntityTextRect.width = MyEntityTextRect.height = 8;
MyPosition = ArenaScale;
MyPosition.x *= x;
MyPosition.y *= y;
switch (myLine.at(x)) {
case ElementTypes::MUR:
try {
//cout << endl <<"wall at " << x << "x - " << y << "y : ";
// CHOIX DE TEXTURE
if (y-1 >= 0 && myMatrice[y-1][x] != ElementTypes::MUR){
if (((x + 1) < myLine.size()) && myMatrice[y][x + 1] != ElementTypes::MUR) {
if ((x - 1 >= 0) && (myMatrice[y][x - 1] != ElementTypes::MUR)) {
//cout << "Haut";
MyEntityTextRect.left = MyEntityTextRect.width * 0;
MyEntityTextRect.top = MyEntityTextRect.height * 3;
} else {
//cout << "Haut Droite";
MyEntityTextRect.left = MyEntityTextRect.width * 3;
MyEntityTextRect.top = MyEntityTextRect.height * 3;
}} else {
if (x - 1 >= 0 && myMatrice[y][x - 1] != ElementTypes::MUR) {
//cout << "Haut Gauche";
MyEntityTextRect.left = MyEntityTextRect.width * 1;
MyEntityTextRect.top = MyEntityTextRect.height * 3;
} else {
//cout << "Haut";
MyEntityTextRect.left = MyEntityTextRect.width * 0;
MyEntityTextRect.top = MyEntityTextRect.height * 3;
}}}
else if (y + 1 >= myMatrice.size() || myMatrice[y + 1][x] == ElementTypes::MUR){
//cout << "interrieur";
MyEntityTextRect.left = MyEntityTextRect.width * 2;
MyEntityTextRect.top = MyEntityTextRect.height * 3;
}
else {
if ((x + 1 < myLine.size()) && myMatrice[y][x + 1] != ElementTypes::MUR) {
if ((x - 1 >= 0) && myMatrice[y][x - 1] != ElementTypes::MUR) {
//cout << "Bas";
MyEntityTextRect.left = MyEntityTextRect.width * 0;
MyEntityTextRect.top = MyEntityTextRect.height * 4;
MyEntityTextRect.height *= -1;
} else {
//cout << "Bas Droite";
MyEntityTextRect.left = MyEntityTextRect.width * 3;
MyEntityTextRect.top = MyEntityTextRect.height * 4;
MyEntityTextRect.height *= -1;
}} else {
if (x - 1 >= 0 && myMatrice[y][x - 1] != ElementTypes::MUR) {
//cout << "Bas Gauche";
MyEntityTextRect.left = MyEntityTextRect.width * 1;
MyEntityTextRect.top = MyEntityTextRect.height * 4;
MyEntityTextRect.height *= -1;
}
else {
//cout << "Bas";
MyEntityTextRect.left = MyEntityTextRect.width * 0;
MyEntityTextRect.top = MyEntityTextRect.height * 4;
MyEntityTextRect.height *= -1;
}}}
//cout << endl;
//cout << "Rectangle : x:" << MyEntityTextRect.left << " y:" << MyEntityTextRect.top << " width:" << MyEntityTextRect.width << " height:" << MyEntityTextRect.height << endl;
//On applique les coordonnées
Mur* Murptr = new Mur(MyPosition, nonPlayerTex, MyEntityTextRect);
Murptr->getSprite()->setScale(EntityScale);
murs.push_back(Murptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::ONEWAY:
try {
//cout << "OneWay (defaut = Haut) at " << x << "x - " << y << "y : " << endl;
MyEntityTextRect.top = 2 * MyEntityTextRect.height;
MyEntityTextRect.left = 0 * MyEntityTextRect.width;
/*
Le sens Bloqué est l'opposé du sens affiché
*/
OneWay* owptr = new OneWay(Direction::BAS, MyPosition, nonPlayerTex, MyEntityTextRect);
owptr->getSprite()->setScale(EntityScale);
oneWays.push_back(owptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::ONEWAY_HAUT:
try {
//cout << "OneWay Haut at " << x << "x - " << y << "y : "<< endl;
MyEntityTextRect.top = 2 * MyEntityTextRect.height;
MyEntityTextRect.left = 0 * MyEntityTextRect.width;
/*
Le sens Bloqué est l'opposé du sens affiché
*/
OneWay* owptr = new OneWay(Direction::BAS, MyPosition, nonPlayerTex, MyEntityTextRect);
owptr->getSprite()->setScale(EntityScale);
oneWays.push_back(owptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::ONEWAY_BAS:
try {
//cout << "OneWay Bas at " << x << "x - " << y << "y : "<< endl;
MyEntityTextRect.top = 3 * MyEntityTextRect.height;
MyEntityTextRect.left = 0 * MyEntityTextRect.width;
MyEntityTextRect.height = -MyEntityTextRect.height;
/*
Le sens Bloqué est l'opposé du sens affiché
*/
OneWay* owptr = new OneWay(Direction::HAUT, MyPosition, nonPlayerTex, MyEntityTextRect);
owptr->getSprite()->setScale(EntityScale);
oneWays.push_back(owptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::ONEWAY_GAUCHE:
try {
//cout << "OneWay Gauche at " << x << "x - " << y << "y : " << endl;
MyEntityTextRect.top = 2 * MyEntityTextRect.height;
MyEntityTextRect.left = 2 * MyEntityTextRect.width;
MyEntityTextRect.width = -MyEntityTextRect.width;
/*
Le sens Bloqué est l'opposé du sens affiché
*/
OneWay* owptr = new OneWay(Direction::DROITE, MyPosition, nonPlayerTex, MyEntityTextRect);
owptr->getSprite()->setScale(EntityScale);
oneWays.push_back(owptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::ONEWAY_DROITE:
try {
//cout << "OneWay Droite at " << x << "x - " << y << "y : " << endl;
MyEntityTextRect.top = 2 * MyEntityTextRect.height;
MyEntityTextRect.left = 1 * MyEntityTextRect.width;
/*
Le sens Bloqué est l'opposé du sens affiché
*/
OneWay* owptr = new OneWay(Direction::GAUCHE, MyPosition, nonPlayerTex, MyEntityTextRect);
owptr->getSprite()->setScale(EntityScale);
oneWays.push_back(owptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::PIQUE:
try {
//cout << "spike at " << x << "x - " << y << "y : " << endl;
MyEntityTextRect.top = 2 * MyEntityTextRect.height;
MyEntityTextRect.left = 2 * MyEntityTextRect.width;
/*
Le sens Bloqué est l'opposé du sens affiché
*/
spike* spptr = new spike(MyPosition, nonPlayerTex, MyEntityTextRect);
spptr->getSprite()->setScale(EntityScale);
spikes.push_back(spptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::SPAWN:
try {
/**
cout << endl << "SpawnPoint at " << x << "x - " << y << "y : ";
cout << myLine.size() << " " << myMatrice.size() << endl;
if ((x + 1 < myLine.size()) && (myLine.at(x + 1) == ElementTypes::VIDE) && (y + 1 < myMatrice.size()) && (myMatrice.at(x).at(y + 1) == ElementTypes::VIDE) && (myMatrice.at(x + 1).at(y + 1) == ElementTypes::VIDE)) {
cout << "VALIDE" << endl;
}
else {
cout << "INVALIDE" << endl;
}
/**/
MyPlayerTextRect.width = MyPlayerTextRect.height = 32;
MyPlayerTextRect.left = MyPlayerTextRect.width * 0;
MyPlayerTextRect.top = MyPlayerTextRect.height * 0;
//cout << "Rectangle : x:" << MyPlayerTextRect.left << " y:" << MyPlayerTextRect.top << " width:" << MyPlayerTextRect.width << " height:" << MyPlayerTextRect.height << endl;
spawnPoint.x = MyPosition.x;
spawnPoint.y = MyPosition.y;
/**
player.setTexture(PlayerTex);
player.setTextureRect(MyPlayerTextRect);
player.getSprite()->setPosition(spawnPoint);/**/
Player* pptr = new Player(spawnPoint, PlayerTex, MyPlayerTextRect);
pptr->getSprite()->setScale(PlayerScale);
player = pptr;
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::BOUTEILLE:
try {
//cout << endl << "BOUTEILLE at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 2 * MyEntityTextRect.height;
MyEntityTextRect.left = 4 * MyEntityTextRect.width;
Bouteille* btllptr = new Bouteille(true, MyPosition, nonPlayerTex, MyEntityTextRect);
btllptr->getSprite()->setScale(EntityScale);
bouteilles.push_back(btllptr);
grabbablesETInhalables.push_back(btllptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::BOUTEILLE_VIVANTE:
try {
//cout << endl << "BOUTEILLE_VIVANTE at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 3 * MyEntityTextRect.height;
MyEntityTextRect.left = 4 * MyEntityTextRect.width;
Bouteille* btllptr = new Bouteille(false, MyPosition, nonPlayerTex, MyEntityTextRect);
btllptr->getSprite()->setScale(EntityScale);
bouteilles.push_back(btllptr);
grabbablesETInhalables.push_back(btllptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::BOUTEILLE_COULEUR1:
try {
//cout << endl << "BOUTEILLE_COULEUR1 at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 2 * MyEntityTextRect.height;
MyEntityTextRect.left = 4 * MyEntityTextRect.width;
Bouteille* btllptr = new Bouteille(true, ROUGE, MyPosition, nonPlayerTex, MyEntityTextRect);
btllptr->getSprite()->setScale(EntityScale);
bouteilles.push_back(btllptr);
grabbablesETInhalables.push_back(btllptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::BOUTEILLE_COULEUR2:
try {
//cout << endl << "BOUTEILLE_COULEUR2 at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 2 * MyEntityTextRect.height;
MyEntityTextRect.left = 4 * MyEntityTextRect.width;
Bouteille* btllptr = new Bouteille(true, BLEU, MyPosition, nonPlayerTex, MyEntityTextRect);
btllptr->getSprite()->setScale(EntityScale);
bouteilles.push_back(btllptr);
grabbablesETInhalables.push_back(btllptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::BOUTEILLE_COULEUR3:
try {
//cout << endl << "BOUTEILLE_COULEUR3 at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 2 * MyEntityTextRect.height;
MyEntityTextRect.left = 4 * MyEntityTextRect.width;
Bouteille* btllptr = new Bouteille(true, JAUNE, MyPosition, nonPlayerTex, MyEntityTextRect);
btllptr->getSprite()->setScale(EntityScale);
bouteilles.push_back(btllptr);
grabbablesETInhalables.push_back(btllptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::SWITCH:
try {
//cout << endl << "SWITCH at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 1 * MyEntityTextRect.height;
MyEntityTextRect.left = 0 * MyEntityTextRect.width;
Switch* swptr = new Switch(MyPosition, nonPlayerTex, MyEntityTextRect);
swptr->getSprite()->setScale(EntityScale);
switches.push_back(swptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::ROCHER:
try {
//cout << endl << "ROCHER at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 2 * MyEntityTextRect.height;
MyEntityTextRect.left = 3 * MyEntityTextRect.width;
Rocher* rchptr = new Rocher(MyPosition, nonPlayerTex, MyEntityTextRect);
rchptr->getSprite()->setScale(EntityScale);
grabbablesETInhalables.push_back(rchptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::GOAL:
try {
//cout << endl << "GOAL at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 1 * MyEntityTextRect.height;
MyEntityTextRect.left = 4 * MyEntityTextRect.width;
Goal* goalptr = new Goal(MyPosition, nonPlayerTex, MyEntityTextRect);
goalptr->getSprite()->setScale(EntityScale);
goals.push_back(goalptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::BLOC:
try {
// cout << endl << "BLOC at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 0 * MyEntityTextRect.height;
MyEntityTextRect.left = 2 * MyEntityTextRect.width;
Block* blptr = new Block(NOCOLOR,MyPosition, nonPlayerTex, MyEntityTextRect);
blptr->getSprite()->setScale(EntityScale);
grabbablesETInhalables.push_back(blptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::BLOC_VIVANT:
try {
// cout << endl << "BLOC_VIVANT at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 0 * MyEntityTextRect.height;
MyEntityTextRect.left = 3 * MyEntityTextRect.width;
Block* blptr = new Block(true, NOCOLOR, MyPosition, nonPlayerTex, MyEntityTextRect);
blptr->getSprite()->setScale(EntityScale);
grabbablesETInhalables.push_back(blptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::BLOC_COULEUR1:
try {
// cout << endl << "BLOC_COULEUR1 at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 0 * MyEntityTextRect.height;
MyEntityTextRect.left = 2 * MyEntityTextRect.width;
Block* blptr = new Block(ROUGE, MyPosition, nonPlayerTex, MyEntityTextRect);
blptr->getSprite()->setScale(EntityScale);
grabbablesETInhalables.push_back(blptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::BLOC_COULEUR2:
try {
// cout << endl << "BLOC_COULEUR2 at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 0 * MyEntityTextRect.height;
MyEntityTextRect.left = 2 * MyEntityTextRect.width;
Block* blptr = new Block(BLEU, MyPosition, nonPlayerTex, MyEntityTextRect);
blptr->getSprite()->setScale(EntityScale);
grabbablesETInhalables.push_back(blptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
case ElementTypes::BLOC_COULEUR3:
try {
// cout << endl << "BLOC_COULEUR3 at " << x << "x - " << y << "y : ";
MyEntityTextRect.top = 0 * MyEntityTextRect.height;
MyEntityTextRect.left = 2 * MyEntityTextRect.width;
Block* blptr = new Block(JAUNE, MyPosition, nonPlayerTex, MyEntityTextRect);
blptr->getSprite()->setScale(EntityScale);
grabbablesETInhalables.push_back(blptr);
}
catch (exception & e) { cout << "Exception: " << e.what(); }
break;
default:
cout << "l'index de la case " << x << "x "<< y << "y n'est pas connu" << endl;
}
}
}
}
}
void Scene::draw(RenderWindow&e)
{
View v = e.getView();
FloatRect centerBox = player->getSprite()->getGlobalBounds();
Vector2f centre;
centre.y = centerBox.top + (centerBox.height / 2);
centre.x = centerBox.left + (centerBox.width / 2);
v.setCenter(centre);
e.setView(v);
centre.x -= 660;
centre.y -= 550;
e.clear();
for (int i = 0; i < murs.size(); i++)
{
murs[i]->drawMe(e);
}
for (int i = 0; i < oneWays.size(); i++)
{
oneWays[i]->drawMe(e);
}
for (int i = 0; i < spikes.size(); i++)
{
spikes[i]->drawMe(e);
}
for (int i = 0; i < switches.size(); i++)
{
switches[i]->drawMe(e);
}
for (int i = 0; i < grabbablesETInhalables.size(); i++)
{
grabbablesETInhalables[i]->drawMe(e);
}
for (int i = 0; i < goals.size(); i++)
{
goals[i]->drawMe(e);
}
player->drawMe(e);
ScoreString.setPosition(centre);
e.draw(ScoreString);
e.display();
}
GameObject* Scene::testCollide(GameObject*e , Direction D)
{
Direction OpposeD = Direction::HAUT;
switch (D)
{
case Direction::HAUT:
OpposeD = Direction::BAS;
break;
case Direction::BAS:
OpposeD = Direction::HAUT;
break;
case Direction::GAUCHE:
OpposeD = Direction::DROITE;
break;
case Direction::DROITE:
OpposeD = Direction::GAUCHE;
break;
default:
break;
}
FloatRect collisionBox,ActualBox;
bool TraverseBlock, TraverseMur, MarcheSurBlock, hauteur;
TraverseBlock = TraverseMur = MarcheSurBlock = hauteur = false;
Player* PlayerPointer;
PlayerPointer = dynamic_cast<Player*>(e);
MobileEntity* MobileEntityptr;
MobileEntityptr = dynamic_cast<MobileEntity*>(e);
MobileGameplayElement* MobileGameplayElementPointer = dynamic_cast<MobileGameplayElement*>(e);
if (PlayerPointer) {
collisionBox = PlayerPointer->getUpdatedFantome(D).getGlobalBounds();
ActualBox = PlayerPointer->getSprite()->getGlobalBounds();
TraverseBlock = PlayerPointer->getTraverseBlock();
TraverseMur = PlayerPointer->getTraverseMur();
MarcheSurBlock = PlayerPointer->getMarcheSurBlock();
hauteur = PlayerPointer->getHauteur();
}
else if (MobileEntityptr) {
collisionBox = MobileEntityptr->getUpdatedFantome(D).getGlobalBounds();
ActualBox = MobileEntityptr->getSprite()->getGlobalBounds();
TraverseBlock = MobileEntityptr->getTraverseBlock();
TraverseMur = MobileEntityptr->getTraverseMur();
MarcheSurBlock = MobileEntityptr->getMarcheSurBlock();
hauteur = MobileEntityptr->getHauteur();
}
else if (MobileGameplayElementPointer) {
collisionBox = MobileGameplayElementPointer->getUpdatedFantome(D).getGlobalBounds();
ActualBox = MobileGameplayElementPointer->getSprite()->getGlobalBounds();
TraverseBlock = MobileGameplayElementPointer->getTraverseBlock();
TraverseMur = MobileGameplayElementPointer->getTraverseMur();
MarcheSurBlock = MobileGameplayElementPointer->getMarcheSurBlock();
hauteur = MobileGameplayElementPointer->getHauteur();
}
// A CODER : ROCHER, BLOC, BLOC_VIVANT, ANIMAL
else {
cout << "Mauvais collisionneur " << endl;
}
//Ajustement des zones de collision
collisionBox = getInnerBounds(D, collisionBox);
ActualBox = getInnerBounds(D, ActualBox);
#pragma region entity_collision
if (!TraverseMur) {
Mur* MurPtr;
for (int i = 0; i < murs.size(); i++) {
MurPtr = murs.at(i);
if (collisionBox.intersects(getInnerBounds(OpposeD,MurPtr->getSprite()->getGlobalBounds()))) {
//cout << "Colliding\n";
return MurPtr;
}
}
}
OneWay* oneWayPtr;
for (int i = 0; i < oneWays.size(); i++) {
oneWayPtr = oneWays.at(i);
if (!ActualBox.intersects( oneWayPtr->getSprite()->getGlobalBounds()) && D == oneWayPtr->getBlockDirection() && collisionBox.intersects(getInnerBounds(OpposeD, oneWayPtr->getSprite()->getGlobalBounds()))) {
return oneWayPtr;
}
}
spike* spikePtr;
for (int i = 0; i < spikes.size(); i++) {
spikePtr = spikes.at(i);
if (ActualBox.intersects(spikePtr->getSprite()->getGlobalBounds())) {
if (PlayerPointer)// Si c'est un joueur et qu'il touche actuellement un spike, le jeu est fini
{
score = 0;
}
else
return spikePtr;
}
}
Switch* swtchptr;
for (int i = 0; i < switches.size(); i++) {
swtchptr = switches.at(i);
if (collisionBox.intersects(swtchptr->getSprite()->getGlobalBounds())) {
return swtchptr;
}
}
MobileGameplayElement* mgeptr;
FocusableElement* fEptr;
Block* blptr;
for (int i = 0; i < grabbablesETInhalables.size(); i++) {
mgeptr = dynamic_cast<MobileGameplayElement*>(grabbablesETInhalables.at(i));
if (mgeptr) {//cas des éléments héritant de MobileGameplayElement
fEptr = mgeptr; //On teste leur heritage en focusable Element pour savoir s'ils sont traversable
if (!fEptr->getTraversable()) {
//Si on cherche à tester les collisions d'un MobileGameplayElement
if (MobileGameplayElementPointer) {
//si l'élément collider est identique à l'element testé
if (getInnerBounds(D, mgeptr->getSprite()->getGlobalBounds()) == ActualBox) {
//on passe à l'élément suivant
continue;
}
}
//Dans le cas d'un Block
blptr = dynamic_cast<Block*>(mgeptr);
if (blptr) {
//Si on ne traverse pas les blocks
//Ou que l'on marche sur les blocks et que l'on test une collision vers le bas
if (!TraverseBlock || (D == Direction::BAS && MarcheSurBlock)) {
if (collisionBox.intersects(getInnerBounds(OpposeD, blptr->getSprite()->getGlobalBounds()))) {
return blptr;
}
}
continue;
}
else if (collisionBox.intersects(getInnerBounds(OpposeD, mgeptr->getSprite()->getGlobalBounds()))) {
return mgeptr;
}
}
}
else { // cas opposé (Bouteilles)
fEptr = dynamic_cast<FocusableElement*>(grabbablesETInhalables.at(i));
if (!fEptr->getTraversable()) {
if (collisionBox.intersects(getInnerBounds(OpposeD, fEptr->getSprite()->getGlobalBounds()))) {
return fEptr;
}
}
}
//cas de Bouteille
}
Goal* goalptr;
for (int i = 0; i < goals.size(); i++)
{
//si on entre en collision avec un objectif, on le supprime du tableau de goals
goalptr = goals.at(i);
if (ActualBox.intersects(goalptr->getSprite()->getGlobalBounds())) {
goals.erase(goals.begin() + i);
goals.shrink_to_fit();
}
}
/*
case PIQUE:
break;
case SWITCH:
break;
case GOAL:
break;
case BOUTEILLE:
break;
case BOUTEILLE_VIVANTE:
break;
case BLOC:
break;
case BLOC_VIVANT:
break;
case ANIMAL:
break;/*
default:
break;
}
*/
// si l'element pour lequel on teste les collisions n'est pas un joueur, alors on doit tester cette option
if (PlayerPointer == NULL && collisionBox.intersects(getInnerBounds(OpposeD, player->getSprite()->getGlobalBounds()))) {
//cout << "Colliding\n";
return player;
}
//cout << "Not Colliding\n";
#pragma endregion
return NULL;
}
GameObject* Scene::testEncounter(GameObject*e, Direction D, int margin)
{
Direction OpposeD = Direction::HAUT;
switch (D)
{
case Direction::HAUT:
OpposeD = Direction::BAS;
break;
case Direction::BAS:
OpposeD = Direction::HAUT;
break;
case Direction::GAUCHE:
OpposeD = Direction::DROITE;
break;
case Direction::DROITE:
OpposeD = Direction::GAUCHE;
break;
default:
break;
}
FloatRect collisionBox, ActualBox;
bool TraverseBlock, TraverseMur, MarcheSurBlock, hauteur;
TraverseBlock = TraverseMur = MarcheSurBlock = hauteur = false;
Player* PlayerPointer;
PlayerPointer = dynamic_cast<Player*>(e);
MobileEntity* MobileEntityptr;
MobileEntityptr = dynamic_cast<MobileEntity*>(e);
MobileGameplayElement* MobileGameplayElementPointer = dynamic_cast<MobileGameplayElement*>(e);
if (PlayerPointer) {
collisionBox = PlayerPointer->getUpdatedFantome(D).getGlobalBounds();
ActualBox = PlayerPointer->getSprite()->getGlobalBounds();
TraverseBlock = PlayerPointer->getTraverseBlock();
TraverseMur = PlayerPointer->getTraverseMur();
MarcheSurBlock = PlayerPointer->getMarcheSurBlock();
hauteur = PlayerPointer->getHauteur();
}
else if (MobileEntityptr) {
collisionBox = MobileEntityptr->getUpdatedFantome(D).getGlobalBounds();
ActualBox = MobileEntityptr->getSprite()->getGlobalBounds();
TraverseBlock = MobileEntityptr->getTraverseBlock();
TraverseMur = MobileEntityptr->getTraverseMur();
MarcheSurBlock = MobileEntityptr->getMarcheSurBlock();
hauteur = MobileEntityptr->getHauteur();
}
else if (MobileGameplayElementPointer) {
collisionBox = MobileGameplayElementPointer->getUpdatedFantome(D).getGlobalBounds();
ActualBox = MobileGameplayElementPointer->getSprite()->getGlobalBounds();
TraverseBlock = MobileGameplayElementPointer->getTraverseBlock();
TraverseMur = MobileGameplayElementPointer->getTraverseMur();
MarcheSurBlock = MobileGameplayElementPointer->getMarcheSurBlock();
hauteur = MobileGameplayElementPointer->getHauteur();
}
// A CODER : ROCHER, BLOC, BLOC_VIVANT, ANIMAL
else {
cout << "Mauvais collisionneur " << endl;
}
//Ajustement des zones de collision
collisionBox = getOuterBounds(D, collisionBox, margin);
ActualBox = getOuterBounds(D, ActualBox, margin);
#pragma region boundery_collision
/* TODO */
#pragma endregion
#pragma region entity_collision
if (!TraverseMur) {
Mur* MurPtr;
for (int i = 0; i < murs.size(); i++) {
MurPtr = murs.at(i);
if (collisionBox.intersects(getInnerBounds(OpposeD, MurPtr->getSprite()->getGlobalBounds()))) {
//cout << "Colliding\n";
return MurPtr;
}
}
}
OneWay* oneWayPtr;
for (int i = 0; i < oneWays.size(); i++) {
oneWayPtr = oneWays.at(i);
if (!ActualBox.intersects(oneWayPtr->getSprite()->getGlobalBounds()) && D == oneWayPtr->getBlockDirection() && collisionBox.intersects(getInnerBounds(OpposeD, oneWayPtr->getSprite()->getGlobalBounds()))) {
return oneWayPtr;
}
}
spike* spikePtr;
for (int i = 0; i < spikes.size(); i++) {
spikePtr = spikes.at(i);
if (ActualBox.intersects(spikePtr->getSprite()->getGlobalBounds())) {
if (PlayerPointer)// Si c'est un joueur et qu'il touche actuellement un spike, le jeu est fini
score = 0;
else
return spikePtr;
}
}
Switch* swtchptr;
for (int i = 0; i < switches.size(); i++) {
swtchptr = switches.at(i);
if (collisionBox.intersects(swtchptr->getSprite()->getGlobalBounds())) {
return swtchptr;
}
}
MobileGameplayElement* mgeptr;
FocusableElement* fEptr;
Block* blptr;
for (int i = 0; i < grabbablesETInhalables.size(); i++) {
mgeptr = dynamic_cast<MobileGameplayElement*>(grabbablesETInhalables.at(i));
if (mgeptr) {//cas des éléments héritant de MobileGameplayElement
fEptr = mgeptr; //On teste leur heritage en focusable Element pour savoir s'ils sont traversable
if (!fEptr->getTraversable()) {
//Si on cherche à tester les collisions d'un MobileGameplayElement
if (MobileGameplayElementPointer) {
//si l'élément collider est identique à l'element testé
if (getInnerBounds(D, mgeptr->getSprite()->getGlobalBounds()) == ActualBox) {
//on passe à l'élément suivant
continue;
}
}
//Dans le cas d'un Block
blptr = dynamic_cast<Block*>(mgeptr);
if (blptr) {
//Si on ne traverse pas les blocks
//Ou que l'on marche sur les blocks et que l'on test une collision vers le bas
if (!TraverseBlock || (D == Direction::BAS && MarcheSurBlock)) {
if (collisionBox.intersects(getInnerBounds(OpposeD, blptr->getSprite()->getGlobalBounds()))) {
return blptr;
}
}
continue;
}
else if (collisionBox.intersects(getInnerBounds(OpposeD, mgeptr->getSprite()->getGlobalBounds()))) {
return mgeptr;
}
}
}
else { // cas opposé (Bouteilles)
fEptr = dynamic_cast<FocusableElement*>(grabbablesETInhalables.at(i));
if (!fEptr->getTraversable()) {
if (collisionBox.intersects(getInnerBounds(OpposeD, fEptr->getSprite()->getGlobalBounds()))) {
return fEptr;
}
}
}
//cas de Bouteille
}
Goal* goalptr;
for (int i = 0; i < goals.size(); i++)
{
//si on entre en collision avec un objectif, on le supprime du tableau de goals
goalptr = goals.at(i);
if (ActualBox.intersects(goalptr->getSprite()->getGlobalBounds())) {
goals.erase(goals.begin() + i);
goals.shrink_to_fit();
}
}
/*
case PIQUE:
break;
case SWITCH:
break;
case GOAL:
break;
case BOUTEILLE:
break;
case BOUTEILLE_VIVANTE:
break;
case BLOC:
break;
case BLOC_VIVANT:
break;
case ANIMAL:
break;/*
default:
break;
}
*/
// si l'element pour lequel on teste les collisions n'est pas un joueur, alors on doit tester cette option
if (PlayerPointer == NULL && collisionBox.intersects(getInnerBounds(OpposeD, player->getSprite()->getGlobalBounds()))) {
//cout << "Colliding\n";
return player;
}
//cout << "Not Colliding\n";
#pragma endregion
return NULL;
}
int Scene::update(RenderWindow& GM, vector <Event>EventPool)
{
/*
enum sceneOutput {RienASignaler = -1,
QuickSave = -2,
ReloadPrevious = -3,
Exit = -4,
Restart = -5
};
i on retourne 0 ou Plus, alorS on retourne le score
*/
int retour = sceneOutput::RienASignaler;
Event event;
// cout << EventPool.size() << endl;
while(EventPool.size() != 0)
{
event = EventPool.back();
switch (event.type)
{
case Event::KeyPressed:
/* Format d'inputs
Left = arrow left
right = arrow right
discard = arraw down
jump = arrow up
inhale/exhale = crtl right
Select = s ou num1
Lock = L ou num4
cancel = N ou num3
confirm = O ou num6
//anciens paramêtres, ceux la sont présents dans le menu accessible via Echape
reload = R ou num5
Quicksave = Q ou num2
Exit = E ou Echape
Restart = T ou num8
*/
if (event.key.code == Keyboard::Down) {
/*Si on appuis sur la fleche du bas,
on doit savoir si 'lon marche sur un
switch ou non.
Etape 1 : convertir les switchs en gameObject
afin d'etre acceptés en paramêtre de walkon
*/
vector <GameObject*> goptr;
for (int i = 0; i < switches.size(); i++)
{
goptr.push_back(switches.at(i));
}
/*
Etape 2 : Si l'on est bien sur un switch, alors on l'active
sinon on vide notre couleur
*/
if (walkOn(player, goptr)) {
// cout << "switchColor" << endl;
switches.at(0)->interact(this);
}
else {
// cout << "discard" << endl;
if (player->getBringColor() != NOCOLOR) {
player->setBringColor(NOCOLOR);
}
}
}
else if (event.key.code == Keyboard::RControl) {
// cout << "Inhale/Hexale" << endl;
if (player->getBringSomething()) {
// cout << "hexaling" << endl;
if(player->getBringColor() == NOCOLOR){
// cout << "entity" << endl;
grabbablesETInhalables.push_back(player->getBringElement());
player->setBringElement(NULL);
/*
Dans le cas d'un depot d'objet dynamique,
on le met a jour pour qu'il puisse reprendre conscience de sa position
*/
MobileEntity* mEptr = dynamic_cast<MobileEntity*>(grabbablesETInhalables.at(
grabbablesETInhalables.size() - 1
));
if (mEptr)
mEptr->update(this);
}
else {
// cout << "color" << endl;
FloatRect interactionBox = player->getInteractionBox();
for (int i = 0; i < grabbablesETInhalables.size() && player->getBringSomething(); i++)
{
if (interactionBox.intersects(grabbablesETInhalables.at(i)->getSprite()->getGlobalBounds())) {
MobileGameplayElement* mpptr = dynamic_cast <MobileGameplayElement*>(grabbablesETInhalables.at(i));
if (mpptr && mpptr->getColor() == NOCOLOR && mpptr->getPaintable()) {
// cout << "Transfert possible "<< endl;
mpptr->setColor(player->getBringColor());
player->setBringColor(NOCOLOR);
}
else {
// cout << "Transfert impossible " << endl;
}
}
}
}
}
else {
// cout << "Inhaling" << endl;
FloatRect interactionBox = player->getInteractionBox();
for (int i = 0; i < grabbablesETInhalables.size() && !player->getBringSomething(); i++)
{
if (interactionBox.intersects(grabbablesETInhalables.at(i)->getSprite()->getGlobalBounds())) {
// cout << "found something to inhale" << endl;
Bouteille* btptr = dynamic_cast <Bouteille* >(grabbablesETInhalables.at(i));
if (btptr) {
if (btptr->getInhalable()) {
// cout << "Pick Color" << endl;
player->setBringColor(btptr->getColor());
}
else {
// cout << "bouteille vivante" << endl;
}
}
else {
Block * blptr = dynamic_cast <Block*>(grabbablesETInhalables.at(i));
if (blptr && blptr->getVivant()) {
// cout << "block vivant" << endl;
}
else {
MobileGameplayElement* mpptr = dynamic_cast <MobileGameplayElement*>(grabbablesETInhalables.at(i));
if (mpptr->getColor() != NOCOLOR) {
// cout << "Pick Entity's color" << endl;
player->setBringColor(mpptr->getColor());
mpptr->setColor(NOCOLOR);
}
else {
// cout << "Pick Entity" << endl;
player->setBringElement(mpptr);
grabbablesETInhalables.erase(grabbablesETInhalables.begin() + i);
grabbablesETInhalables.shrink_to_fit();
}
}
}
}
}
}
}
else if (event.key.code == Keyboard::S || event.key.code == Keyboard::Numpad1) {
cout << "Select" << endl;
//pas encore implémenté
}
else if (event.key.code == Keyboard::L || event.key.code == Keyboard::Numpad4) {
cout << "Lock" << endl;
//pas encore implémenté
}
else if (event.key.code == Keyboard::N || event.key.code == Keyboard::Numpad2) {
cout << "cancel" << endl;
//pas encore implémenté
}
else if (event.key.code == Keyboard::O || event.key.code == Keyboard::Numpad5) {
cout << "confirm" << endl;
//pas encore implémenté
}
break;
default:
break;
}
EventPool.pop_back();
EventPool.shrink_to_fit();
}
player->update(this);
//Mise a jour de tout les éléments dynamiques
for (int i = 0; i < grabbablesETInhalables.size(); i++)
{
//si ils héritent de MobileGameplayElement
MobileGameplayElement* mgeptr = dynamic_cast<MobileGameplayElement*>(grabbablesETInhalables.at(i));
if (mgeptr) {
mgeptr->update(this);
continue;
}
}
if (score <= 0)//si on meurt
{
retour = sceneOutput::Restart;
}
if (goals.size() == 0)//si on gagne
retour = score;
ScoreString.setString(to_string(score));
return retour;
}
int Scene::getScore()
{
return score;
}
void Scene::setScore(int s)
{
score = s;
}
Text Scene::getScoreString()
{
return ScoreString;
}
void Scene::setScoreString(Text t)
{
ScoreString = t;
}
vector<GameObject*> Scene::getGrabbablesETInhalables()
{
return grabbablesETInhalables;
}
void Scene::setGrabbablesETInhalables(vector<GameObject*>g)
{
grabbablesETInhalables = g;
}
Player Scene::getPlayer()
{
return *player;
}
void Scene::setPlayer(Player p)
{
player = &p;
}
Vector2f Scene::getSpawnPoint()
{
return spawnPoint;
}
void Scene::setSpawnPoint(Vector2f s)
{
spawnPoint = s;
}
vector<Bouteille*> Scene::getBouteilles()
{
return bouteilles;
}
void Scene::setBouteilles(vector<Bouteille*> b)
{
bouteilles = b;
}
vector<Mur*> Scene::getMurs()
{
return murs;
}
void Scene::setMurs(vector<Mur*>m)
{
murs = m;
}
vector<OneWay*> Scene::getOneWays()
{
return oneWays;
}
void Scene::setOneWays(vector<OneWay*>w)
{
oneWays = w;
}
vector<spike*> Scene::getSpikes()
{
return spikes;
}
void Scene::setSpikes(vector<spike*>s)
{
spikes = s;
}
vector<Switch*> Scene::getSwiches()
{
return switches;
}
void Scene::setSwiches(vector<Switch*>s)
{
switches = s;
}
vector<Goal*> Scene::getGoals()
{
return goals;
}
void Scene::setGoals(vector<Goal*>g)
{
goals = g;
}
bool Scene::walkOn(GameObject* mvr, vector<GameObject*> obstcl)
{
FloatRect box = mvr->getSprite()->getGlobalBounds();
box.top += 10;// on descend la boite pour detecter une collision avec les objets
for (int i = 0; i < obstcl.size(); i++)
{
//cout << "test walkingOn " << i << endl;
if (box.intersects(obstcl.at(i)->getSprite()->getGlobalBounds()))
return true;
}
return false;
}
<file_sep>#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include "Map.h"
#include "MainMenu.h"
using namespace std;
using namespace sf;
class GameMaster:public RenderWindow //Classe du jeu
{
protected:
vector <Map> maps; //Stock de cartes
int selectedMapIndex; //index de la carte en cours
Font *font; //police stockée globalement
double framerate; //fréquence de jeu
Clock MainClock; //Horloge pour définir la fréquence de jeu
public:
/* CONSTRUCTEURS */
GameMaster();
/* FONCTIONS MEMBRES DE LA CLASSE */
void run();
/* GETER SETER */
vector <Map> getMaps();
void setMaps(vector <Map>);
void addMap(Map);
void setSelectedMapIndex(int);
int getSelectedMapIndex();
Font* getFont();
void setFont(Font*);
};
<file_sep>#pragma once
#include "GameEntity.h"
class GameplayElement:public GameEntity
{
private:
// Pour le selector
bool focused;
bool locked;
// pour la peinture
bool Paintable; // rocher, block vivant et bouteilles = false
Color color; // rocher et block vivant = couleur spécifique non incluse
bool inhalable; // Bouteille vivante, rocher et block vivant = false
//pour le déplacement
bool grabbable; // faux pour les bouteilles et le block vivant
bool HateWalls; // différencie les éléments qui ne peuvent etre placés dans un mur
public:
GameplayElement();
GameplayElement(bool, bool, bool, Color, bool, bool);
bool getFocused();
void setFocused(bool);
bool getLocked();
void setLocked(bool);
bool getPaintable();
void setPaintable(bool);
Color getColor();
void setColor(Color);
bool getInhalable();
void setInhalable(bool);
bool getgrabbable();
void setgrabbable(bool);
bool getHateWalls();
void setHateWalls(bool);
void claimFocus();
void grab();
};
<file_sep>#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <SFML/audio.hpp>
#include <SFML/Graphics.hpp>
#include "GameObject.h"
using namespace std;
using namespace sf;
class ElementContainer
{
private:
String Type;
String name;
GameObject gameObject;
public:
ElementContainer();
String getType();
void setType(String);
String getName();
void setName(String);
};
<file_sep>#include "Goal.h"
Goal::Goal():GameEntity()
{
}
Goal::Goal(Vector2f pos, Texture tex, IntRect rect) : GameEntity(true, 4, pos, tex, rect)
{
}
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <SFML/audio.hpp>
#include <SFML/Graphics.hpp>
#include "GameMaster.h"
using namespace std;
using namespace sf;
int main(void) {
GameMaster MJ;
Font myFont;
if (!myFont.loadFromFile("PressStart2P-Regular.ttf")) {
//cout << "Font failed to load" << endl;
}
MJ.setFont(&myFont);
/*
VIDE, MUR, ONEWAY, ONEWAY_HAUT, ONEWAY_BAS, ONEWAY_GAUCHE,
ONEWAY_DROITE, PIQUE, SWITCH, GOAL, ROCHER, BOUTEILLE,
BOUTEILLE_VIVANTE, BOUTEILLE_COULEUR1, BOUTEILLE_COULEUR2,
BOUTEILLE_COULEUR3, PLAYER, SPAWN,
BLOC, BLOC_VIVANT, BLOC_COULEUR1,
BLOC_COULEUR2, BLOC_COULEUR3, ANIMAL, ANIMAL_COULEUR1,
ANIMAL_COULEUR2, ANIMAL_COULEUR3,
*/
/**
MJ.addMap(Map(1500, {
{MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, GOAL, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, SPAWN, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, SWITCH, VIDE, VIDE, VIDE, BOUTEILLE, MUR},
{MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR},
}));
/**/
MJ.addMap(Map(2000,{
{MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR},
{MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR},
{MUR, MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, VIDE, VIDE, VIDE, GOAL, VIDE, VIDE, MUR, MUR},
{MUR, MUR, VIDE, GOAL, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, VIDE, VIDE, GOAL, VIDE, GOAL, VIDE, MUR, MUR},
{MUR, MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, ONEWAY_DROITE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, VIDE, GOAL, VIDE, VIDE, VIDE, GOAL, MUR, MUR},
{MUR, MUR, VIDE, ONEWAY_HAUT, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, MUR},
{MUR, MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, VIDE, VIDE, VIDE, VIDE, BOUTEILLE, VIDE, VIDE, VIDE, BOUTEILLE_COULEUR3, VIDE, VIDE, VIDE, MUR, VIDE, VIDE, GOAL, VIDE, GOAL, VIDE, MUR, MUR},
{MUR, MUR, VIDE, VIDE, VIDE, BLOC_COULEUR2, VIDE, VIDE, VIDE, VIDE, MUR, ONEWAY_HAUT, ONEWAY_HAUT, ONEWAY_HAUT, ONEWAY_HAUT, ONEWAY_HAUT, VIDE, VIDE, ONEWAY_HAUT, ONEWAY_HAUT, VIDE, VIDE, VIDE, MUR, VIDE, VIDE, GOAL, GOAL, GOAL, VIDE, MUR, MUR},
{MUR, MUR, VIDE, ONEWAY_HAUT, VIDE, VIDE, ONEWAY_GAUCHE, ONEWAY_DROITE, VIDE, VIDE, MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, VIDE, VIDE, GOAL, GOAL, GOAL, VIDE, MUR, MUR},
{MUR, MUR, VIDE, VIDE, VIDE, ONEWAY_BAS, VIDE, ONEWAY_BAS, VIDE, ONEWAY_BAS, MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, VIDE, VIDE, VIDE, GOAL, VIDE, VIDE, MUR, MUR},
{MUR, MUR, VIDE, VIDE, VIDE, SPAWN, VIDE, VIDE, VIDE, VIDE, MUR, MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, ONEWAY_HAUT, VIDE, ONEWAY_HAUT, VIDE, VIDE, MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, MUR},
{MUR, MUR, VIDE, ONEWAY_HAUT, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, MUR},
{MUR, MUR, VIDE, VIDE, BLOC, VIDE, VIDE, VIDE, PIQUE, PIQUE, MUR, BOUTEILLE_VIVANTE, VIDE, VIDE, VIDE, BOUTEILLE_COULEUR1, VIDE, SWITCH, VIDE, BOUTEILLE_COULEUR2, VIDE, VIDE, VIDE, VIDE, ROCHER, VIDE, VIDE, VIDE, VIDE, VIDE, MUR, MUR},
{MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR},
{MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR},
}));
MJ.addMap(Map(1500, {
{MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, GOAL, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, ONEWAY_BAS, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, ONEWAY_BAS, VIDE, ONEWAY_BAS, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, ROCHER, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, ONEWAY_BAS, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, ONEWAY_BAS, VIDE, ONEWAY_BAS, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, SPAWN, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, BLOC, BLOC, BLOC_COULEUR1, VIDE, VIDE, VIDE, VIDE, VIDE, SWITCH, VIDE, VIDE, VIDE, BOUTEILLE, MUR},
{MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR},
}));
MJ.addMap(Map(500,{
{MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR},
{MUR, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, GOAL, VIDE, VIDE, VIDE, GOAL, VIDE, GOAL, GOAL, GOAL, VIDE, GOAL, GOAL, GOAL, VIDE, VIDE, GOAL, VIDE, VIDE, GOAL, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, GOAL, GOAL, VIDE, GOAL, GOAL, VIDE, GOAL, VIDE, VIDE, VIDE, GOAL, VIDE, GOAL, VIDE, GOAL, VIDE, GOAL, VIDE, VIDE, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, GOAL, VIDE, GOAL, VIDE, GOAL, VIDE, GOAL, GOAL, VIDE, VIDE, GOAL, GOAL, VIDE, VIDE, GOAL, VIDE, VIDE, VIDE, GOAL, VIDE, VIDE, MUR},
{MUR, SPAWN, VIDE, VIDE, GOAL, VIDE, VIDE, VIDE, GOAL, VIDE, GOAL, VIDE, VIDE, VIDE, GOAL, VIDE, GOAL, VIDE, GOAL, VIDE, GOAL, VIDE, GOAL, VIDE, VIDE, MUR},
{MUR, VIDE, VIDE, VIDE, GOAL, VIDE, VIDE, VIDE, GOAL, VIDE, GOAL, GOAL, GOAL, VIDE, GOAL, VIDE, GOAL, VIDE, VIDE, GOAL, VIDE, VIDE, GOAL, VIDE, VIDE, MUR},
{MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR, MUR},
}));
MJ.addMap(Map{ 404, {
{ SPAWN, VIDE},
{ VIDE, VIDE},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL},
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ GOAL, GOAL },
{ PIQUE, PIQUE },
{ GOAL, GOAL },
} });
MJ.run();
}<file_sep>#pragma once
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace std;
using namespace sf;
/* ENUMERATEURS */
enum class Direction { HAUT, BAS, GAUCHE, DROITE }; // Les directions de deplacement possibles
enum ElementTypes { // Les éléments que l'on peut retrouver dans une carte matrice
VIDE, MUR, ONEWAY, ONEWAY_HAUT, ONEWAY_BAS, ONEWAY_GAUCHE, ONEWAY_DROITE,
PIQUE, SWITCH, GOAL, ROCHER, BOUTEILLE, BOUTEILLE_VIVANTE, BOUTEILLE_COULEUR1, BOUTEILLE_COULEUR2,
BOUTEILLE_COULEUR3, BLOC, BLOC_VIVANT, BLOC_COULEUR1, BLOC_COULEUR2, BLOC_COULEUR3, ANIMAL,
ANIMAL_COULEUR1, ANIMAL_COULEUR2, ANIMAL_COULEUR3, PLAYER, SPAWN
};
enum MovingState { // Les Mouvement possibles pour les entités non joueur
IDLE, MOVING_LEFT, MOVING_RIGHT, MOVING_UP, MOVING_DOWN,
JUMPING, FALLING, MOVING_UP_LEFT, MOVING_UP_RIGHT, MOVING_DOWN_LEFT, MOVING_DOWN_RIGHT,
};
enum GameColor { // Les couleurs disponible (NOCOLOR = blanc, ROUGE, BLEU et JAUNE)
NOCOLOR,ROUGE,BLEU,JAUNE
};
//Fonctions utilitaires pour convertir les enums gamecolor en couleur
Color getColorFromEnum(GameColor);
GameColor getEnumFromColor(Color);
//Fonctions utilitaires pour obtenir une zone de collision plus adaptée en fonction des cas
FloatRect getInnerBounds(Direction, FloatRect );
//Fonctions utilitaires pour obtenir une zone de collision plus adaptée en fonction des cas
FloatRect getOuterBounds(Direction, FloatRect, int);
class Scene;
class GameObject
{
protected:
Sprite sprite;
IntRect textureRect;
Texture texture;
int animationframes = 1;
Clock innerAnnimationClock;
float frequence = 0.5;
int animationStep = 0;
public:
/* CONSTRUCTEURS */
GameObject();//Constructeur standard
/*
Les constructeurs suivant servent pour etre intégrés dans la construction de classes filles
*/
GameObject(Vector2f, Texture, IntRect);
GameObject(int, Vector2f, Texture, IntRect);
/* FONCTIONS MEMBRES DE LA CLASSE */
void drawMe(RenderWindow&);
virtual void update(Scene *);
/* GETER SETER */
Sprite* getSprite();
void setSprite(Sprite);
IntRect* getTextureRect();
void setTextureRect(IntRect);
Texture* getTexture();
void setTexture(Texture);
int getAnimationframes();
void setAnimationframes(int);
};
<file_sep>#include "Mur.h"
Mur::Mur():GameObject()
{
}
Mur::Mur(Vector2f Pos):GameObject()
{
sprite.setPosition(Pos);
}
Mur::Mur(Vector2f pos, Texture tex, IntRect rect):GameObject(pos,tex,rect)
{
/*setPosition(pos);
setTexture(tex);
setTextureRect(rect);*/
}
/**
void Mur::update()
{
}
/**/<file_sep>#include "Map.h"
Map::Map()
{
initialScore = 1000;
highScore = 0;
gravity = 9.8;
matrice = {
{VIDE}
};
sauvegardes.push_back(generate());
// cout << "sauvegarde size = " << sauvegardes.size() << endl ;
isPlaying = true;
}
Map::Map(vector<vector<enum ElementTypes>> M)
{
initialScore = 1000;
highScore = 0;
gravity = 9.8;
matrice = M;
sauvegardes.push_back(generate());
// cout << "sauvegarde size = " << sauvegardes.size() << endl ;
isPlaying = true;
}
Map::Map(int i, vector<vector<enum ElementTypes>> M)
{
initialScore = i;
highScore = 0;
gravity = 9.8;
matrice = M;
sauvegardes.push_back(generate());
// cout << "sauvegarde size = " << sauvegardes.size() << endl ;
isPlaying = true;
}
Map::Map(int i, double g, vector<vector<enum ElementTypes>> M, vector<Scene> sv)
{
initialScore = i;
highScore = 0;
gravity = g;
matrice = M;
sauvegardes = sv;
isPlaying = true;
}
void Map::finish()
{
cout << "finish" << endl;
if (sauvegardes.size() != 0) {
//on recupere le meilleur score
highScore = sauvegardes.at(0).getScore();
//On supprime les sauvegardes et on regénère la scene
while (sauvegardes.size() != 0)
{
sauvegardes.pop_back();
}
sauvegardes.push_back(generate());
// cout << "sauvegarde size = " << sauvegardes.size() << endl ;
isPlaying = false;
}
else {
// cout << "Not supposed to Finish" << endl;
}
}
Scene Map::generate()
{
Scene retour(initialScore,matrice);
return retour;
}
void Map::quickSave()
{
cout << "quickSave" << endl;
int penalty = 20;
//On supprime toutes les sauvegardes pour n'en laisser que la scene en cours
while (sauvegardes.size() > 1)
{
sauvegardes.erase(sauvegardes.begin()+1);
sauvegardes.shrink_to_fit();
}
if (sauvegardes.size() != 0) {
// cout << "copying" << endl;
Scene duplique = Scene(&sauvegardes.at(0));
duplique.setScore(duplique.getScore() - penalty);
sauvegardes.push_back(duplique);
// cout << "sauvegarde size = " << sauvegardes.size() << endl ;
}
else {
cout << "Pas de quickSave sans sauvegardes existantes" << endl;
}
}
void Map::loadSave()
{
cout << "loadSave" << endl;
if (sauvegardes.size() > 1) {
//Transfert du texte
sauvegardes.at(1).setScoreString(sauvegardes.at(0).getScoreString());
sauvegardes.erase(sauvegardes.begin());
sauvegardes.shrink_to_fit();
// cout << "sauvegarde size = " << sauvegardes.size() << endl ;
}
else {
// cout << "Pas assez de sauvegardes" << endl;
}
}
void Map::update(RenderWindow& window, vector <Event>Evts)
{
int output;
output = sauvegardes[0].update(window, Evts);
if (output > 0) {//You Win
cout << "score = " << output << endl;
if (output > highScore) {
highScore = output;
cout << "new high score : " << output << endl;
}
isPlaying = false;
return;
}
if (output == 0) {//You Died
cout << "restart" << endl;
restart();
}
}
void Map::draw(RenderWindow&R)
{
sauvegardes[0].draw(R);
}
void Map::restart()
{
// cout << "restart" << endl;
//On supprime toutes les sauvegardes pour n'en laisser qu'une
while (sauvegardes.size() > 1)
{
sauvegardes.erase(sauvegardes.begin());
sauvegardes.shrink_to_fit();
}
//On ajoute une sauvegarde vierge
sauvegardes.push_back(generate());
// cout << "sauvegarde size = " << sauvegardes.size() << endl ;
//et on la charge
loadSave();
}
int Map::getInitialScore()
{
return initialScore;
}
void Map::setInitialScore(int i)
{
initialScore = i;
}
double Map::getGravity()
{
return gravity;
}
void Map::setGravity(double g)
{
gravity = g;
}
vector<vector<enum ElementTypes>> Map::getMatrice()
{
return matrice;
}
void Map::setMatrice(vector<vector<enum ElementTypes>> m)
{
matrice = m;
}
vector<Scene> Map::getSauvegardes()
{
return sauvegardes;
}
void Map::setSauvegardes(vector<Scene> s)
{
sauvegardes = s;
}
bool Map::getIsPlaying()
{
return isPlaying;
}
void Map::setIsPlaying(bool b)
{
isPlaying = b;
if (isPlaying == true)
restart();
}
<file_sep>#pragma once
#include "FocusableElement.h"
class PaintableElement:public FocusableElement //classe mere des éléments interagissant avec la couleur
{
protected:
bool paintable = false; // si l'on peut appliquer de la couleur ou non sur l'objet
enum GameColor color = GameColor::NOCOLOR; // la couleur stockée de l'élément
bool inhalable = true; // si l'on peut prendre de la couleur ou non de l'objet
public:
/* CONSTRUCTEURS
*/
PaintableElement();//Constructeur standard
/*
Les constructeurs suivant servent pour etre intégrés dans la construction de classes filles
*/
PaintableElement(bool, bool);
PaintableElement(bool, bool, bool);
PaintableElement(bool, bool, bool, GameColor);
PaintableElement(bool, bool, bool, Vector2f, Texture, IntRect);
PaintableElement(bool, bool, bool, int, Vector2f, Texture, IntRect);
PaintableElement(bool, bool, GameColor);
PaintableElement(bool, bool, GameColor, bool, Vector2f, Texture, IntRect);
PaintableElement(bool, bool, GameColor, bool, int, Vector2f, Texture, IntRect);
/* GETER SETER */
bool getPaintable();
void setPaintable(bool);
GameColor getColor();
void setColor(GameColor);
bool getInhalable();
void setInhalable(bool);
};
<file_sep>#pragma once
#include "GameObject.h"
class GameEntity : public GameObject//classe mère des objets non Joueur
{
protected:
bool traversable; //Si un élément est transparent aux collisions
public:
/* CONSTRUCTEURS */
GameEntity();//Constructeur standard
/*
Les constructeurs suivant servent pour etre intégrés dans la construction de classes filles
*/
GameEntity(bool);
GameEntity(bool, Vector2f, Texture, IntRect);
GameEntity(bool, int, Vector2f, Texture, IntRect);
/* FONCTIONS MEMBRES DE LA CLASSE */
virtual void interact();
/* GETER SETER */
bool getTraversable();
void setTraversable(bool);
};
<file_sep>#include "Bouteille.h"
Bouteille::Bouteille():PaintableElement(false,false, GameColor::ROUGE)
{
}
Bouteille::Bouteille(GameColor c):PaintableElement(false, false,c)
{
}
Bouteille::Bouteille(bool vrai):PaintableElement(false, vrai, GameColor::ROUGE)
{
}
Bouteille::Bouteille(bool vrai, GameColor c):PaintableElement(false, vrai, c)
{
}
Bouteille::Bouteille(bool vrai, Vector2f pos, Texture tex, IntRect rect) : PaintableElement(false, vrai, GameColor::ROUGE, false, 4, pos, tex, rect)
{
}
Bouteille::Bouteille(bool vrai, GameColor c, Vector2f pos, Texture tex, IntRect rect) : PaintableElement(false, vrai, c, false, 4, pos, tex, rect)
{
}
<file_sep>#include "MobileGameplayElement.h"
#include "Scene.h"
MobileGameplayElement::MobileGameplayElement(): PaintableElement(false, false,false)
{
movingState = FALLING;
HateWalls = true;
heavy = false;
/*
code dupliqué
*/
flying = TraverseBlock = false;
speed = 15;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = TraverseMur = false;
Hauteur = 0;
////cout << "speed:" << speed << endl;
}
MobileGameplayElement::MobileGameplayElement(
bool hw, bool hv, GameColor gc
) : PaintableElement(false, false, false, gc)
{
movingState = FALLING;
HateWalls = hw;
heavy = hv;
/*
code dupliqué
*/
flying = TraverseBlock = false;
speed = 15;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = TraverseMur = false;
Hauteur = 0;
//cout << "speed:" << speed << endl;
}
MobileGameplayElement::MobileGameplayElement(
bool hw, bool hv, bool paintbl, bool inhalabl, GameColor gc
) : PaintableElement(paintbl, inhalabl, false, gc)
{
movingState = FALLING;
HateWalls = hw;
heavy = hv;
/*
code dupliqué
*/
flying = TraverseBlock = false;
speed = 15;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = TraverseMur = false;
Hauteur = 0;
//cout << "speed:" << speed << endl;
}
MobileGameplayElement::MobileGameplayElement(
bool hw, bool hv, bool paintbl, bool inhalabl, bool fly, double Speed,
bool TraverseB, bool TraverseM, bool MarcheSurB, GameColor gc
): PaintableElement(paintbl, inhalabl, false,gc)
{
movingState = FALLING;
HateWalls = hw;
heavy = hv;
/*
code dupliqué
*/
flying = fly;
TraverseBlock = TraverseB;
speed = Speed;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = MarcheSurB;
TraverseMur = TraverseM;
Hauteur = 0;
//cout << "speed:" << speed << endl;
}
MobileGameplayElement::MobileGameplayElement(
bool hateW, bool heavii, bool fly, double Speed, bool TraverseB,
bool TraverseM, bool MarcheSurB, bool traversable, Vector2f position,
Texture texture, IntRect textrect, GameColor gc
):PaintableElement(false,false, gc,traversable, position, texture, textrect)
{
//cout << "traversable" << traversable << endl;
movingState = FALLING;
HateWalls = hateW;
heavy = heavii;
/*
code dupliqué
*/
flying = fly;
TraverseBlock = TraverseB;
speed = Speed;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = MarcheSurB;
TraverseMur = TraverseM;
Hauteur = 0;
Fantome.setTexture(texture);
Fantome.setTextureRect(textrect);
//cout << "speed:" << speed << endl;
}
MobileGameplayElement::MobileGameplayElement(
bool hateW, bool heavii, bool fly, double Speed, bool TraverseB,
bool TraverseM, bool MarcheSurB, bool traversable, Vector2f position,
Texture texture, IntRect textrect, bool paintbl, bool inhalabl, GameColor gc
):PaintableElement(paintbl, inhalabl, gc, traversable, position, texture, textrect)
{
//cout << "traversable" << traversable << endl;
movingState = FALLING;
HateWalls = hateW;
heavy = heavii;
/*
code dupliqué
*/
flying = fly;
TraverseBlock = TraverseB;
speed = Speed;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = MarcheSurB;
TraverseMur = TraverseM;
Hauteur = 0;
Fantome.setTexture(texture);
Fantome.setTextureRect(textrect);
////cout << "speed:" << speed << endl;
}
MobileGameplayElement::MobileGameplayElement(
bool hateW, bool heavii, bool fly, double Speed, bool TraverseB,
bool TraverseM, bool MarcheSurB, bool traversable, int intervalframe,
Vector2f position, Texture texture, IntRect textrect, GameColor gc
) :PaintableElement(false, false, gc, traversable,
intervalframe, position, texture, textrect)
{
//cout << "traversable " << traversable << endl;
movingState = FALLING;
HateWalls = hateW;
heavy = heavii;
/*
code dupliqué
*/
flying = fly;
TraverseBlock = TraverseB;
speed = Speed;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = MarcheSurB;
TraverseMur = TraverseM;
Hauteur = 0;
Fantome.setTexture(texture);
Fantome.setTextureRect(textrect);
////cout << "speed:" << speed << endl;
}
MobileGameplayElement::MobileGameplayElement(
bool hateW, bool heavii, bool fly, double Speed, bool TraverseB,
bool TraverseM, bool MarcheSurB, bool traversable, int intervalframe,
Vector2f position, Texture texture, IntRect textrect, bool paintbl,
bool inhalabl, GameColor gc
):PaintableElement(paintbl,inhalabl,gc, traversable,
intervalframe, position, texture, textrect)
{
//cout << "traversable" << traversable << endl;
movingState = FALLING;
HateWalls = hateW;
heavy = heavii;
/*
code dupliqué
*/
flying = fly;
TraverseBlock = TraverseB;
speed = Speed;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = MarcheSurB;
TraverseMur = TraverseM;
Hauteur = 0;
Fantome.setTexture(texture);
Fantome.setTextureRect(textrect);
//cout <<"speed:"<< speed << endl;
}
void MobileGameplayElement::update(Scene* scene)
{
//cout << "update MobileGamePlayElement" << endl;
if (!flying) { //system de chute pour les éléments non volants
/*
Ce code est inspiré de player.cpp,
cependant des propriétés doivent etre ajoutées pour s'adapter au type nonPlayer
*/
GameObject* testcollbas = scene->testCollide(this, Direction::BAS);
if (testcollbas) {
if (getHauteur() != 0 && acceleration.y > 0) {
setHauteur(0);
FloatRect colliderGB = testcollbas->getSprite()->getGlobalBounds();
FloatRect localGB = this->getSprite()->getGlobalBounds();
float LocalDelta = (colliderGB.top - localGB.height) - localGB.top;
this->getSprite()->move(Vector2f(0, LocalDelta));
}
if (heavy) {
//Suppresion des éléments sur lesquels l'objet atterrie selon certaines conditions
MobileGameplayElement* mgeptr = dynamic_cast<MobileGameplayElement*>(testcollbas);
bool deleted = false;
if (mgeptr) {
vector <GameObject*> grabs = scene->getGrabbablesETInhalables();
for (int i = 0; i < grabs.size() && !deleted; i++)
{
if (mgeptr->getSprite()->getGlobalBounds() == grabs.at(i)->getSprite()->getGlobalBounds()) {
grabs.erase(grabs.begin() + i);
grabs.shrink_to_fit();
deleted = true;
}
}
scene->setGrabbablesETInhalables(grabs);
}
if (!deleted) {
movingState = IDLE;
}
}
else {
movingState = IDLE;
}
}
else {
if (getHauteur() == 0) {
setHauteur(1);
}
movingState = FALLING;
}
}
updatePos(9.8 / 12);
}
enum MovingState MobileGameplayElement::getMovingState()
{
return movingState;
}
void MobileGameplayElement::setMovingState(enum MovingState m)
{
movingState = m;
}
bool MobileGameplayElement::getHateWalls()
{
return HateWalls;
}
void MobileGameplayElement::setHateWalls(bool h)
{
HateWalls = h;
}
bool MobileGameplayElement::getHeavy()
{
return heavy;
}
void MobileGameplayElement::setHeavy(bool h)
{
heavy = h;
}
/*
Fonctions dupliquées et adaptées de MobileEntity
*/
void MobileGameplayElement::moveTo(Direction d)
{
switch (d) {
case Direction::HAUT:
if (Hauteur == 0) {
if (!flying) {
Hauteur = 1;
acceleration.y = -30;
}
direction.y = -1;
}
break;
case Direction::BAS:
direction.y = 1;
break;
case Direction::GAUCHE:
direction.x = -1;
break;
case Direction::DROITE:
direction.x = 1;
break;
default:
break;
}
}
void MobileGameplayElement::updatePos(double G)
{
if (Hauteur != 0 && !flying) {
acceleration.y += G;
}
else {
acceleration.y = 0;
}
//cout << "x:" << sprite.getPosition().x << " y:" << sprite.getPosition().y;
//cout << "dy:" << direction.y << " ay:" << acceleration.y << "tot:" << (direction.y * speed) + acceleration.y << "h" << Hauteur << endl;
sprite.move((direction.x * speed) + acceleration.x, (direction.y * speed) + acceleration.y);
}
void MobileGameplayElement::initDirection()
{
direction = Vector2f(0, 0);
}
Sprite MobileGameplayElement::getUpdatedFantome(Direction d)
{
double myHauteur = Hauteur;
Vector2f myDirection(direction), myAcceleration(acceleration);
Fantome.setPosition(sprite.getPosition());
Fantome.setScale(sprite.getScale());
Fantome.setTextureRect(sprite.getTextureRect());
#pragma region moveto
switch (d) {
case Direction::HAUT:
if (myHauteur == 0) {
if (!flying) {
myHauteur = 1;
myAcceleration.y = -30;
}
myDirection.y = -1;
}
break;
case Direction::BAS:
myDirection.y = 1;
break;
case Direction::GAUCHE:
myDirection.x = -1;
break;
case Direction::DROITE:
myDirection.x = 1;
break;
default:
//cout << "direction inconnue" << endl;
break;
}
#pragma endregion
#pragma region updatepos
if (myHauteur != 0 && !flying) {
myAcceleration.y -= 9.8 / 12;
}
else {
myAcceleration.y = 0;
}
Fantome.move((myDirection.x * speed) + myAcceleration.x, (myDirection.y * speed) + myAcceleration.y);
#pragma endregion
return Fantome;
}
bool MobileGameplayElement::getFlying()
{
return flying;
}
void MobileGameplayElement::setFlying(bool f)
{
flying = f;
}
double MobileGameplayElement::getSpeed()
{
return speed;
}
void MobileGameplayElement::setSpeed(double s)
{
speed = s;
}
Vector2f MobileGameplayElement::getAcceleration()
{
return acceleration;
}
void MobileGameplayElement::setAcceleration(Vector2f a)
{
acceleration = a;
}
Vector2f MobileGameplayElement::getDirection()
{
return direction;
}
void MobileGameplayElement::setDirection(Vector2f d)
{
direction = d;
}
bool MobileGameplayElement::getTraverseBlock()
{
return TraverseBlock;
}
void MobileGameplayElement::setTraverseBlock(bool t)
{
TraverseBlock = t;
}
bool MobileGameplayElement::getTraverseMur()
{
return TraverseMur;
}
void MobileGameplayElement::setTraverseMur(bool t)
{
TraverseMur = t;
}
bool MobileGameplayElement::getMarcheSurBlock()
{
return MarcheSurBlock;
}
void MobileGameplayElement::setMarcheSurBlock(bool m)
{
MarcheSurBlock = m;
}
double MobileGameplayElement::getHauteur()
{
return Hauteur;
}
void MobileGameplayElement::setHauteur(double h)
{
Hauteur = h;
}
Sprite MobileGameplayElement::getFantome()
{
Fantome.setPosition(sprite.getPosition());
Fantome.setScale(sprite.getScale());
Fantome.setTextureRect(sprite.getTextureRect());
return Fantome;
}
void MobileGameplayElement::setFantome(Sprite f)
{
Fantome = f;
}
<file_sep>#include "MobileEntity.h"
MobileEntity::MobileEntity():GameObject()
{
flying = TraverseBlock = false;
speed = 15;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = TraverseMur = false;
Hauteur = 0;
}
MobileEntity::MobileEntity(
Vector2f pos, Texture tex, IntRect rect
) :GameObject(pos, tex, rect)
{
flying = TraverseBlock = false;
speed = 15;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = true;
TraverseMur = false;
Hauteur = 0;
Fantome.setTexture(tex);
Fantome.setTextureRect(rect);
}
MobileEntity::MobileEntity(
int intervalframe, Vector2f pos, Texture tex, IntRect rect
) :GameObject(intervalframe, pos, tex, rect)
{
flying = TraverseBlock = false;
speed = 15;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = true;
TraverseMur = false;
Hauteur = 0;
Fantome.setTexture(tex);
Fantome.setTextureRect(rect);
}
MobileEntity::MobileEntity(
bool fly, double Speed, bool TraverseB, bool TraverseM,
bool MarcheSurB
):GameObject()
{
flying = fly;
TraverseBlock = TraverseB;
speed = Speed;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = MarcheSurB;
TraverseMur = TraverseM;
Hauteur = 0;
}
MobileEntity::MobileEntity(
bool fly, double Speed, bool TraverseB, bool TraverseM,
bool MarcheSurB, Vector2f pos, Texture tex, IntRect rect
) :GameObject(pos, tex, rect)
{
flying = fly;
TraverseBlock = TraverseB;
speed = Speed;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = MarcheSurB;
TraverseMur = TraverseM;
Hauteur = 0;
Fantome.setTexture(tex);
Fantome.setTextureRect(rect);
}
MobileEntity::MobileEntity(
bool fly, double Speed, bool TraverseB, bool TraverseM,
bool MarcheSurB, int intervalFrame, Vector2f pos,
Texture tex, IntRect rect
) :GameObject(intervalFrame, pos, tex, rect)
{
flying = fly;
TraverseBlock = TraverseB;
speed = Speed;
acceleration = direction = Vector2f(0, 0);
MarcheSurBlock = MarcheSurB;
TraverseMur = TraverseM;
Hauteur = 0;
Fantome.setTexture(tex);
Fantome.setTextureRect(rect);
}
MobileEntity::MobileEntity(
bool fly, double myspeed, Vector2f myAcceleration,
Vector2f myDirection, bool TravB, bool TravM, bool MarchB,
double Hight
):GameObject()
{
flying = fly;
speed = myspeed;
acceleration = myAcceleration;
direction = myDirection;
TraverseBlock = TravB;
TraverseMur = TravM;
MarcheSurBlock = MarchB;
Hauteur = Hight;
}
MobileEntity::MobileEntity(
bool fly, double myspeed, Vector2f myAcceleration,
Vector2f myDirection, bool TravB, bool TravM, bool MarchB,
double Hight, Vector2f pos, Texture tex, IntRect rect
) :GameObject(pos, tex, rect)
{
flying = fly;
speed = myspeed;
acceleration = myAcceleration;
direction = myDirection;
TraverseBlock = TravB;
TraverseMur = TravM;
MarcheSurBlock = MarchB;
Hauteur = Hight;
Fantome.setTexture(tex);
Fantome.setTextureRect(rect);
}
MobileEntity::MobileEntity(
bool fly, double myspeed, Vector2f myAcceleration,
Vector2f myDirection, bool TravB, bool TravM, bool MarchB,
double Hight, int intervalFrame, Vector2f pos, Texture tex,
IntRect rect
) :GameObject(intervalFrame, pos, tex, rect)
{
flying = fly;
speed = myspeed;
acceleration = myAcceleration;
direction = myDirection;
TraverseBlock = TravB;
TraverseMur = TravM;
MarcheSurBlock = MarchB;
Hauteur = Hight;
Fantome.setTexture(tex);
Fantome.setTextureRect(rect);
}
void MobileEntity::moveTo(Direction d)
{
switch (d) {
case Direction::HAUT:
if (Hauteur == 0) {
if (!flying) {
Hauteur = 1;
acceleration.y = -30;
}
direction.y = -1;
}
break;
case Direction::BAS:
direction.y = 1;
break;
case Direction::GAUCHE:
direction.x = -1;
break;
case Direction::DROITE:
direction.x = 1;
break;
default:
//cout << "direction inconnue" <<endl;
break;
}
}
void MobileEntity::updatePos(double G)
{
if (Hauteur != 0 && !flying) {
acceleration.y += G;
}
else {
acceleration.y = 0;
}
//cout << "x:" << sprite.getPosition().x << " y:" << sprite.getPosition().y;
//cout << "dy:" << direction.y << " ay:" << acceleration.y << "tot:" << (direction.y * speed) + acceleration.y << "h" << Hauteur << endl;
sprite.move((direction.x * speed) + acceleration.x, (direction.y * speed) + acceleration.y);
}
void MobileEntity::initDirection()
{
direction = Vector2f(0, 0);
}
Sprite MobileEntity::getUpdatedFantome(Direction d)
{
double myHauteur = Hauteur;
Vector2f myDirection(direction), myAcceleration(acceleration);
Fantome.setPosition(sprite.getPosition());
Fantome.setScale(sprite.getScale());
Fantome.setTextureRect(sprite.getTextureRect());
#pragma region moveto
switch (d) {
case Direction::HAUT:
if (myHauteur == 0) {
if (!flying) {
myHauteur = 1;
myAcceleration.y = -30;
}
myDirection.y = -1;
}
break;
case Direction::BAS:
myDirection.y = 1;
break;
case Direction::GAUCHE:
myDirection.x = -1;
break;
case Direction::DROITE:
myDirection.x = 1;
break;
default:
//cout << "direction inconnue" << endl;
break;
}
#pragma endregion
#pragma region updatepos
if (myHauteur != 0 && !flying) {
myAcceleration.y -= 9.8 / 12;
}
else {
myAcceleration.y = 0;
}
Fantome.move((myDirection.x * speed) + myAcceleration.x, (myDirection.y * speed) + myAcceleration.y);
#pragma endregion
return Fantome;
}
bool MobileEntity::getFlying()
{
return flying;
}
void MobileEntity::setFlying(bool f)
{
flying = f;
}
double MobileEntity::getSpeed()
{
return speed;
}
void MobileEntity::setSpeed(double s)
{
speed = s;
}
Vector2f MobileEntity::getAcceleration()
{
return acceleration;
}
void MobileEntity::setAcceleration(Vector2f a)
{
acceleration = a;
}
Vector2f MobileEntity::getDirection()
{
return direction;
}
void MobileEntity::setDirection(Vector2f d)
{
direction = d;
}
bool MobileEntity::getTraverseBlock()
{
return TraverseBlock;
}
void MobileEntity::setTraverseBlock(bool t)
{
TraverseBlock = t;
}
bool MobileEntity::getTraverseMur()
{
return TraverseMur;
}
void MobileEntity::setTraverseMur(bool t)
{
TraverseMur = t;
}
bool MobileEntity::getMarcheSurBlock()
{
return MarcheSurBlock;
}
void MobileEntity::setMarcheSurBlock(bool m)
{
MarcheSurBlock = m;
}
double MobileEntity::getHauteur()
{
return Hauteur;
}
void MobileEntity::setHauteur(double h)
{
Hauteur = h;
}
Sprite MobileEntity::getFantome()
{
Fantome.setPosition(sprite.getPosition());
Fantome.setScale(sprite.getScale());
Fantome.setTextureRect(sprite.getTextureRect());
return Fantome;
}
void MobileEntity::setFantome(Sprite f)
{
Fantome = f;
}
<file_sep>#include "OneWay.h"
OneWay::OneWay():GameEntity()
{
blockDirection = Direction::HAUT;
}
OneWay::OneWay(Direction d):GameEntity()
{
blockDirection = d;
}
OneWay::OneWay(Direction d, Vector2f pos, Texture tex, IntRect rect) : GameEntity(false,pos, tex, rect)
{
blockDirection = d;
}
Direction OneWay::getBlockDirection()
{
return blockDirection;
}
void OneWay::setBlockDirection(Direction d)
{
blockDirection = d;
}<file_sep>#include "GameMaster.h"
GameMaster::GameMaster():RenderWindow(VideoMode(1200, 1000), "Sutte Hakkun by <NAME>")
{
selectedMapIndex = 0;
framerate = 60;
MainClock.restart();
}
void GameMaster::run()
{
cout << "Run" << endl;
Map mainMap = maps.at(selectedMapIndex);
View v (FloatRect(0, 0, 4800, 4000));
v.zoom(0.30f);
this->setView(v);
//Ensemble des actions disponibles dans le menu principal
vector <String> MainMenuInputs;
//Génération des inputs
for (int i = 0; i < maps.size(); i++)
MainMenuInputs.push_back("Play Level " + to_string(i + 1));
MainMenuInputs.push_back("Exit/return (Escape)");
//Ensemble des inputs pour le menu in game
vector <String> MenuInputs{
"Recommencer",
"Sauvegarder",
"charger sauvegarde",
"Menu principal"
};
Event event;
vector <Event> eventList;//sert pour envoyer les événements aux maps/scenes si ils ne concernent pas le GameMaster
MainMenu mainMenu(this->getSize().x, this->getSize().y, font, MainMenuInputs, "Menu Principal");//menu principale
mainMenu.setOpened(true);
MainMenu InGameMenu(this->getSize().x, this->getSize().y, font, MenuInputs, "Pause");//menu principale
InGameMenu.setOpened(false);
while (isOpen()) {
if (float(MainClock.getElapsedTime().asSeconds()) >= 0.016)//1 / 60 = 0.016
{
eventList.clear();
eventList.shrink_to_fit();
while (this->pollEvent(event)) {
switch (event.type)
{
case Event::Closed:
this->close();
break;
case Event::KeyPressed:
if (mainMenu.getOpened()) {
if (event.key.code == Keyboard::Down) {
mainMenu.MoveDown();
}
else if (event.key.code == Keyboard::Up) {
mainMenu.MoveUp();
}
else if (event.key.code == Keyboard::Enter) {
if (mainMenu.getSelectedItemIndex() == 5)
this->close();
else {
selectedMapIndex = mainMenu.getSelectedItemIndex();
mainMap = maps.at(selectedMapIndex);
mainMap.restart();
mainMenu.setOpened(false);
}
}
}
else if ((InGameMenu.getOpened())) {
if (event.key.code == Keyboard::Down) {
InGameMenu.MoveDown();
}
else if (event.key.code == Keyboard::Up) {
InGameMenu.MoveUp();
}
else if (event.key.code == Keyboard::Enter) {
switch (InGameMenu.getSelectedItemIndex())
{
case 0://Recommencer
mainMap.restart();
break;
case 1://sauvegarder
mainMap.quickSave();
break;
case 2://charger sauvegarde
mainMap.loadSave();
break;
case 3://retour au menu principal
mainMenu.setOpened(true);
break;
default:
break;
}
InGameMenu.setOpened(false);
}
}
else {
if (event.key.code == Keyboard::Escape) {
InGameMenu.setOpened(true);
}
else {
eventList.push_back(event);
}
}
break;
default:
eventList.push_back(event);
break;
}
}
if (mainMenu.getOpened()) {
mainMenu.drawMe(*this);
}
else if (InGameMenu.getOpened()) {
InGameMenu.drawMe(*this);
}
else {
//cout << float(MainClock.getElapsedTime().asSeconds()) << " " << float(1 / 25) << endl;
//si la map est en cours de jeu
if (mainMap.getIsPlaying()) {
mainMap.update(*this, eventList);
mainMap.draw(*this);
}
else {
//si la map viens d'etre finis, on la réinitialise et on passe à la map suivante
cout << "switch map" << endl;
mainMap.setIsPlaying(true);
selectedMapIndex = (selectedMapIndex + 1) % maps.size();
mainMap = maps.at(selectedMapIndex);
}
}
MainClock.restart();
}
}
}
vector<Map> GameMaster::getMaps()
{
return maps;
}
void GameMaster::setMaps(vector<Map>m)
{
maps = m;
}
void GameMaster::addMap(Map m)
{
vector <Scene> saves = m.getSauvegardes();
Text t;
for (int i = 0; i < saves.size(); i++)
{
t = saves.at(i).getScoreString();
t.setFont(*font);
saves.at(i).setScoreString(t);
}
m.setSauvegardes(saves);
maps.push_back(m);
}
void GameMaster::setSelectedMapIndex(int i)
{
if (i >= maps.size() || i < 0)
i = 0;
selectedMapIndex = i;
}
int GameMaster::getSelectedMapIndex()
{
return selectedMapIndex;
}
Font* GameMaster::getFont()
{
return font;
}
void GameMaster::setFont(Font*f)
{
font = f;
}
<file_sep>#pragma once
#include "GameEntity.h"
class FocusableElement:public GameEntity// Classe mère des éléments que l'on peut cibler pour interagier
{
protected:
//Pas encore mis en application
bool focused = false;
bool locked = false;
public:
/* CONSTRUCTEURS */
FocusableElement();//Constructeur standard
/*
Les constructeurs suivant servent pour etre intégrés dans la construction de classes filles
*/
FocusableElement(bool);
FocusableElement(bool, bool, bool);
FocusableElement(bool, Vector2f, Texture, IntRect);
FocusableElement(bool, int, Vector2f, Texture, IntRect);
/* GETER SETER */
bool getFocused();
void setFocused(bool);
bool getLocked();
void setLocked(bool);
};
<file_sep>#include "Block.h"
#include "Scene.h"
Block::Block():MobileGameplayElement(false, false, true, true, true, 4, true, true, false, NOCOLOR)
{
//cout << traversable;
}
Block::Block(GameColor gc) : MobileGameplayElement(false, false, true, true, true, 4, true, true, false, gc)
{
//cout << traversable;
}
Block::Block(
bool paramvivant
):MobileGameplayElement(false, false, !paramvivant, !paramvivant, true, 4, true, true, false, NOCOLOR)
{
//cout <<"1speed:"<< speed << endl;
vivant = paramvivant;
//cout << traversable;
}
Block::Block(
bool paramvivant, GameColor gc
) : MobileGameplayElement(false, false, !paramvivant, !paramvivant, true, 4, true, true, false, gc)
{
//cout <<"2speed:"<< speed << endl;
vivant = paramvivant;
//cout << traversable;
}
Block::Block(
Vector2f position, Texture texture, IntRect textrect
)
:MobileGameplayElement( false, false, true, true, true, 4, true, true, false, position, texture, textrect, true, true, NOCOLOR)
{
//cout <<"3speed:"<< speed << endl;
traversable = false;
}
Block::Block(
bool paramvivant, Vector2f position, Texture texture,
IntRect textrect
)
: MobileGameplayElement(false, false, !paramvivant, 6, true, true, false, false, 1, position, texture, textrect, true, true, NOCOLOR)
//bool hateW, bool heavii, bool fly, double Speed, bool TraverseB,bool TraverseM, bool MarcheSurB, bool traversable, int intervalframe,Vector2f position, Texture texture, IntRect textrect, GameColor gc)
{
vivant = paramvivant;
//cout <<"4speed:"<< speed << endl;
traversable = false;
}
Block::Block(
GameColor gc, Vector2f position, Texture texture,
IntRect textrect
)
: MobileGameplayElement(false, false, true, 6, true, true, true, true, 1, position, texture, textrect, true, true, gc)
{
//cout << traversable;
//cout <<"5speed:"<< speed << endl;
traversable = false;
}
Block::Block(
bool paramvivant, GameColor gc, Vector2f position,
Texture texture, IntRect textrect
)
: MobileGameplayElement(false, false, true, 6, true, true, false, true, 1, position, texture, textrect, !paramvivant, !paramvivant, gc)
{
//cout <<"6speed:"<< speed << endl;
vivant = paramvivant;
traversable = false;
}
bool Block::getVivant()
{
return vivant;
}
void Block::setVivant(bool v)
{
vivant = v;
setFlying(!v);
setInhalable(!v);
setPaintable(!v);
}
void Block::update(Scene*scene)
{
initDirection();
bool playererGoingLeft = scene->getPlayer().goingLeft();
bool switchMovement = false;
if (SwitchMouvementClock.getElapsedTime().asSeconds() > SwitchMouvementDelay) {
switchMovement = true;
SwitchMouvementClock.restart();
}
//Detection de l'état et mise ŕ jour de ce dernier
switch (movingState)
{
case IDLE:
//cout << "IDLE ->";
switch (color)
{
case NOCOLOR:
//do nothing
break;
case ROUGE:
//change de direction
setMovingState(MOVING_UP);
SwitchMouvementClock.restart();
break;
case BLEU:
//change de direction
if (playererGoingLeft)
setMovingState(MOVING_LEFT);
else
setMovingState(MOVING_RIGHT);
SwitchMouvementClock.restart();
break;
case JAUNE:
//change de direction
if (playererGoingLeft)
setMovingState(MOVING_UP_LEFT);
else
setMovingState(MOVING_UP_RIGHT);
SwitchMouvementClock.restart();
break;
default:
//do nothing
break;
}
break;
case MOVING_LEFT:
//cout << "MOVING_LEFT ->";
switch (color)
{
case NOCOLOR:
//change de direction
setMovingState(IDLE);
break;
case ROUGE:
//change de direction
setMovingState(MOVING_UP);
break;
case BLEU:
if (!switchMovement)
setMovingState(MOVING_LEFT);
else
setMovingState(MOVING_RIGHT);
break;
case JAUNE:
//change de direction
if (playererGoingLeft)
setMovingState(MOVING_UP_LEFT);
else
setMovingState(MOVING_UP_RIGHT);
break;
default:
//do nothing
break;
}
break;
case MOVING_RIGHT:
//cout << "MOVING_RIGHT ->";
switch (color)
{
case NOCOLOR:
//change de direction
setMovingState(IDLE);
break;
case ROUGE:
//change de direction
setMovingState(MOVING_UP);
break;
case BLEU:
if (switchMovement)
setMovingState(MOVING_LEFT);
else
setMovingState(MOVING_RIGHT);
break;
case JAUNE:
//change de direction
if (playererGoingLeft)
setMovingState(MOVING_UP_LEFT);
else
setMovingState(MOVING_UP_RIGHT);
break;
default:
//do nothing
break;
}
break;
case MOVING_UP:
//cout << "MOVING_UP ->";
switch (color)
{
case NOCOLOR:
//change de direction
setMovingState(IDLE);
break;
case ROUGE:
if(!switchMovement)
setMovingState(MOVING_UP);
else
setMovingState(MOVING_DOWN);
break;
case BLEU:
//change de direction
if (playererGoingLeft)
setMovingState(MOVING_LEFT);
else
setMovingState(MOVING_RIGHT);
break;
case JAUNE:
//change de direction
if (playererGoingLeft)
setMovingState(MOVING_UP_LEFT);
else
setMovingState(MOVING_UP_RIGHT);
break;
default:
//do nothing
break;
}
break;
case MOVING_DOWN:
//cout << "MOVING_DOWN ->";
switch (color)
{
case NOCOLOR:
//change de direction
setMovingState(IDLE);
break;
case ROUGE:
if (switchMovement)
setMovingState(MOVING_UP);
else
setMovingState(MOVING_DOWN);
break;
case BLEU:
//change de direction
if (playererGoingLeft)
setMovingState(MOVING_LEFT);
else
setMovingState(MOVING_RIGHT);
break;
case JAUNE:
//change de direction
if (playererGoingLeft)
setMovingState(MOVING_UP_LEFT);
else
setMovingState(MOVING_UP_RIGHT);
break;
default:
//do nothing
break;
}
break;
case MOVING_UP_LEFT:
//cout << "MOVING_UP_LEFT ->";
switch (color)
{
case NOCOLOR:
//change de direction
movingState = IDLE;
break;
case ROUGE:
//change de direction
movingState = MOVING_UP;
break;
case BLEU:
//change de direction
if (playererGoingLeft)
movingState = MOVING_LEFT;
else
movingState = MOVING_RIGHT;
break;
case JAUNE:
if (!switchMovement)
movingState = MOVING_UP_LEFT;
else
movingState = MOVING_DOWN_RIGHT;
break;
default:
//do nothing
break;
}
break;
case MOVING_UP_RIGHT:
//cout << "MOVING_UP_RIGHT ->";
switch (color)
{
case NOCOLOR:
//change de direction
movingState = IDLE;
break;
case ROUGE:
//change de direction
movingState = MOVING_UP;
break;
case BLEU:
//change de direction
if (playererGoingLeft)
movingState = MOVING_LEFT;
else
movingState = MOVING_RIGHT;
break;
case JAUNE:
if (!switchMovement)
movingState = MOVING_UP_RIGHT;
else
movingState = MOVING_DOWN_LEFT;
break;
default:
//do nothing
break;
}
break;
case MOVING_DOWN_LEFT:
//cout << "MOVING_DOWN_LEFT ->";
switch (color)
{
case NOCOLOR:
//change de direction
movingState = IDLE;
break;
case ROUGE:
//change de direction
movingState = MOVING_UP;
break;
case BLEU:
//change de direction
if (playererGoingLeft)
movingState = MOVING_LEFT;
else
movingState = MOVING_RIGHT;
break;
case JAUNE:
if (switchMovement)
movingState = MOVING_UP_RIGHT;
else
movingState = MOVING_DOWN_LEFT;
break;
default:
//do nothing
break;
}
break;
case MOVING_DOWN_RIGHT:
//cout << "MOVING_DOWN_RIGHT ->";
switch (color)
{
case NOCOLOR:
//change de direction
movingState = IDLE;
break;
case ROUGE:
//change de direction
movingState = MOVING_UP;
break;
case BLEU:
//change de direction
if (playererGoingLeft)
movingState = MOVING_LEFT;
else
movingState = MOVING_RIGHT;
break;
case JAUNE:
if (switchMovement)
movingState = MOVING_UP_LEFT;
else
movingState = MOVING_DOWN_RIGHT;
break;
default:
//do nothing
break;
}
break;
default:
//cout << "default ->";
movingState = IDLE;
break;
}
/**/
//mise a jour du deplacement en fonction de l'etat de deplacement
switch (movingState)
{
case IDLE:
//cout << " IDLE" << endl;
break;
case MOVING_LEFT:
//cout << " MOVING_LEFT" << endl;
moveTo(Direction::GAUCHE);
break;
case MOVING_RIGHT:
//cout << " MOVING_RIGHT" << endl;
moveTo(Direction::DROITE);
break;
case MOVING_UP:
//cout << " MOVING_UP" << endl;
moveTo(Direction::HAUT);
break;
case MOVING_DOWN:
//cout << " MOVING_DOWN" << endl;
moveTo(Direction::BAS);
break;
case MOVING_UP_LEFT:
//cout << " MOVING_UP_LEFT" << endl;
moveTo(Direction::HAUT);
moveTo(Direction::GAUCHE);
break;
case MOVING_UP_RIGHT:
//cout << " MOVING_UP_RIGHT" << endl;
moveTo(Direction::HAUT);
moveTo(Direction::DROITE);
break;
case MOVING_DOWN_LEFT:
//cout << " MOVING_DOWN_LEFT" << endl;
moveTo(Direction::BAS);
moveTo(Direction::GAUCHE);
break;
case MOVING_DOWN_RIGHT:
//cout << " MOVING_DOWN_RIGHT" << endl;
moveTo(Direction::BAS);
moveTo(Direction::DROITE);
break;
default:
//cout << " default" << endl;
break;
}
//ProtectWalkingOnEntity
if (movingState != IDLE) {
GameObject* walker = scene->testEncounter(this, Direction::HAUT,20);
if (walker) {
//cout << "colliding walker" << endl;
MobileGameplayElement* dynamicWalker = dynamic_cast<MobileGameplayElement*>(walker);
if (dynamicWalker) {
//cout << "colliding dynamicWalker walker" << endl;
FloatRect blockBounds = this->getSprite()->getGlobalBounds();
FloatRect localGB = dynamicWalker->getSprite()->getGlobalBounds();
float LocalDelta = (blockBounds.top - localGB.height) - localGB.top;
dynamicWalker->getSprite()->move(Vector2f(0, LocalDelta));
}
else {
Player* dynamicplayingWalker = dynamic_cast<Player*>(walker);
if (dynamicplayingWalker) {
//cout << "colliding dynamicplayingWalker walker" << endl;
FloatRect blockBounds = this->getSprite()->getGlobalBounds();
FloatRect localGB = dynamicplayingWalker->getSprite()->getGlobalBounds();
float LocalDelta = (blockBounds.top - localGB.height) - localGB.top;
dynamicplayingWalker->getSprite()->move(Vector2f(0, LocalDelta));
}
}
}
}
//updatePos(9.8 / 12);
/**/
MobileGameplayElement::update(scene);
}
<file_sep>#pragma once
#include "GameObject.h"
class Mur:public GameObject
{
public:
/* CONSTRUCTEURS */
Mur();//Constructeur standard
Mur(Vector2f, Texture, IntRect);//Constructeur utilisé dans la génération de la scene
/* Constructeurs alternatifs */
Mur(Vector2f);
//void update();
};
<file_sep>#pragma once
#include "GameEntity.h"
class OneWay:public GameEntity
{
protected:
enum Direction blockDirection;//Direction bloquée par le OneWay
public:
/* CONSTRUCTEURS */
OneWay();//Constructeur standard
OneWay(Direction,Vector2f, Texture, IntRect);//Constructeur utilisé dans la génération de la scene
/* Constructeurs alternatifs */
OneWay(Direction);
/* GETER SETER */
Direction getBlockDirection();
void setBlockDirection(Direction);
};
<file_sep>#pragma once
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace sf;
using namespace std;
class MainMenu//Choisir les maps a jouer
{
protected:
int SelectedItemIndex = 0;
vector <Text> elements;
bool opened = false;
Text titre;
public:
MainMenu(int, int, Font*);
MainMenu(int, int, Font*,String);
MainMenu(int, int, Font*, vector<String>);
MainMenu(int, int,Font*,vector<String>, String);
void drawMe(RenderWindow& GM);
void MoveUp();
void MoveDown();
bool getOpened();
void setOpened(bool);
int getSelectedItemIndex();
};
<file_sep>#include "GameplayElement.h"
<file_sep>#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include "Mur.h"
#include "Player.h"
#include "OneWay.h"
#include "Switch.h"
#include "spike.h"
#include "Bouteille.h"
#include "Rocher.h"
#include "Goal.h"
#include "Block.h"
using namespace std;
using namespace sf;
enum sceneOutput {
RienASignaler = -1,
QuickSave = -2,
ReloadPrevious = -3,
Exit = -4,
Restart = 0
};
class Scene
{
protected:
int score;
Text ScoreString;
vector <GameObject *> grabbablesETInhalables;
vector <Mur*> murs;
vector <OneWay*> oneWays;
vector <spike*> spikes;
vector <Bouteille*> bouteilles;
vector <Switch*> switches;
vector <Goal*> goals;
Player *player;
Vector2f spawnPoint;
public:
/* CONSTRUCTEURS */
Scene();//Constructeur standard
Scene(int, vector <vector <enum ElementTypes>>);
Scene(Scene*);
/* FONCTIONS MEMBRES DE LA CLASSE */
void generate(vector <vector <enum ElementTypes>>);
void draw(RenderWindow&);
GameObject* testCollide(GameObject*, Direction);
GameObject* testEncounter(GameObject*, Direction,int);
int update(RenderWindow&,vector <Event>);
bool walkOn(GameObject*, vector <GameObject*>);
/* GETER SETER */
int getScore();
void setScore(int);
Text getScoreString();
void setScoreString(Text);
Player getPlayer();
void setPlayer(Player);
Vector2f getSpawnPoint();
void setSpawnPoint(Vector2f);
vector <GameObject*> getGrabbablesETInhalables();
void setGrabbablesETInhalables(vector <GameObject*>);
vector <Bouteille*> getBouteilles();
void setBouteilles(vector <Bouteille*>);
vector <spike*> getSpikes();
void setSpikes(vector <spike*>);
vector <Switch*> getSwiches();
void setSwiches(vector <Switch*>);
vector <Mur*> getMurs();
void setMurs(vector <Mur*>);
vector <OneWay*> getOneWays();
void setOneWays(vector <OneWay*>);
vector <Goal*> getGoals();
void setGoals(vector <Goal*>);
};
<file_sep>#include "PaintableElement.h"
PaintableElement::PaintableElement():FocusableElement()
{
paintable = false;
inhalable = false;
}
PaintableElement::PaintableElement(
bool paintbl, bool inhalabl
):FocusableElement()
{
paintable = paintbl;
inhalable = inhalabl;
}
PaintableElement::PaintableElement(
bool paintbl, bool inhalabl, bool trav
) :FocusableElement(trav)
{
paintable = paintbl;
inhalable = inhalabl;
}
PaintableElement::PaintableElement(
bool paintbl, bool inhalabl, bool trav, GameColor gc
) :FocusableElement(trav)
{
paintable = paintbl;
inhalable = inhalabl;
setColor(gc);
}
PaintableElement::PaintableElement(
bool paintbl, bool inhalabl, bool trav, Vector2f pos, Texture tex,
IntRect rect
) : FocusableElement(trav, pos, tex, rect)
{
paintable = paintbl;
inhalable = inhalabl;
}
PaintableElement::PaintableElement(
bool paintbl, bool inhalabl, bool trav, int intervalFramce,
Vector2f pos, Texture tex, IntRect rect
) : FocusableElement(trav, intervalFramce, pos, tex, rect)
{
paintable = paintbl;
inhalable = inhalabl;
}
PaintableElement::PaintableElement(
bool paintbl, bool inhalabl, GameColor gcolor
)
{
paintable = paintbl;
inhalable = inhalabl;
setColor(gcolor);
}
PaintableElement::PaintableElement(
bool paintbl, bool inhalabl, GameColor gcolor, bool trav,
Vector2f pos, Texture tex, IntRect rect
) : FocusableElement(trav, pos, tex, rect)
{
paintable = paintbl;
inhalable = inhalabl;
setColor(gcolor);
}
PaintableElement::PaintableElement(
bool paintbl, bool inhalabl, GameColor gcolor, bool trav,
int intervalFrame, Vector2f pos, Texture tex, IntRect rect
) : FocusableElement(trav, intervalFrame, pos, tex, rect)
{
paintable = paintbl;
inhalable = inhalabl;
setColor(gcolor);
}
bool PaintableElement::getPaintable()
{
return paintable;
}
void PaintableElement::setPaintable(bool p)
{
paintable = p;
}
GameColor PaintableElement::getColor()
{
return color;
}
void PaintableElement::setColor(GameColor c)
{
color = c;
this->sprite.setColor( getColorFromEnum(c) );
}
bool PaintableElement::getInhalable()
{
return inhalable;
}
void PaintableElement::setInhalable(bool i)
{
inhalable = i;
}
<file_sep>#pragma once
#include "PaintableElement.h"
class Bouteille:public PaintableElement
{
public:
/* CONSTRUCTEURS */
Bouteille();//Constructeur standard
Bouteille(bool, Vector2f, Texture, IntRect);//Constructeur utilisable dans la génération de la scene
Bouteille(bool, GameColor, Vector2f, Texture, IntRect);//Constructeur utilisable dans la génération de la scene
/* Constructeurs alternatifs */
Bouteille(GameColor);
Bouteille(bool);
Bouteille(bool, GameColor);
};
<file_sep>#include "Switch.h"
#include "Scene.h"
Switch::Switch():GameEntity()
{
}
Switch::Switch(Vector2f pos, Texture tex, IntRect rect) : GameEntity(false, pos, tex, rect)
{
}
void Switch::interact(Scene* scene)
{
vector <Bouteille*> bouteilles = scene->getBouteilles();
GameColor c;
for (int i = 0; i < bouteilles.size(); i++)
{
c = bouteilles.at(i)->getColor();
switch (c)
{
case NOCOLOR:
c = ROUGE;
break;
case ROUGE:
c = BLEU;
break;
case BLEU:
c = JAUNE;
break;
case JAUNE:
c = ROUGE;
break;
default:
c = ROUGE;
break;
}
bouteilles.at(i)->setColor(c);
}
scene->setBouteilles(bouteilles);
}
<file_sep>#include "GameObject.h"
#include "Scene.h"
GameObject::GameObject()
{
}
GameObject::GameObject(Vector2f vect, Texture tex, IntRect rect)
{
sprite.setPosition(vect);
setTexture(tex);
setTextureRect(rect);
}
GameObject::GameObject(int anim, Vector2f vect, Texture tex, IntRect rect)
{
animationframes = anim;
sprite.setPosition(vect);
setTexture(tex);
setTextureRect(rect);
}
void GameObject::drawMe(RenderWindow &R)
{
//cout << "DrawMe\n";
if (animationframes >= 2 && innerAnnimationClock.getElapsedTime().asSeconds() >= frequence) {
animationStep++;
animationStep = (animationStep % animationframes) ;
IntRect tr = sprite.getTextureRect();
tr.left = textureRect.left + (animationStep * tr.width);
sprite.setTextureRect(tr);
innerAnnimationClock.restart();
}
R.draw(sprite);
}
void GameObject::update(Scene *)
{
}
Sprite* GameObject::getSprite()
{
return &sprite;
}
void GameObject::setSprite(Sprite s)
{
sprite = s;
}
IntRect* GameObject::getTextureRect()
{
return &textureRect;
}
void GameObject::setTextureRect(IntRect t)
{
textureRect = t;
sprite.setTextureRect(textureRect);
}
Texture* GameObject::getTexture()
{
return &texture;
}
void GameObject::setTexture(Texture t)
{
texture = t;
sprite.setTexture(texture);
}
int GameObject::getAnimationframes()
{
return animationframes;
}
void GameObject::setAnimationframes(int i)
{
animationframes = i;
}
Color getColorFromEnum(GameColor gc) {
switch (gc)
{
case GameColor::NOCOLOR:
return Color::White;
break;
case GameColor::ROUGE:
return Color::Red;
break;
case GameColor::BLEU:
return Color::Blue;
break;
case GameColor::JAUNE:
return Color::Yellow;
break;
default:
return Color::White;
break;
}
}
GameColor getEnumFromColor(Color C) {
if (C == Color::Red) {
return GameColor::ROUGE;
}
else if (C == Color::Blue) {
return GameColor::BLEU;
}
else if (C == Color::Yellow) {
return GameColor::JAUNE;
}
else {
return GameColor::NOCOLOR;
}
}
FloatRect getInnerBounds(Direction D, FloatRect Original) {
int margin = 30;
FloatRect retour = Original;
switch (D)
{
case Direction::HAUT:
retour.height = margin;
break;
case Direction::BAS:
retour.top = retour.top + retour.height - margin;
retour.height = margin;
break;
case Direction::GAUCHE:
retour.width = margin;
break;
case Direction::DROITE:
retour.left = retour.left + retour.width - margin;
retour.width = margin;
break;
default:
break;
}
return retour;
}
FloatRect getOuterBounds(Direction D, FloatRect Original, int margin) {
FloatRect retour = Original;
switch (D)
{
case Direction::HAUT:
retour.top = retour.top - margin;
retour.height = margin;
break;
case Direction::BAS:
retour.top = retour.top + retour.height;
retour.height = margin;
break;
case Direction::GAUCHE:
retour.left = retour.left - margin;
retour.width = margin;
break;
case Direction::DROITE:
retour.left = retour.left + retour.width;
retour.width = margin;
break;
default:
break;
}
return retour;
}<file_sep>#pragma once
#include "GameEntity.h"
class Goal :public GameEntity
{
public:
/* CONSTRUCTEURS */
Goal();//Constructeur standard
Goal(Vector2f, Texture, IntRect);//Constructeur utilisé dans la génération de la scene
};
| e9a79c640b8974f6b0c64f542d732975be482087 | [
"C++"
] | 43 | C++ | arthurmougin/projetSFML | e0b4835dc75603cfc41afd4b86f40602e196c300 | 0c210fafe4b6136acdb31247f9a129d5e9653c44 |
refs/heads/master | <repo_name>scherbinin/HW_coursera_algorithms<file_sep>/src/test/java/week3/collinearePoints/PointTest.java
package week3.collinearePoints;
import org.junit.Test;
import week3.collinearPoints.Point;
/**
* Created by scher on 14.08.2019.
*/
public class PointTest {
@Test
public void test() {
Point point1 = new Point(1,4);
Point point2 = new Point(9,0);
Point point3 = new Point(1,4);
double slopePQ = point1.slopeTo(point2);
double slopePR = point1.slopeTo(point3);
double compare = point1.slopeOrder().compare(point2, point3);
}
}
<file_sep>/src/test/java/week3/collinearePoints/FastCollinearPointsTest.java
package week3.collinearePoints;
import org.junit.Test;
import week3.collinearPoints.FastCollinearPoints;
import week3.collinearPoints.LineSegment;
import week3.collinearPoints.Point;
import static org.junit.Assert.assertEquals;
public class FastCollinearPointsTest {
private FastCollinearPoints fastCollinearPoints;
@Test
public void testCalculationOfCollinearPoints_whenExist3Lines_expectedOnlyOneLineSegment() {
fastCollinearPoints = new FastCollinearPoints(get5CollinearPointAnd());
int size = fastCollinearPoints.numberOfSegments();
LineSegment[] segments = fastCollinearPoints.segments();
assertEquals(3,size);
}
private Point[] get5CollinearPointAnd() {
Point[] points = new Point[12];
points[0] = new Point(1,1);
points[1] = new Point(4,4);
points[2] = new Point(2,2);
points[3] = new Point(3,3);
points[4] = new Point(5,5);
points[5] = new Point(7,7);
points[6] = new Point(2,7);
points[7] = new Point(3,7);
points[8] = new Point(4,7);
points[9] = new Point(4,3);
points[10] = new Point(5,3);
points[11] = new Point(6,3);
return points;
}
}
<file_sep>/README.md
# HW_coursera_algorithms
The home works for cource from coursera: Algorithms, Part I, Part II. Temporary repo, will be deleted when cources will be finished
<file_sep>/src/main/java/week3/mergeSort/Permutations.java
package week3.mergeSort;
/**
* Created by scher on 10.08.2019.
* <p>
* An inversion in an array a[\,]a[] is a pair of entries a[i]a[i] and a[j]a[j] such that i < ji<j but a[i] > a[j]a[i]>a[j].
* Given an array, design a linearithmic algorithm to count the number of inversions.
*/
public class Permutations {
int permutations;
public int sort(Integer[] arr) {
sort(arr, 0, arr.length);
return permutations;
}
private void sort(Integer[] arr, int left, int right) {
int mid = (right - left) / 2 + left;
if (right - left > 1) {
sort(arr, left, mid);
sort(arr, mid, right);
}
permutations += merge(arr, left, right, mid);
}
public int merge(Integer[] arr, Integer left, Integer right, int mid) {
int leftIndex = left;
int midIndex = mid;
int permutations = 0;
Integer[] aux = new Integer[right - left];
for (int i = 0; i < right - left; i++) {
if (midIndex == right) {
aux[i] = arr[leftIndex++];
} else if (leftIndex == mid) {
aux[i] = arr[midIndex++];
} else if (arr[leftIndex] < arr[midIndex]) {
aux[i] = arr[leftIndex++];
} else {
aux[i] = arr[midIndex++];
permutations += mid - leftIndex;
}
}
System.arraycopy(aux, 0, arr, left, aux.length);
return permutations;
}
}
<file_sep>/src/main/java/week2/queues/Deque.java
package week2.queues;
import java.util.NoSuchElementException;
public class Deque<Item> implements Iterable<Item> {
private Node root;
private Node last;
private int size;
// construct an empty deque
public Deque() {
}
// is the deque empty?
public boolean isEmpty() {
return size == 0;
}
// return the number of items on the deque
public int size() {
return size;
}
// add the item to the front
public void addFirst(Item item) {
if (item == null)
throw new IllegalArgumentException();
Node newNode = new Node(item, root, null);
if (isEmpty()) {
root = newNode;
last = newNode;
} else {
root.setPrev(newNode);
root = newNode;
}
size++;
}
// add the item to the back
public void addLast(Item item) {
if (item == null)
throw new IllegalArgumentException();
Node newLast = new Node(item, null, last);
if (isEmpty()) {
root = newLast;
last = newLast;
}
last.setNext(newLast);
last = newLast;
size++;
}
// remove and return the item from the front
public Item removeFirst() {
if (isEmpty())
throw new NoSuchElementException();
Item value = root.getValue();
root = root.getNext();
if (root != null)
root.setPrev(null);
size--;
return value;
}
// remove and return the item from the back
public Item removeLast() {
if (isEmpty())
throw new NoSuchElementException();
Item value = last.getValue();
last = last.getPrev();
if (last != null)
last.setNext(null);
size--;
return value;
}
// return an iterator over items in order from front to back
public java.util.Iterator<Item> iterator() {
return new Iterator();
}
private class Iterator implements java.util.Iterator<Item> {
Node node = root;
@Override
public boolean hasNext() {
return node != null;
}
@Override
public Item next() {
if (node == null)
throw new NoSuchElementException();
Item value = node.getValue();
node = node.getNext();
return value;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
private class Node {
Item value;
Node next;
Node prev;
Node(Item value, Node next, Node prev) {
this.value = value;
this.next = next;
this.prev = prev;
}
Item getValue() {
return value;
}
Node getNext() {
return next;
}
void setNext(Node next) {
this.next = next;
}
Node getPrev() {
return prev;
}
void setPrev(Node prev) {
this.prev = prev;
}
}
// unit testing (required)
public static void main(String[] args) {
}
}<file_sep>/src/main/java/week1/unions/Percolation.java
package week1.unions;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.WeightedQuickUnionUF;
public class Percolation {
private WeightedQuickUnionUF unionEngine;
private char[] sites;
private final int N;
private final int TOP_SITE = 0;
private final int BOTTOM_SITE = 1;
private final char BLOCKED_SITE = '0';
private int numberOfOpenSites = 0;
// creates n-by-n grid, with all sites initially blocked
public Percolation(int n) {
if (n < 1)
throw new IllegalArgumentException();
N = n;
int size = n * n;
//Zero index - is a virtual sites for top row
//SIZE+1 index - is virtual sites for bottom row
unionEngine = new WeightedQuickUnionUF(size + 2);
sites = new char[size + 2];
sites[TOP_SITE] = TOP_SITE;
sites[BOTTOM_SITE] = BOTTOM_SITE;
for (int i = 2; i < size + 2; i++)
sites[i] = BLOCKED_SITE;
}
// opens the sites (row, col) if it is not open already
public void open(int row, int col) {
validateBoundaries(row, col);
if (isOpen(row, col))
return;
sites[getIndexFlatArray(row, col)] = '*';
numberOfOpenSites++;
if (row == 1) {
unionEngine.union(getIndexFlatArray(row, col), TOP_SITE);
}
if (row == N) {
unionEngine.union(BOTTOM_SITE, getIndexFlatArray(row, col));
}
//percolate it to all of its adjacent open sites.
percolate(row - 1, col, row, col);
percolate(row + 1, col, row, col);
percolate(row, col - 1, row, col);
percolate(row, col + 1, row, col);
}
// is the sites (row, col) open?
public boolean isOpen(int row, int col) {
validateBoundaries(row, col);
return sites[getIndexFlatArray(row, col)] != BLOCKED_SITE;
}
// is the sites (row, col) full?
public boolean isFull(int row, int col) {
//A full sites is an open sites that can be connected to an open sites in the top row
validateBoundaries(row, col);
return unionEngine.connected(getIndexFlatArray(row, col), TOP_SITE);
}
// returns the number of open sites
public int numberOfOpenSites() {
return numberOfOpenSites;
}
// does the system percolate?
public boolean percolates() {
return unionEngine.connected(TOP_SITE, BOTTOM_SITE);
}
private void percolate(int row, int col, int actualRow, int actualCol) {
if (inBoundaries(row, col) && isOpen(row, col)) {
unionEngine.union(getIndexFlatArray(row, col), getIndexFlatArray(actualRow, actualCol));
}
}
private int getIndexFlatArray(int row, int column) {
return N * (row - 1) + column + 1;
}
private void validateBoundaries(int row, int col) {
if (!inBoundaries(row, col))
throw new IllegalArgumentException();
}
private boolean inBoundaries(int row, int col) {
if (row < 1 || row > N || col < 1 || col > N)
return false;
return true;
}
//Simple visualization for debug
public void print() {
for (int i = 0; i < N * N; i++) {
if (i % N == 0) {
StdOut.print("\n");
}
StdOut.print(sites[i + 2] + " ");
}
StdOut.print("\n\n");
}
// test client (optional)
public static void main(String[] args) {
}
}
<file_sep>/src/test/java/week1/searches/BitonicSearchTest.java
package week1.searches;
import org.junit.Before;
import org.junit.Test;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
/**
* Created by scher on 01.08.2019.
*/
public class BitonicSearchTest {
private BitonicSearch underTestSearchEngine;
@Before
public void setup() {
underTestSearchEngine = new BitonicSearch();
}
//The input array consists of distinct digits, the first part of array is ascending till some maximum digit and second part is descending.
@Test
public void executeBitonicSearch_whenSortedArrayWithMoreThatOneElement_expectedFoundValue() {
final int[] array1 = {-1, 0, 1, 7, 6, 5, 4, 3, 2, -2, -3, -7, -11};
IntStream.range(0, array1.length - 1).forEach(index ->
assertEquals(underTestSearchEngine.bitonicSearch(array1, array1[index]), index));
}
@Test(expected = IllegalArgumentException.class)
public void executeBitonicSearch_whenInputArrayIsNotBitonic1_expectedException() {
final int[] arrayWithoutDuplicationsButNotBitonic1 = {-1, 9, 1, 7, 6, 5, 4, 3, 2, -2, -3, -7};
IntStream.range(0, arrayWithoutDuplicationsButNotBitonic1.length - 1).forEach(index ->
assertEquals(underTestSearchEngine.bitonicSearch(arrayWithoutDuplicationsButNotBitonic1, arrayWithoutDuplicationsButNotBitonic1[index]), index));
}
@Test(expected = IllegalArgumentException.class)
public void executeBitonicSearch_whenInputArrayIsNotBitonic2_expectedException() {
final int[] arrayWithoutDuplicationsButNotBitonic2 = {-1, 0, 1, 7, 6, 5, 4, 3, 2, -2, 2, -7};
IntStream.range(0, arrayWithoutDuplicationsButNotBitonic2.length - 1).forEach(index ->
assertEquals(underTestSearchEngine.bitonicSearch(arrayWithoutDuplicationsButNotBitonic2, arrayWithoutDuplicationsButNotBitonic2[index]), index));
}
@Test(expected = IllegalArgumentException.class)
public void executeBitonicSearch_whenInputArrayWithDuplications_expectedException() {
final int[] array1 = {-1, 0, 1, 7, 6, 5, 4, 3, 2, -2, -3, -7, -1};
IntStream.range(0, array1.length - 1).forEach(index ->
assertEquals(underTestSearchEngine.bitonicSearch(array1, array1[index]), index));
}
@Test(expected = IllegalArgumentException.class)
public void executeBitonicSearch_whenInputArrayIsNotBitonic_expectedException() {
final int[] arrayWithDuplications = {-1, 0, 1, 7, 6, 5, 4, 3, 2, -2, -3, -7, -1};
final int[] arrayWithoutDuplicationsButNotBitonic1 = {-1, 9, 1, 7, 6, 5, 4, 3, 2, -2, -3, -7};
final int[] arrayWithoutDuplicationsButNotBitonic2 = {-1, 0, 1, 7, 6, 5, 4, 3, 2, -2, 2 -7};
IntStream.range(0, arrayWithDuplications.length - 1).forEach(index ->
assertEquals(underTestSearchEngine.bitonicSearch(arrayWithDuplications, arrayWithDuplications[index]), index));
IntStream.range(0, arrayWithoutDuplicationsButNotBitonic1.length - 1).forEach(index ->
assertEquals(underTestSearchEngine.bitonicSearch(arrayWithoutDuplicationsButNotBitonic1, arrayWithoutDuplicationsButNotBitonic1[index]), index));
IntStream.range(0, arrayWithoutDuplicationsButNotBitonic2.length - 1).forEach(index ->
assertEquals(underTestSearchEngine.bitonicSearch(arrayWithoutDuplicationsButNotBitonic2, arrayWithoutDuplicationsButNotBitonic2[index]), index));
}
@Test
public void executeAscendingBinarySearch_whenSortedArrayWithMoreThatOneElement_expectedFoundValue() {
final int[] array1 = {1, 3, 5, 6, 7, 8, 9};
final int[] array2 = {1, 3, 5, 6, 7, 8};
IntStream.range(0, array1.length - 1).forEach(index ->
assertEquals(underTestSearchEngine.ascendingBinarySearch(array1, array1[index], 0, array1.length), index));
IntStream.range(0, array2.length - 1).forEach(index ->
assertEquals(underTestSearchEngine.ascendingBinarySearch(array2, array2[index], 0, array1.length), index));
}
@Test
public void executeDescendingBinarySearch_whenSortedArrayWithMoreThatOneElement_expectedFoundValue() {
final int[] array1 = {9, 7, 5, 4, 3, 2};
final int[] array2 = {9, 7, 5, 4, 3, 2, 0};
IntStream.range(0, array1.length - 1).forEach(index ->
assertEquals(underTestSearchEngine.descendingBinarySearch(array1, array1[index], 0, array1.length), index));
IntStream.range(0, array2.length - 1).forEach(index ->
assertEquals(underTestSearchEngine.descendingBinarySearch(array2, array2[index], 0, array1.length), index));
}
@Test
public void executeFindMaxBinarySearch_whenBionicArrayMoreThatOneElement_expectedFoundValue() {
final int[] array1 = {-1, 0, 1, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2};
final int expectedIndex = 3;
int actualIndex = underTestSearchEngine.maxBinarySearch(array1);
assertEquals(expectedIndex, actualIndex);
}
}
<file_sep>/src/test/java/week3/mergeSort/HelperTest.java
package week3.mergeSort;
import org.junit.Test;
/**
* Created by scher on 10.08.2019.
*/
public class HelperTest {
@Test
public void helperTest() {
int[] arr = {1, 4, 0, 7, 2, 9, 8, 10};
int a = (new Helper()).permutations(arr);
}
}
<file_sep>/src/main/java/week3/collinearPoints/Point.java
package week3.collinearPoints;
import edu.princeton.cs.algs4.StdDraw;
import java.util.Comparator;
public class Point implements Comparable<Point> {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// draws this point
public void draw() {
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.filledCircle(x, y, 3);
}
// draws the line segment from this point to that point
public void drawTo(Point that) {
draw();
that.draw();
StdDraw.setPenColor(StdDraw.RED);
StdDraw.line(this.x, this.y, that.x, that.y);
}
// string representation
public String toString() {
return String.format("point: (%d, %d)", x, y);
}
// compare two points by y-coordinates, breaking ties by x-coordinates
public int compareTo(Point that) {
if (this.y == that.y) {
return Double.compare(this.x, that.x);
} else if (this.y < that.y) {
return -1;
}
return 1;
}
// the slope between this point and that point
public double slopeTo(Point that) {
double deltaX = that.x - this.x;
double deltaY = that.y - this.y;
if (deltaX == 0 && deltaY == 0)
return Double.NEGATIVE_INFINITY;
if (deltaX == 0)
return Double.POSITIVE_INFINITY;
double slope = deltaY / deltaX;
// Because -0.0 not equal 0.0. But they are should be equal
if (slope == 0)
return 0;
return slope;
}
// compare two points by slopes they make with this point
public Comparator<Point> slopeOrder() {
return (o1, o2) -> {
double slope1 = slopeTo(o1);
double slope2 = slopeTo(o2);
if (o1 == o2)
return 0;
return Double.compare(slope1, slope2);
};
}
}<file_sep>/src/test/java/week2/PermutationTest.java
package week2;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* Created by scher on 07.08.2019.
*/
public class PermutationTest {
@Test
public void executeAreTheSame_whenTwoArraysHasTheSameElementsInDiffOrde_expectedTrue() {
Integer[] actual = {2, 7, 1, 0, 3, 4, 6, 5, -9,11};
Integer[] expected = {2, 7, 4, 0, 3, 1, 6, 5, -9,11};
assertTrue(new Permutation().areTheSame(actual,expected));
}
}
<file_sep>/src/test/java/week5/PointSETTest.java
package week5;
import org.junit.Test;
import week5.intersectionsOfGeometricPrimitives.PointSET;
import week5.intersectionsOfGeometricPrimitives.primitives.Point2D;
import week5.intersectionsOfGeometricPrimitives.primitives.RectHV;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
public class PointSETTest {
@Test
public void executeRange_when2PointsAreIntoAnd2OutsideRectangle_expectedRightBehavior(){
PointSET testedContainer = new PointSET();
Point2D point1 = new Point2D(0,0);
Point2D point2 = new Point2D(2,2);
Point2D point3 = new Point2D(2,3);
Point2D point4 = new Point2D(4,4);
testedContainer.insert(point1);
testedContainer.insert(point2);
testedContainer.insert(point3);
testedContainer.insert(point4);
Iterable<Point2D> actual = testedContainer.range(new RectHV(1, 1, 3, 3));
List<Point2D> expected = Arrays.asList(point2, point3);
assertArrayEquals(expected.toArray(), convertToList(actual).toArray());
}
@Test
public void executeNearest_when5DifferentPointsExist_expectedRightBehavior(){
PointSET testedContainer = new PointSET();
Point2D point1 = new Point2D(0,0);
Point2D point2 = new Point2D(2,2);
Point2D point3 = new Point2D(2,3);
Point2D point4 = new Point2D(4,4);
Point2D point5 = new Point2D(10,5);
testedContainer.insert(point1);
testedContainer.insert(point2);
testedContainer.insert(point3);
testedContainer.insert(point4);
testedContainer.insert(point5);
Point2D actual = testedContainer.nearest(new Point2D(7, 5));
Point2D expected = point5;
assertEquals(expected, actual);
}
private List<Point2D> convertToList(Iterable<Point2D> actual) {
List<Point2D> actualList = new ArrayList<>();
for (Point2D point2D : actual) {
actualList.add(point2D);
}
return actualList;
}
}
<file_sep>/src/test/java/week3/mergeSort/MergeSortTest.java
package week3.mergeSort;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertArrayEquals;
/**
* Created by scher on 09.08.2019.
*/
public class MergeSortTest {
// @Test
// public void testMergingOfTwoSortedArrays2() {
// Integer[] arr = {-1,2, 3,-2,1,10,12,};
// Integer[] rez = new Integer[arr.length];
//
// new MergeSort().merge(rez, arr, 0, arr.length, 3);
//
// }
@Test
public void testAscendingSorting() {
List<Integer> initialData = Arrays.asList(2, 7, 1, 0, 3, 12, 434, -99871, 4, 4, 6, 5, -9,11,-99);
Integer[] actual = new Integer[initialData.size()];
Integer[] expected = new Integer[initialData.size()];
initialData.toArray(actual);
Arrays.sort(initialData.toArray(expected));
new MergeSort().sort(actual);
assertArrayEquals(actual, expected);
}
}
<file_sep>/src/test/java/week3/quickSort/quickSortTest.java
package week3.quickSort;
import org.junit.Test;
public class quickSortTest {
@Test
public void testPartionWorkability() {
QuickSort quickSort = new QuickSort();
int[] arr = {10, 1, 23, 5, 45, 3, 46, 7, 2, 3, -1, 16};
quickSort.sort(arr);
for (int item : arr) {
System.out.print(item + ", ");
}
}
}
<file_sep>/src/test/java/week2/queues/QueueTest.java
package week2.queues;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by scher on 04.08.2019.
*/
public class QueueTest {
private Queue<Integer> queue;
@Before
public void setup() {
queue = new Queue<>();
}
@Test
public void testQueue() {
int[] actual = {1, 2, 3, 4, 5, 6, 1};
int[] expected = {1, 2, 3, 4, 5, 6, 1};
for (int item : actual) {
queue.push(item);
}
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i],(int)queue.pop());
}
assertEquals(0, queue.size());
}
}
<file_sep>/src/main/java/week2/simpleSortings/SelectingSort.java
package week2.simpleSortings;
import java.util.Comparator;
/**
* Created by scher on 07.08.2019.
*/
public class SelectingSort implements Comparator<Integer> {
public void sort(Integer[] arr) {
for(int leftIndex = 0; leftIndex < arr.length; leftIndex++) {
for (int i = leftIndex+1; i< arr.length; i++) {
if(isLess(arr[i], arr[leftIndex])) {
swap(arr, i, leftIndex);
}
}
}
}
private void swap(Integer[] arr, int i, int j) {
int buf = arr[i];
arr[i] = arr[j];
arr[j] = buf;
}
private boolean isLess(int one, int two) {
if (compare(one, two) < 1)
return true;
return false;
}
@Override
public int compare(Integer o1, Integer o2) {
if (o1 < o2) return -1;
else if (o1 == o2) return 0;
else return 1;
}
}
<file_sep>/src/test/java/week4/PazzleByAstart/SolverTest.java
package week4.PazzleByAstart;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SolverTest {
@Test
public void executeSolve_whenBoardNeedJust7Moves_expectTheSuccessAfter7Moves() {
int[][] tilesArr = {{1, 0, 3},
{7, 2, 6},
{5, 4, 8}};
Board board = new Board(tilesArr);
Solver solver = new Solver(board);
System.out.println("\nThe print out of the solution path: ");
System.out.println("---- initial board ----");
for (Board item : solver.solution()) {
System.out.println(item);
System.out.println("-------------");
}
System.out.println("Is solvable: " + solver.isSolvable());
System.out.println("Number of moves: " + solver.moves());
assertTrue(solver.isSolvable());
assertEquals(solver.moves(), 7);
}
@Test
public void executeSolve_whenBoardUnsolved_expectTheSuccessWithTwinTask() {
int[][] tilesArr = {{1,2,3},
{4,5,6},
{8,7,0}};
Board board = new Board(tilesArr);
Solver solver = new Solver(board);
System.out.println("\nThe print out of the solution path: ");
System.out.println("---- initial board ----");
System.out.println("Is solvable: " + solver.isSolvable());
System.out.println("Number of moves: " + solver.moves());
assertFalse(solver.isSolvable());
}
}
<file_sep>/src/main/java/week2/simpleSortings/ShellSort.java
package week2.simpleSortings;
import java.util.Comparator;
/**
* Created by scher on 07.08.2019.
*/
public class ShellSort implements Comparator<Integer> {
public void sort(Integer[] arr) {
//The sequences of the gaps calculated by following way: h = 3*a + 1, where a=0,1,2,3...
int h = arr.length - 2;
//the sense of that: to pass firstly comparisons with long interval, to prepare whole arrays to insertion sorting, to obtain the best time (less swapping)
while (h > 0) {
for (int rightIndex = h; rightIndex < arr.length; rightIndex = rightIndex + h) {
for (int i = rightIndex - h; i >= 0; i = i - h) {//go from right to left and swapping all pairs of numbers where right less than left
if (isLess(arr[rightIndex], arr[i])) {
swap(arr, rightIndex, i);
rightIndex = i;//just to save pointer on swapped number
}
}
}
h = h / 3;
}
for (int rightIndex = 1; rightIndex < arr.length; rightIndex++) {
for (int i = rightIndex - 1; i >= 0; i--) {//go from right to left and swapping all pairs of numbers where right less than left
if (isLess(arr[rightIndex], arr[i])) {
swap(arr, rightIndex, i);
rightIndex = i;//just to save pointer on swapped number
}
}
}
}
private void swap(Integer[] arr, int i, int j) {
int buf = arr[i];
arr[i] = arr[j];
arr[j] = buf;
}
private boolean isLess(int one, int two) {
if (compare(one, two) < 1)
return true;
return false;
}
@Override
public int compare(Integer o1, Integer o2) {
if (o1 < o2) return -1;
else if (o1 == o2) return 0;
else return 1;
}
}<file_sep>/src/test/java/week2/queues/DequeTest.java
package week2.queues;
import org.junit.Before;
import org.junit.Test;
import java.util.Iterator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by scher on 04.08.2019.
*/
public class DequeTest {
private Deque<String> underTestQueue;
@Before
public void setup() {
underTestQueue = new Deque<>();
}
@Test
public void testLIFO_whenCallOnlyFist_expectedOk() {
String str1 = "first";
String str2 = "second";
String str3 = "third";
String str4 = "fourth";
//Push 3
underTestQueue.addFirst(str1);
underTestQueue.addFirst(str2);
underTestQueue.addFirst(str3);
//Pop 1
assertEquals(underTestQueue.removeFirst(), str3);
//Push 1 more
underTestQueue.addFirst(str4);
//Pop all
assertEquals(underTestQueue.removeFirst(), str4);
assertEquals(underTestQueue.removeFirst(), str2);
assertEquals(underTestQueue.removeFirst(), str1);
//Check is empty
assertTrue(underTestQueue.isEmpty());
assertEquals(underTestQueue.size(), 0);
}
@Test
public void testLIFO_whenCallOnlyLast_expectedOk() {
String str1 = "first";
String str2 = "second";
String str3 = "third";
String str4 = "fourth";
//Push 3
underTestQueue.addLast(str1);
underTestQueue.addLast(str2);
underTestQueue.addLast(str3);
assertEquals(underTestQueue.size(), 3);
//Pop 1
assertEquals(underTestQueue.removeLast(), str3);
//Push 1 more
underTestQueue.addLast(str4);
//Pop all
assertEquals(underTestQueue.removeLast(), str4);
assertEquals(underTestQueue.removeLast(), str2);
assertEquals(underTestQueue.removeLast(), str1);
//Check is empty
assertTrue(underTestQueue.isEmpty());
assertEquals(underTestQueue.size(), 0);
}
@Test
public void testLILO_whenAddFront_expectedOk() {
String str1 = "first";
String str2 = "second";
String str3 = "third";
String str4 = "fourth";
//Push 3
underTestQueue.addFirst(str1);
underTestQueue.addFirst(str2);
underTestQueue.addFirst(str3);
//Pop 1
assertEquals(underTestQueue.removeLast(), str1);
//Push 1 more
underTestQueue.addFirst(str4);
//Pop all
assertEquals(underTestQueue.removeLast(), str2);
assertEquals(underTestQueue.removeLast(), str3);
assertEquals(underTestQueue.removeLast(), str4);
//Check is empty
assertTrue(underTestQueue.isEmpty());
assertEquals(underTestQueue.size(), 0);
}
@Test
public void test1() {
Deque<Integer> underTestQueue1 = new Deque<>();
int m = 50;
for (int i = 0; i <= m; i++) {
underTestQueue1.addFirst(i);
underTestQueue1.addLast(i);
underTestQueue1.removeFirst();
underTestQueue1.removeLast();
}
Iterator<Integer> it = underTestQueue1.iterator();
while(it.hasNext()) {
it.next();
}
}
}
<file_sep>/src/main/java/week2/queues/RandomizedQueue.java
package week2.queues;
import edu.princeton.cs.algs4.StdRandom;
import java.util.NoSuchElementException;
/**
* Created by scher on 04.08.2019.
* <p>
* A randomized queue is similar to a stack or queue, except that the item removed is chosen uniformly at random among items in the data structure
*/
public class RandomizedQueue<Item> implements Iterable<Item> {
private Node<Item> root;
private Node<Item> last;
private int size;
// construct an empty randomized queue
public RandomizedQueue() {
}
// is the randomized queue empty?
public boolean isEmpty() {
return size == 0;
}
// return the number of items on the randomized queue
public int size() {
return size;
}
// add the item
public void enqueue(Item item) {
if (item == null)
throw new IllegalArgumentException();
Node<Item> newNode = new Node<>(item, root, null);
if (isEmpty()) {
root = newNode;
last = newNode;
} else {
root.setPrev(newNode);
root = newNode;
}
size++;
}
// remove and return a random item
public Item dequeue() {
if (isEmpty())
throw new NoSuchElementException();
Node<Item> randomNode = selectRandomNode();
Item value = randomNode.getValue();
size--;
if (randomNode.getPrev() != null) {
Node<Item> prevNode = randomNode.getPrev();
prevNode.setNext(randomNode.getNext());
if (randomNode == last)
last = prevNode;
}
if (randomNode.getNext() != null) {
Node<Item> nextNode = randomNode.getNext();
nextNode.setPrev(randomNode.getPrev());
if (randomNode == root)
root = nextNode;
}
if (isEmpty()) {
root = null;
last = null;
}
return value;
}
// return a random item (but do not remove it)
public Item sample() {
if (isEmpty())
throw new NoSuchElementException();
return selectRandomNode().getValue();
}
private Node<Item> selectRandomNode() {
int index = StdRandom.uniform(size);
int curr = 0;
Node<Item> currNode = root;
while (curr != index) {
currNode = currNode.getNext();
curr++;
}
return currNode;
}
// return an independent iterator over items in random order
public java.util.Iterator<Item> iterator() {
return new Iterator();
}
private class Iterator implements java.util.Iterator<Item> {
private Node<Item>[] nodes;
private int index;
Iterator() {
Node<Item> node = root;
nodes = new Node[size()];
for (int i = 0; i < size(); i++) {
nodes[i] = node;
node = node.getNext();
}
StdRandom.shuffle(nodes);
}
@Override
public boolean hasNext() {
return index != size();
}
@Override
public Item next() {
if (index >= size())
throw new NoSuchElementException();
Item value = nodes[index].getValue();
index++;
return value;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
private class Node<Item> {
Item value;
Node<Item> next;
Node<Item> prev;
Node(Item value, Node<Item> next, Node<Item> prev) {
this.value = value;
this.next = next;
this.prev = prev;
}
Item getValue() {
return value;
}
Node<Item> getNext() {
return next;
}
void setNext(Node<Item> next) {
this.next = next;
}
Node<Item> getPrev() {
return prev;
}
void setPrev(Node<Item> prev) {
this.prev = prev;
}
}
// unit testing (required)
public static void main(String[] args) {
}
}
<file_sep>/src/main/java/week4/heap/MaxHeap.java
package week4.heap;
import edu.princeton.cs.algs4.StdRandom;
/**
* Created by scher on 19.08.2019.
*/
public class MaxHeap {
private final int DEFAULT_SIZE = 5;
private final int ROOT_INDEX = 1;
private int[] array;
private int currentSize;
private int randomKey;
public MaxHeap(int count) {
if (count < 2) {
array = new int[DEFAULT_SIZE];
} else {
array = new int[count];
}
}
public MaxHeap() {
this(0);
}
public void insert(int value) {
if (currentSize == array.length - 1)
resizeContainer();
array[++currentSize] = value;
swimUp(currentSize);
}
public int delete() {
if(currentSize == 1)
throw new IllegalArgumentException("Heap is empty");
int deletedVal = array[ROOT_INDEX];
swap(ROOT_INDEX, currentSize);
array[currentSize--] = 0;
sinkDown(ROOT_INDEX);
return deletedVal;
}
public int sample() {
randomKey = StdRandom.uniform(currentSize) + 1;
return randomKey;
}
public int delRandom() {
if(currentSize == 1)
throw new IllegalArgumentException("Heap is empty");
sample();
int deletedVal = array[randomKey];
swap(randomKey, currentSize);
array[currentSize--] = 0;
//if we didn't remove the last node, sink and swim operation is required
if (randomKey <= currentSize) {
sinkDown(randomKey);
swimUp(randomKey);
}
return deletedVal;
}
public int size() {
return currentSize;
}
private void swimUp(int nodeIndex) {
//Until we don't archive parent
while (nodeIndex / 2 > 0) {
int parent = getParent(nodeIndex);
if (array[parent] > array[nodeIndex])
break;
swap(nodeIndex, parent);
nodeIndex = parent;
}
}
private void sinkDown(int parentIndex) {
while (parentIndex * 2 <= currentSize) {
int biggerChild = getBiggerChild(parentIndex);
if (array[biggerChild] > array[parentIndex]) {
swap(biggerChild, parentIndex);
parentIndex = biggerChild;
} else {
break;
}
}
}
private void swap(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private int getBiggerChild(int parent) {
int left = getLeftChild(parent);
int right = getRightChild(parent);
if (left > currentSize)
return right;
else if (right > currentSize)
return left;
else return array[left] > array[right] ? left : right;
}
private int getLeftChild(int parent) {
return parent * 2;
}
private int getRightChild(int parent) {
return parent * 2 + 1;
}
private int getParent(int child) {
return child / 2;
}
private void resizeContainer() {
int[] newArray = new int[array.length * 2];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
}
<file_sep>/src/main/java/week1/unions/PercolationStats.java
package week1.unions;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
private final double[] experiments;
private final int T;
private final double coff = 1.96;
// perform independent trials on an n-by-n grid
public PercolationStats(int n, int trials) {
if (n < 1 || trials < 1)
throw new IllegalArgumentException();
experiments = new double[trials];
T = trials;
for (int i = 0; i < trials; i++) {
experiments[i] = experimentConduction(n);
}
}
// sample mean of percolation threshold
public double mean() {
return StdStats.mean(experiments);
}
// sample standard deviation of percolation threshold
public double stddev() {
return StdStats.stddev(experiments);
}
// low endpoint of 95% confidence interval
public double confidenceLo() {
return (mean() - (coff * stddev()) / Math.sqrt(T));
}
// high endpoint of 95% confidence interval
public double confidenceHi() {
return (mean() + (coff * stddev()) / Math.sqrt(T));
}
// test client (see below)
public static void main(String[] args) {
if (args.length == 2) {
int n = Integer.parseInt(args[0]);
int t = Integer.parseInt(args[1]);
PercolationStats percolationStats = new PercolationStats(n, t);
StdOut.printf("mean\t = %f\n", percolationStats.mean());
StdOut.printf("stddev\t = %f\n", percolationStats.stddev());
StdOut.printf("95%c confidence interval\t = [%f, %f]\n", '%', percolationStats.confidenceLo(),
percolationStats.confidenceHi());
}
}
private static double experimentConduction(int n) {
Percolation percolation = new Percolation(n);
final int totalSize = n * n;
do {
int row = StdRandom.uniform(n) + 1;
int col = StdRandom.uniform(n) + 1;
percolation.open(row, col);
} while (!percolation.percolates());
return percolation.numberOfOpenSites() / (double) totalSize;
}
}<file_sep>/src/main/java/week2/Permutation.java
package week2;
import week2.simpleSortings.ShellSort;
/**
* Created by scher on 07.08.2019.
* <p>
* Given two integer arrays of size nn, design a subquadratic algorithm to determine whether one is a permutation of the other.
* That is, do they contain exactly the same entries but, possibly, in a different order.
*/
public class Permutation {
public boolean areTheSame(Integer[] arr1, Integer[] arr2) {
if (arr1.length != arr2.length)
return false;
ShellSort sorter = new ShellSort();
sorter.sort(arr1);
sorter.sort(arr2);
for (int i = 0; i < arr1.length; i++)
if (arr1[i] != arr2[i])
return false;
return true;
}
}
<file_sep>/src/main/java/week5/intersectionsOfGeometricPrimitives/PointSET.java
package week5.intersectionsOfGeometricPrimitives;
import week5.intersectionsOfGeometricPrimitives.primitives.Point2D;
import week5.intersectionsOfGeometricPrimitives.primitives.RectHV;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.TreeSet;
import java.util.Set;
// Brute-force implementation. Write a mutable data type PointSET.java
// that represents a set of points in the unit square. Implement the following API by using a red–black BST
public class PointSET {
private final Set<Point2D> pointsContainer;
// construct an empty set of points
public PointSET() {
pointsContainer = new TreeSet<>();
}
// is the set empty?
public boolean isEmpty() {
return pointsContainer.isEmpty();
}
// number of points in the set
public int size() {
return pointsContainer.size();
}
// add the point to the set (if it is not already in the set)
public void insert(Point2D p) {
if (Objects.isNull(p))
throw new IllegalArgumentException();
pointsContainer.add(p);
}
// does the set contain point p?
public boolean contains(Point2D p) {
if (Objects.isNull(p))
throw new IllegalArgumentException();
return pointsContainer.contains(p);
}
// draw all points to standard draw
public void draw() {
throw new UnsupportedOperationException();
}
// all points that are inside the rectangle (or on the boundary)
public Iterable<Point2D> range(RectHV rect) {
if (Objects.isNull(rect))
throw new IllegalArgumentException();
List<Point2D> inRect = new LinkedList<>();
for (Point2D point2D : pointsContainer) {
if (rect.contains(point2D))
inRect.add(point2D);
}
return inRect;
}
// a nearest neighbor in the set to point p; null if the set is empty
public Point2D nearest(Point2D p) {
if (Objects.isNull(p))
throw new IllegalArgumentException();
double minDist = Double.POSITIVE_INFINITY;
Point2D nearestPoint = null;
for (Point2D point2D : pointsContainer) {
double currDist = p.distanceSquaredTo(point2D);
if (minDist > currDist) {
minDist = currDist;
nearestPoint = point2D;
}
}
return nearestPoint;
}
public static void main(String[] args) {
throw new UnsupportedOperationException();
}
}
| 60da2f55ff945a35a2f5a9932a88d1a925ac2411 | [
"Markdown",
"Java"
] | 23 | Java | scherbinin/HW_coursera_algorithms | cf85360b73023cdadbf4c7d78bdd344288a6aa16 | c3e302abfd01f44df0e0117acd02d193fba8caf0 |
refs/heads/master | <repo_name>chigoncalves/cproj<file_sep>/src/main.cc
#include "config.hh"
#include <iostream>
#include <cstdlib>
int
main (int argc, char* argv[]) {
UNUSED (argc, argv);
std::cout << "Project -> \"" << PROJECT_NAME << "\"" << std::endl;
return EXIT_SUCCESS;
}
<file_sep>/CMakeLists-qt.cmake
if ("${CMAKE_CURRENT_BINARY_DIR}" STREQUAL
"${CMAKE_CURRENT_SOURCE_DIR}")
message (FATAL_ERROR [[In source builds are not allowed.
Try running `cmake' . -B<build-dir>]])
endif ()
cmake_minimum_required (VERSION 3.0)
cmake_policy (SET CMP0054 NEW)
project (<? APP_NAME ?> LANGUAGES <? LANG ?>)
set (CMAKE_AUTOMOC ON)
set (CMAKE_AUTOUIC ON)
set (CMAKE_AUTORCC ON)
list (APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
include (Utils)
include_directories ("${CMAKE_BINARY_DIR}"
"${CMAKE_SOURCE_DIR}/src")
configure_file ("${CMAKE_SOURCE_DIR}/src/config.<? HEADER ?>.in"
"${CMAKE_BINARY_DIR}/config.<? HEADER ?>"
@ONLY)
set (SOURCES src/main.<? SOURCE ?>)
add_executable (${PROJECT_NAME} ${SOURCES})
find_package (Qt5Widgets CONFIG)
target_link_libraries (${PROJECT_NAME}
PUBLIC
Qt5::Widgets)
<file_sep>/src/main-qt.cc
#include "config.hh"
#include <iostream>
#include <cstdlib>
#include <QApplication>
#include <QDesktopWidget>
#include <QMainWindow>
int
main (int argc, char* argv[]) {
QApplication app (argc, argv);
QMainWindow window;
window.setWindowTitle (PROJECT_NAME);
window.resize (600, 480);
window.move (QApplication::desktop ()->screen ()->rect ().center ()
- window.rect ().center ());
window.show ();
return app.exec ();
}
<file_sep>/src/main.c
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
int
main (int argc, char* argv[]) {
UNUSED (argc, argv);
printf ("Project -> \"%s\".\n", PROJECT_NAME);
return EXIT_SUCCESS;
}
<file_sep>/CMakeLists.txt
if ("${CMAKE_CURRENT_BINARY_DIR}" STREQUAL
"${CMAKE_CURRENT_SOURCE_DIR}")
message (FATAL_ERROR [[In source builds are not allowed.
Try running `cmake' . -B<build-dir>]])
endif ()
cmake_minimum_required (VERSION 3.0)
cmake_policy (SET CMP0054 NEW)
project (<? APP_NAME ?> LANGUAGES <? LANG ?>)
set (CMAKE_INCLUDE_CURRENT_DIR ON)
list (APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
include (Utils)
configure_file ("${CMAKE_SOURCE_DIR}/src/config.<? HEADER ?>.in"
"${CMAKE_BINARY_DIR}/config.<? HEADER ?>"
@ONLY)
set (SOURCES src/main.<? SOURCE ?>)
add_subdirectory (t)
add_subdirectory (vendor)
add_executable (${PROJECT_NAME} ${SOURCES})
<file_sep>/cmake/Utils.cmake
set (CMAKE_POSITION_INDEPENDENT_CODE ON)
set (CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
set (CMAKE_INCLUDE_CURRENT_DIR ON)
set (CMAKE_C_STANDARD 99)
set (CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin")
set (CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib")
set (CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib")
set (CMAKE_DEBUG_POSTFIX d)
if (NOT CMAKE_BUILD_TYPE)
set (CMAKE_BUILD_TYPE "Release")
endif ()
if (NOT DEFINED BUILD_SHARED_LIBS)
set (BUILD_SHARED_LIBS ON)
endif ()
macro (list_to_string VARNAME)
list (REMOVE_DUPLICATES ${VARNAME})
string (REPLACE ";" " " ${VARNAME} "${${VARNAME}}")
endmacro ()
if (CMAKE_C_COMPILER_ID STREQUAL "Clang")
set (CLANG ON)
if (CMAKE_C_COMPILER_VERSION VERSION_GREATER "3.3.0")
set (COMPILER_SUPPORTS_SAN ON)
endif ()
elseif (CMAKE_C_COMPILER_ID STREQUAL "GNU")
set (GNU ON)
if (CMAKE_C_COMPILER_VERSION VERSION_GREATER "4.8.0")
set (COMPILER_SUPPORTS_SAN ON)
endif ()
endif ()
if (CMAKE_BUILD_TYPE STREQUAL "Debug")
set (CMAKE_WARN_DEPRECATED ON)
set (CMAKE_ERROR_DEPRECATED ON)
set (CMAKE_EXPORT_COMPILE_COMMANDS ON)
set (DEBUG 1)
unset (NDEBUG)
option (ENABLE_SAN "Enable sanatizers." ON)
list (APPEND CMAKE_C_FLAGS_DEBUG -Wall
-Wextra
-Werror
-std=c99
-pedantic
# -Wwrite-strings
)
if (COMPILER_SUPPORTS_SAN)
set (SAN_BLACKLIST_FILE "${CMAKE_SOURCE_DIR}/res/blacklists.txt")
list (APPEND CMAKE_C_FLAGS_DEBUG -fPIE )
list (APPEND CMAKE_EXE_LINKER_FLAGS_DEBUG -fno-omit-frame-pointer
-pie)
if (ENABLE_SAN)
string (TOLOWER ${ENABLE_SAN} ENABLE_SAN)
list (APPEND CMAKE_EXE_LINKER_FLAGS_DEBUG -pie)
endif ()
if (CLANG)
list (APPEND CMAKE_C_FLAGS_DEBUG
-fsanitize-blacklist="${SAN_BLACKLIST_FILE}")
endif ()
if (${ENABLE_SAN} STREQUAL "asan" OR ${ENABLE_SAN} STREQUAL "on")
list (APPEND CMAKE_EXE_LINKER_FLAGS_DEBUG -fsanitize=address
-fsanitize=undefined)
elseif (${ENABLE_SAN} STREQUAL "msan")
list (APPEND CMAKE_EXE_LINKER_FLAGS_DEBUG -fsanitize=memory)
elseif (${ENABLE_SAN} STREQUAL "tsan")
list (APPEND CMAKE_EXE_LINKER_FLAGS_DEBUG -fsanitize=thread)
endif ()
endif ()
list_to_string (CMAKE_C_FLAGS_DEBUG)
list_to_string (CMAKE_EXE_LINKER_FLAGS_DEBUG)
endif ()
mark_as_advanced (COMILER_SUPPORTS_SAN
CLANG
GNU
DEBUG)
<file_sep>/readme.rst
#######
cproj
#######
Generates project skeleton for C and C++.
<file_sep>/src/config.h.in
// -*- c -*-
#ifndef <? PROJECT_MACRO ?>_SRC_CONFIG_<? HEADER_FOR_MACRO ?>
#define <? PROJECT_MACRO ?>_SRC_CONFIG_<? HEADER_FOR_MACRO ?> 1
#define PROJECT_NAME "<? PROJECT ?>"
#ifdef UNUSED
#undef UNUSED
#endif
#ifdef __cplusplus
#define _UNUSED_LEVEL_1(var) (static_cast<void>(var))
#else
#define _UNUSED_LEVEL_1(var) ((void)var)
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#elif _POSIX_C_SOURCE < 200809L
#undef 200809L
#define _POSIX_C_SOURCE 200809L
#endif
#define begin
#endif /* __cplusplus */
#define UNUSED(...) _UNUSED_CALL ( \
_UNUSED_GET_LEVEL_WRAPPER (__VA_ARGS__, _UNUSED_LEVELS ()), \
__VA_ARGS__)
#define _UNUSED_LEVEL_2(a, b) _UNUSED_LEVEL_1 (a), _UNUSED_LEVEL_1 (b)
#define _UNUSED_LEVEL_3(a, b, c) _UNUSED_LEVEL_1 (a), \
_UNUSED_LEVEL_2 (b, c)
#define _UNUSED_LEVEL_4(a, b, c, d) _UNUSED_LEVEL_3 (a, b, c), \
_UNUSED_LEVEL_1 (d)
#define _UNUSED_LEVEL_5(a, b, c, d, e) _UNUSED_LEVEL_4 (a, b, c, d), \
_UNUSED_LEVEL_1 (e)
#define _UNUSED_GET_LEVEL_WRAPPER(...) _UNUSED_GET_LEVEL (__VA_ARGS__)
#define _UNUSED_GET_LEVEL(__ignored_a, __ignored_b, __ignored_c, \
__ignored_d, _ignored_e, level, ...) level
#define _UNUSED_LEVELS() _UNUSED_LEVEL_5, _UNUSED_LEVEL_4, \
_UNUSED_LEVEL_3, _UNUSED_LEVEL_2, _UNUSED_LEVEL_1, 0
#define _UNUSED_CALL(level, ... ) level (__VA_ARGS__)
#cmakedefine DEBUG 1
#define block
#define progn
#ifndef NUL
#define NUL '\0'
#endif /* NUL */
#endif /* <? PROJECT_MACRO ?>_SRC_CONFIG_<? HEADER_FOR_MACRO ?> */
| b1f8afd961c62f6d51dd00f88f43f467b55b5afc | [
"C",
"CMake",
"C++",
"reStructuredText"
] | 8 | C++ | chigoncalves/cproj | efe54607b703707d363d5ba2bd9a697946b48f84 | 55ea0c055b3e43b3538aa16326fa52477687b922 |
refs/heads/main | <repo_name>ismailertaylan/ReverseTrianglePattern<file_sep>/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TersDuz
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string first = textBox1.Text;
string eklenecek = "";
int i = first.Length - 1;
int j = 0, adim = 0;
while (i > 0)
{
eklenecek += first[i];
i--;
}
eklenecek += first;
listBox1.Items.Add(eklenecek);
adim++;
while (first.Length > 0)
{
first = first.Substring(1, first.Length - 1);
eklenecek = "";
int dongu = adim;
while (dongu > 0)
{
eklenecek += " ";
dongu--;
}
i = first.Length - 1;
j = 0;
while (i > 0)
{
eklenecek += first[i];
i--;
}
eklenecek += first;
if(eklenecek!="")
listBox1.Items.Add(eklenecek);
adim++;
}
}
}
}
| b034f7fdca352fe1b8281eed1edc557b1755b6d2 | [
"C#"
] | 1 | C# | ismailertaylan/ReverseTrianglePattern | e3de56da8c43c80954d5ab4a3deb401fff7eacec | 7168649a3206966b0c58201b2dd71b9c6f84413a |
refs/heads/master | <repo_name>chezhenjun110/ManagementSystem<file_sep>/Ad Tools/Ad Tools/Controllers/HomeController.cs
using Ad_Tools.Log4net;
using Ad_Tools.Models;
using ADTOOLS.AD;
using ADTOOLS.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml;
namespace Ad_Tools.Controllers
{
public class HomeController : Controller
{
//GET
public ActionResult Login(string a)
{
List<string> DomainLst = HttpContext.Application["domains"] as List<string>;
if (DomainLst!=null&& DomainLst.Count > 0)
{
List<SelectListItem> DomainItem = new List<SelectListItem>();
foreach (var Item in DomainLst)
{
DomainItem.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() });
}
UserLoginModel USVM = new UserLoginModel()
{
domains = DomainItem,
};
return View(USVM);
}
else
{
System.Exception exp = HttpContext.Application["startup_exception"] as System.Exception;
if (exp != null)
{
ModelState.AddModelError("Error", exp.Message);
return new HttpStatusCodeResult(500, exp.Message);
}
else
{
UserLoginModel USVM = new UserLoginModel()
{
domains = new List<SelectListItem>(),
};
return View(USVM);//返回结果集合
}
}
}
[HttpPost]
public ActionResult Login()
{
string member = "";
List<string> memberof = null;
bool logined = false;
string username = Request.Form["username"].Trim().ToString();
string domian = Request.Form["domain"].Trim().ToString();
string password = Request.Form["password"].Trim().ToString();
string LoginFailedInfo = "";
try
{
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(username, domian, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
memberof = ud.MemberOf;
}
catch (Exception e)
{
return Json(new JsonData(e.ToString()));
}
if(ADHelper.IsAuthenticated(username, password, ref LoginFailedInfo).Equals(LoginResult.LOGIN_USER_OK))
{
logined = true;
Session["memberof"] = memberof;//存入session
Session["username"] = username;
Session["domain"] = domian;
if (memberof.Contains("DeletePermission"))
{
Session["DeletePermission"] = true;
}
else
{
Session["DeletePermission"] = false;
};
LogHelper.WriteLog(typeof(HomeController), username, "Login",true);
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/UserDetail.xml"));
XmlElement root = null;
root = doc.DocumentElement;
//从session得到用户
//XmlNodeList listNodes = root.SelectNodes(permission);
XmlNode node = doc.SelectSingleNode("ADUserDetail");
// 得到根节点的所有子节点
XmlNodeList xnl = node.ChildNodes;
foreach (XmlNode xn1 in xnl)
{
// 将节点转换为元素,便于得到节点的属性值
XmlElement xe = (XmlElement)xn1;
// 得到Type和ISBN两个属性的属性值
if(xe.GetAttribute("Name").ToString()== username){
XmlNodeList xnl0 = xe.ChildNodes;
xnl0.Item(2).InnerXml=DateTime.Today.ToString("yyyyMMdd");
}
}
doc.Save(Server.MapPath("~/UserDetail.xml"));
}
else
{
member = LoginFailedInfo;
LogHelper.WriteLog(typeof(HomeController), username, "Login",false);
}
return Json(new JsonData(member,logined));
}
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
LogHelper.WriteLog(typeof(HomeController), Session["username"].ToString(), "LogOff", true);
Session["username"] = null;
return RedirectToAction("Login", "Home");
}
public ActionResult Error()
{
return View();
}
}
}<file_sep>/Ad Tools/Ad Tools/Models/GroupManagementViewModels.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Ad_Tools.Models
{
public class GroupSearchViewModels
{
public List<SelectListItem> domains { get; set; }
public List<SelectListItem> searchcriteria { get; set; }
public List<SelectListItem> searchfield { get; set; }
}
public class GroupCreateViewModels
{
public List<SelectListItem> domains { get; set; }
}
public class GroupReport
{
public string groupnumber { get; set; }
}
}<file_sep>/Ad Tools/Ad Tools/Models/GroupDetail.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ad_Tools.Models
{
public class GroupDetail
{
public int id { get; set; }
public string Createby { get; set; }
public string name { get; set; }
public string CreateTime { get; set; }
}
}<file_sep>/Ad Tools/Ad Tools/Scripts/adtools/Group.js
var groupname1;
var description;
var email;
var isSecurityGroup;
var note;
var GroupModifySubmited = false;
var oupathHidde;
var formatedou;
var MemberOfTable;
var Members;
function Group_Memberof_Search_begin() {
var event = window.event || arguments.callee.caller.arguments[0];
if (event.keyCode == 13) {
Group_Memberof_Search();
}
}
function Group_radioClick() {
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn").disabled = false;
}
function Group_Detail_Cancle() {
$("#MiddleMess").html("");
document.getElementById("canclebtn").disabled = true;
document.getElementById("modifybtn").disabled = true;
document.getElementById("groupname").style.color = "black";
document.getElementById("description").style.color = "black";
document.getElementById("email").style.color = "black";
document.getElementById("groupname").value = groupname1;
document.getElementById("description").value = description;
document.getElementById("email").value =email;
document.getElementById("note").value = note;
if (isSecurityGroup) {
document.getElementById("Security").checked = true;
}
else {
document.getElementById("Distribution").checked = true;
}
$("#membertable").html(MemberOfTable);
Memberoftable = $('#Memberof').DataTable({
"bAutoWidth": false, //是否启用自动适应列宽
"aoColumns": [ //设定各列宽度
{ "sWidth": "50px" },
{ "sWidth": "*" }]
});
$('#Memberof tbody').on('click', 'tr', function () {
console.log(Memberoftable.row(this).data());
Memberoftable.row(this).remove().draw(false);
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn").disabled = false;
UserModifySubmited = true;
});
$("#Memberstable").html(Members);
MembersTable = $('#Mem').DataTable({
"bAutoWidth": false,
//是否启用自动适应列宽
"aoColumns": [ //设定各列宽度
{ "sWidth": "50px" },
{ "sWidth": "*" }]
});
$('#Mem tbody').on('click', 'tr', function () {
console.log(MembersTable.row(this).data());
MembersTable.row(this).remove().draw(false);
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn").disabled = false;
UserModifySubmited = true;
});
}
function Group_entersearch() { //回车键搜索
//alert(dd);
var event = window.event || arguments.callee.caller.arguments[0];
if (event.keyCode == 13) {
Group_search();
}
}
function Group_create_clear() {
document.getElementById("groupname").value = "";
document.getElementById("Create_Cancle").disabled = true;
}
function Group_search_clear() {
document.getElementById("searchkeyword").value = "";
document.getElementById("searchclear").disabled = true;
}
var table;
function Group_search() {
document.getElementById("note").value = "";
document.getElementById("groupname").value = "";
document.getElementById("description").value = "";
document.getElementById("email").value = "";
document.getElementById("ManageBytablespace").value = "";
document.getElementById("ManageByTab").style.visibility = "hidden";
document.getElementById("Usearchkeyword").value = "";
for (var i = 0; i < 3; i++) {
var scope = "GroupScope" + i;
document.getElementById(scope).checked = false;
}
document.getElementById("Security").checked = false;
document.getElementById("Distribution").checked = false;
$("#message").html("");
$("#tablespace").html("<h4 style=\"color:orange\">Searching....Please wait</h4>");
$.ajax({
type: "post",
url: "/GroupsManagement/Search",
data: "domain=" + $("#domain").val() + "&searchkeyword=" + $("#searchkeyword").val(),
dataType: "json",
success: function (data) {
$("#tablespace").html(data.Message);
table= $("#example").DataTable();
$('#example tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
var Memberoftable;
var targrt;
var MembersTable;
var Group_detail = function (obj) { //获取点击用户的详细信息
document.getElementById("ManageBytablespace").value = "";
document.getElementById("ManageByTab").style.visibility = "hidden";
document.getElementById("MembersAddSearch").style.visibility = "hidden";
document.getElementById("Usearchkeyword").value = "";
$('#combotree').combotree('setText', "");
document.getElementById("ManageByName").value = ""; document.getElementById("TabContent").style.visibility = "visible";
var groupname = $(obj).children('td').next().html();
var upName = $(obj).children('td').next().next().html();
var domain = "@";
var ou = upName.split(",DC=");
var len = ou.length;
for (var j = 1; j < len; j++) {
var item = "." + upName.split(",DC=")[j];
domain += item;
}
var fin = domain.split("@.")[1];
$("#MiddleMess").html("");
document.getElementById("groupname").style.color = "black";
document.getElementById("description").style.color = "black";
document.getElementById("email").style.color = "black";
if (GroupModifySubmited) {
if (confirm("Whether to submit the current user's modification?")) {
Group_update();
}
else {
GroupModifySubmited = false;
table.$('tr.ModifyState').removeClass('ModifyState');
}
}
$.ajax({
type: "post",
url: "/GroupsManagement/Details",
data: "groupname=" + groupname + "&domain=" + fin,
dataType: "json",
success: function (data) {
$('#combotree').combotree('setText', data.BelongsOUPath);
targrt = obj;
table.$('tr.ModifyState').removeClass('ModifyState');
table.$('tr.selected').addClass('ModifyState');
$("#key").html(data.SamAccountName + "," + fin);
document.getElementById("deletebtn").disabled = false;
document.getElementById("note").value = data.Note;
note = data.Note;
document.getElementById("groupname").value = data.SamAccountName;
groupname1 = data.SamAccountName;
document.getElementById("description").value = data.Description; description = data.Description;
document.getElementById("email").value = data.Email; email = data.Email;
isSecurityGroup = data.isSecurityGroup;
var scope="GroupScope"+data.GroupScope;
document.getElementById(scope).checked = true;
$("#membertable").html(data.memebertable);
MemberOfTable = data.memebertable;
Memberoftable = $('#Memberof').DataTable({
"bAutoWidth": false,
//是否启用自动适应列宽
"aoColumns": [ //设定各列宽度
{ "sWidth": "50px" },
{ "sWidth": "*" }]
});
$('#Memberof tbody').on('click', 'tr', function () {
console.log(Memberoftable.row(this).data());
Memberoftable.row(this).remove().draw(false);
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn").disabled = false;
UserModifySubmited = true;
});
$("#Memberstable").html(data.members);
Members= data.members;
MembersTable = $('#Mem').DataTable({
"bAutoWidth": false,
//是否启用自动适应列宽
"aoColumns": [ //设定各列宽度
{ "sWidth": "50px" },
{ "sWidth": "*" }]
});
$('#Mem tbody').on('click', 'tr', function () {
console.log(MembersTable.row(this).data());
MembersTable.row(this).remove().draw(false);
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn").disabled = false;
UserModifySubmited = true;
});
if (data.isSecurityGroup) {
document.getElementById("Security").checked = true;
}
else {
document.getElementById("Distribution").checked = true;
}
document.getElementById("OUpathhide").innerHTML = data.ManagedBy;
oupathHidde = data.ManagedBy;
if (data.ManagedBy != "") {
var host = "1";
var b = data.ManagedBy.split(",");
var CNOUDC = "";
for (var i = 0; i < b.length; i++) {
CNOUDC += b[i];
}
var CNOU = CNOUDC.split("DC=");
for (var i = 1; i < CNOU.length; i++) {
host = host + "." + CNOU[i];
}
var CN = CNOU[0].split("OU=");
for (var i = 1; i < CN.length; i++) {
host = host + "/" + CN[i];
}
var c = CN[0].split("CN=");
for (var i = 1; i < c.length; i++) {
host = host + "/" + c[i];
}
host = host.split("1.")[1];
console.log(host);
document.getElementById("ManageByName").style.color = "gray";
document.getElementById("ManageByName").value = host;
formatedou = host;
}
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
};
function Group_update_Confirm() {
if (confirm("Sure to submit the current group's modification?")) {
Group_update();
}
else {
return;
}
}
function Group_update() {
var oupath;
var ou1 = document.getElementById("ChoosedOu").innerHTML;
console.log(ou1);
if (ou1 != "") {
var temp = document.getElementById("ChoosedOu").innerHTML.split('LDAP://')[1];
oupath = temp.split('/')[1];
} else {
oupath = "";
}
var groupscope;
var grouptype;
if (document.getElementById("Security").checked) {
grouptype = "Security";
} else {
grouptype = "Distribution";
}
if (document.getElementById("GroupScope0").checked) {
groupscope = "DomainLocale";
} else if ((document.getElementById("GroupScope1").checked)) {
groupscope = "Gloable";
} else {
groupscope = "Universal";
}
var name = document.getElementById("key").innerHTML.split(",")[0]; //更新用户的信息
$("#MiddleMess").html("");
var groupname = $("#groupname").val();
var domain = document.getElementById("key").innerHTML.split(",")[1];
var description = $("#description").val();
var email = $("#email").val();
var note = $("#note").val();
var manageby = document.getElementById("OUpathhide").innerHTML;
var numberof = "";
var rownum1 = document.getElementById("Memberof_info").innerHTML.split(" ")[5];
for (var i = 0; i < rownum1; i++) {
console.log(Memberoftable.row(i).data()[1]);
numberof += Memberoftable.row(i).data()[1] + ",";
}
console.log(numberof);
var Members = "";
var rownum = document.getElementById("Mem_info").innerHTML.split(" ")[5];
for (var i = 0; i < rownum; i++) {
console.log(MembersTable.row(i).data()[1]);
Members += MembersTable.row(i).data()[1] + ",";
}
$.ajax({
type: "post",
url: "/GroupsManagement/Update",
data: "name=" + name + "&groupname=" + groupname + "&domain=" + domain + "&description=" + description + "&email=" + email +
"¬e=" + note + "&manageby=" + manageby + "&numberof=" + numberof + "&Members=" + Members + "&oupath=" + oupath + "&groupscope=" + groupscope + "&grouptype=" + grouptype,
dataType: "json",
success: function (data) {
$("#MiddleMess").html(data.Message);
if (data.logined) {
var pageindex = table.page();
console.log(table.row(targrt).data());
var d = table.row(targrt).data();
d[1] = groupname;
d[3] = description;
table.row(targrt).data(d).draw();
table.page(pageindex).draw(false);
table.$('tr.ModifyState').addClass('modified');
table.$('tr.ModifyState').removeClass('ModifyState');
table.$('tr.selected').addClass('ModifyState');
document.getElementById("modifybtn").disabled = true;
document.getElementById("ManageByName").style.color = "black";
GroupModifySubmited = false;
document.getElementById("groupname").style.color = "black";
document.getElementById("description").style.color = "black";
document.getElementById("email").style.color = "black";
document.getElementById("note").style.color = "black";
document.getElementById("canclebtn").disabled = true;
}
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
function Group_delete_confirm() {
//利用对话框返回的值 (true 或者 false)
if (confirm("Are you sure you want to delete the group?")) {
//如果是true ,那么就把页面转向thcjp.cnblogs.com
Group_delete();
}
else {
//alert("你按了取消,那就是返回false");
}
}
function Group_delete() { //点击删除某个用户
table.row('.selected').remove().draw(false);
var groupname = document.getElementById("key").innerHTML.split(",")[0]; //更新用户的信息
$("#MiddleMess").html("");
var domain = document.getElementById("key").innerHTML.split(",")[1];
$.ajax({
type: "post",
url: "/GroupsManagement/Delete",
data: "groupname=" + groupname + "&domain=" + domain,
dataType: "json",
success: function (data) {
$("#MiddleMess").html(data.Message);
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
function Group_create() {
$("#message").html("Creating, please wait");
if (document.getElementById("ChoosedOu").innerHTML == "") {
alert("OuPath cannot be empty!!");
return;
}
var temp = document.getElementById("ChoosedOu").innerHTML.split('LDAP://')[1];
var OuPath = temp.split('/')[1];
var groupname = document.getElementById("groupname").value;
var domain = $("#domain").val();
var grouptype;
var groupscope;
var EnableExchange;
if (document.getElementById("Security").checked) {
grouptype = "Security";
} else {
grouptype = "Distribution";
}
if (document.getElementById("DomainLocale").checked) {
groupscope = "DomainLocale";
} else if ((document.getElementById("Gloable").checked)) {
groupscope = "Gloable";
} else {
groupscope = "Universal";
}
if (document.getElementById("EnableExchange").checked) {
EnableExchange = "true";
groupscope = "Universal";
document.getElementById("Universal").checked = true;
} else {
EnableExchange = "false";
}
$.ajax({
type: "post",
url: "/GroupsManagement/Create",
data: "domain=" + domain + "&groupname=" + groupname + "&grouptype=" + grouptype + "&groupscope=" + groupscope + "&EnableExchange=" + EnableExchange + "&OuPath=" + OuPath,
dataType: "json",
success: function (data) {
$("#message").html(data.Message);
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
var Groupchange = function (obj) { //获取点击用户的详细信息
var reg = /^[\s ]|[ ]$/gi;
var girlfirend = $(obj).context;
var text = girlfirend.value;
console.log(text);
if (text == Group_Cache) {
girlfirend.style.color = "black";
GroupModifySubmited = false;
return;
}
if (!reg.test(text)) {
girlfirend.style.color = "green";
GroupModifySubmited = true;
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn").disabled = false;
console.log("没有空格");
} else {
console.log("有空格");
return;
}
};
var Group_Cache;
var Group_Gettextlen = function (obj) {
Group_Cache = $(obj).context.value;
console.log(Group_Cache);
}
function Group_Memberof_Search() {
$.ajax({
type: "post",
url: "/UserManagement/Group_GroupSearch",
data: "groupdomain=" + $("#groupdomain").val() + "&searchkeyword=" + $("#groupkeyword").val(),
dataType: "json",
success: function (data) {
$("#Grouptablespace").html(data.Message);
var GroupChooser = $("#GroupChose").DataTable();
$('#GroupChose tbody').on('click', 'tr', function () {
console.log(GroupChooser.row(this).data());
var rownum = document.getElementById("Memberof_info").innerHTML.split(" ")[5];
var d = GroupChooser.row(this).data();
console.log(d[1]);
var arr = new Array()
for (var i = 0; i < rownum; i++) {
arr[i] = Memberoftable.row(i).data()[1];
}
if (arr.indexOf(d[1]) != -1) {
alert("You selected group name already exists!");
console.log("存在");
}
else {
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn").disabled = false;
Memberoftable.row.add([
rownum,
d[1],
]).draw().nodes().to$().addClass('modified');
Memberoftable.row(1).$('tr').addClass('ModifyState');
GroupChooser.row(this).remove().draw(false);
UserModifySubmited = true;
console.log("不存在");
}
});
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
var ManageByTable;
function Group_UserSearch() {
$("#MiddleMess").html("");
$("#message").html("");
$("#ManageBytablespace").html("<h4 style=\"color:orange\">Searching....Please wait</h4>");
$.ajax({
type: "post",
url: "/GroupsManagement/Group_UserSearch",
data: "Udomain=" + $("#Udomain").val() + "&Usearchfield=" + $("#Usearchfield").val() + " &Usearchcriteria=" + $("#Usearchcriteria").val() + "&Usearchkeyword=" + $("#Usearchkeyword").val(),
dataType: "json",
success: function (data) {
$("#ManageBytablespace").html(data.Message);
ManageByTable = $('#example1').DataTable({
"bAutoWidth": false, //是否启用自动适应列宽
"aoColumns": [ //设定各列宽度
{ "sWidth": "50px" },
{ "sWidth": "*" },
{ "sWidth": "*" },
]
});
$('#example1 tbody').on('click', 'tr', function () {
var d = ManageByTable.row(this).data();
console.log(d[2]);
document.getElementById("OUpathhide").innerHTML = d[2];
var host = "1";
var b = d[2].split(",");
var CNOUDC = "";
for (var i = 0; i<b.length; i++) {
CNOUDC += b[i];
console.log(CNOUDC);
}
var CNOU = CNOUDC.split("DC=");
for (var i = 1; i < CNOU.length; i++) {
host = host + "." + CNOU[i];
}
var CN = CNOU[0].split("OU=");
for (var i = 1; i < CN.length; i++) {
host = host + "/" + CN[i];
}
var c = CN[0].split("CN=");
for (var i = 1; i < c.length; i++) {
host = host + "/" + c[i];
}
host = host.split("1.")[1];
console.log(host);
document.getElementById("ManageByName").value = host;
document.getElementById("ManageByName").style.color = "green";
document.getElementById("canclebtn").disabled = false;
UserModifySubmited = true;
document.getElementById("modifybtn").disabled = false;
});
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
function ouchange() {
document.getElementById("ManageByTab").style.visibility = "visible";
}
function clearOusearch() {
document.getElementById("ManageByTab").style.visibility = "hidden";
document.getElementById("OUpathhide").innerHTML = oupathHidde;
document.getElementById("ManageByName").value = formatedou;
}
function MembersAdd() {
document.getElementById("MembersAddSearch").style.visibility = "visible";
}
var MembersDataTable;
function Group_UserSearch_Members() {
$("#MiddleMess").html("");
$("#message").html("");
$("#Memberstablespace").html("<h4 style=\"color:orange\">Searching....Please wait</h4>");
$.ajax({
type: "post",
url: "/GroupsManagement/Group_UserSearch_Members",
data: "Mdomain=" + $("#Mdomain").val() + "&Msearchfield=" + $("#Msearchfield").val() + " &Msearchcriteria=" + $("#Msearchcriteria").val() + "&Msearchkeyword=" + $("#Msearchkeyword").val(),
dataType: "json",
success: function (data) {
$("#Memberstablespace").html(data.Message);
MembersDataTable = $('#MembersData').DataTable({
"bAutoWidth": false, //是否启用自动适应列宽
"aoColumns": [ //设定各列宽度
{ "sWidth": "50px" },
{ "sWidth": "*" },
]
});
$('#MembersData tbody').on('click', 'tr', function () {
var d = MembersDataTable.row(this).data();
console.log(d);
UserModifySubmited = true;
document.getElementById("modifybtn").disabled = false;
var rownum = document.getElementById("Mem_info").innerHTML.split(" ")[5];
var arr = new Array()
for (var i = 0; i < rownum; i++) {
arr[i] = MembersTable.row(i).data()[1];
}
if (arr.indexOf(d[1]) != -1) {
alert("You selected group name already exists!");
console.log("存在");
}
else {
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn").disabled = false;
MembersTable.row.add([
rownum,
d[1],
]).draw().nodes().to$().addClass('modified');
MembersTable.row(1).$('tr').addClass('ModifyState');
MembersDataTable.row(this).remove().draw(false);
UserModifySubmited = true;
console.log("不存在");
}
});
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
var cache = "";
var ExchangeEnabled=function(obj) {
//var groupname = $(obj).children('td').next().html();
var groupname = $(obj).parent().parent().children('td').next().html();
cache = groupname;
console.log(groupname);
var domain = $("#domain").val();
console.log(domain);
$.ajax({
type: "post",
url: "/GroupsManagement/ExchangeEnabled",
data: "groupname=" + groupname + "&domain=" + domain,
dataType: "json",
success: function (data) {
if (data.Message == "1") {
window.open("ModifyExchange?keyword=" + groupname + "&domain=" + domain);
window.targrt = "_blank";
}
else {
if (confirm("Are you sure you want to Enable the Exchange?")) {
EnableGroupExchange();
}
else {
}
}
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function EnableGroupExchange() {
var groupname = cache;
cache = "";
console.log(groupname);
var domain = $("#domain").val();
console.log(domain);
$.ajax({
type: "post",
url: "/GroupsManagement/EnableGroupExchange",
data: "groupname=" + groupname + "&domain=" + domain,
dataType: "json",
success: function (data) {
if (data.Message == "1") {
window.open("ModifyExchange?keyword=" + groupname + "&domain=" + domain);
window.targrt = "_blank";
} else {
alert("Enable Exchange Failed!")
}
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function Group_Exchange_Modify() {
var userid = GetQueryString("keyword");
var domain = GetQueryString("domain");
var DisplayName = document.getElementById("DisplayName").value;
var DLShortname = document.getElementById("DLShortname").value;
var GroupName = document.getElementById("GroupName").value;
var Emailname = document.getElementById("Emailname").value;
var RequireSenderAuthenticationEnabled = document.getElementById("RequireSenderAuthenticationEnabled").checked ? true : false;
var IndudeinGalsync = document.getElementById("IndudeinGalsync").checked ? true : false;
var Description = document.getElementById("Description").value;
var HideFromOAB = document.getElementById("HideFromAB").checked ? true : false;
$.ajax({
type: "post",
url: "/GroupsManagement/ExchangModfiy",
data: "userid=" + userid + "&domain=" + domain + "&DisplayName=" + DisplayName + "&DLShortname=" + DLShortname + "&GroupName="
+ GroupName + "&Emailname=" + Emailname + "&RequireSenderAuthenticationEnabled=" + RequireSenderAuthenticationEnabled + "&IndudeinGalsync=" + IndudeinGalsync + "&Description=" + Description
+ "&HideFromOAB=" + HideFromOAB,
dataType: "json",
success: function (data) {
$("#message").html(data.Message);
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function SaveChange() {
var userid = "789456";
var domain = "fcachina.ccdroot.cn";
$.ajax({
type: "post",
url: "/GroupsManagement/Test",
data: "keyword=" + userid + "&domain=" + domain,
dataType: "json",
success: function (data) {
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function GetQueryString(name) { //获取浏览器地址栏字符串
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
var times = 0;
$("#domain").on("change", function () {
$("#MiddleMess").html("");
times += 1;
if (times == 1) {
var chosed = $("#domain").val();
console.log(chosed);
if (document.getElementById("combotree") != null) {
$('#combotree').combotree({
url: '/UserManagement/Outree?domain=' + chosed,
required: true,
onSelect: function (node) {
//alert(node.id);
document.getElementById("ChoosedOu").innerHTML = node.path;
}
});
}
times = 0;
}
});<file_sep>/Ad Tools/Ad Tools/Scripts/adtools/Computer.js
var Name;
var dNSHostName;
var site;
var Description;
var operatingSystem;
var operatingSystemVersion;
var oupathHidde;
var formated;
var ComputerModifySubmited = false;
function Computer_Clear() {
document.getElementById("searchkeyword").value = "";
document.getElementById("searchclear").disabled = true;
}
function Computer_Detail_Cancle() {
$("#MiddleMess").html("");
document.getElementById("modifybtn").disabled = true;
document.getElementById("Description").style.color = "black";
document.getElementById("Description").value = Description;
document.getElementById("operatingSystem").value = operatingSystem;
document.getElementById("operatingSystemVersion").value = operatingSystemVersion;
document.getElementById("canclebtn").disabled = true;
}
function Computer_entersearch() { //回车键搜索
//alert(dd);
var event = window.event || arguments.callee.caller.arguments[0];
if (event.keyCode == 13) {
computer_search();
}
}
var table;
function computer_search() {
$("#message").html("");
$("#MiddleMess").html("");
document.getElementById("Name").value = "";
document.getElementById("dNSHostName").value = "";
document.getElementById("site").value = "";
document.getElementById("Description").value = "";
document.getElementById("operatingSystem").value = "";
document.getElementById("operatingSystemVersion").value = "";
$("#tablespace").html("<h4 style=\"color:orange\">Searching....Please wait</h4>");
$.ajax({
type: "post",
url: "/ComputerManagement/SearchModify",
data: "domain=" + $("#domain").val() + " &searchcriteria=" + $("#searchcriteria").val() + "&searchkeyword=" + $("#searchkeyword").val(),
dataType: "json",
success: function (data) {
$("#tablespace").html(data.Message);
table= $('#example').DataTable();
$('#example tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
var targrt;
var computer_detail = function (obj) { //获取点击用户的详细信息
Clear();
document.getElementById("Name").style.color = "gray";
document.getElementById("site").style.color = "gray";
document.getElementById("Description").style.color = "black";
document.getElementById("dNSHostName").style.color = "gray";
document.getElementById("operatingSystem").style.color = "gray";
document.getElementById("operatingSystemVersion").style.color = "gray";
$("#MiddleMess").html(""); document.getElementById("TabContent").style.visibility = "visible";
var computername = $(obj).children('td').next().html();
var upName = $(obj).children('td').next().next().html();
var domain = "@";
var ou = upName.split(",DC=");
var len = ou.length;
for (var j = 1; j < len; j++) {
var item = "." + upName.split(",DC=")[j];
domain += item;
}
var fin = domain.split("@.")[1];
if (ComputerModifySubmited) {
if (confirm("Whether to submit the current user's modification?")) {
Computer_update();
}
else {
ComputerModifySubmited = false;
table.$('tr.ModifyState').removeClass('ModifyState');
}
}
$.ajax({
type: "post",
url: "/ComputerManagement/Details",
data: "computername=" + computername+"&domainname="+fin,
dataType: "json",
success: function (data) {
$('#combotree').combotree('setText', data.OUName);
table.$('tr.ModifyState').removeClass('ModifyState');
targrt = obj;
document.getElementById("deletebtn").disabled = false;
table.$('tr.selected').addClass('ModifyState');
$("#key").html(data.Name+","+fin);
document.getElementById("Name").value = data.Name;
Name=data.Name;
document.getElementById("dNSHostName").value = data.dNSHostName; dNSHostName = data.dNSHostName;
document.getElementById("site").value = data.site; site = data.site;
document.getElementById("Description").value = data.Description; Description = data.Description;
document.getElementById("operatingSystem").value = data.operatingSystem; operatingSystem = data.operatingSystem;
document.getElementById("operatingSystemVersion").value = data.operatingSystemVersion; operatingSystemVersion = data.operatingSystemVersion;
console.log(data.manageby);
document.getElementById("OUpathhide").innerHTML = data.managedBy;
oupathHidde = data.managedBy;
if (data.managedBy != "") {
var host = "1";
var CNOUDC = data.managedBy;
var CNOU = CNOUDC.split(",DC=");
for (var i = 1; i < CNOU.length; i++) {
host = host + "." + CNOU[i];
}
var CN = CNOU[0].split(",OU=");
for (var i = 1; i < CN.length; i++) {
host = host + "/" + CN[i];
}
host = host + "/" + CN[0].split("CN=")[1];
host = host.split("1.")[1];
console.log(host);
document.getElementById("managedBy").style.color = "gray";
document.getElementById("managedBy").value = host;
formated = host;
console.log(formated);
}
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
};
function Computer_update_Confirm() {
if (confirm("Sure to submit the current user's modification?")) {
Computer_update();
}
else {
return;
}
}
function Computer_update() {
$("#MiddleMess").html("");//更新用户的信息
var name = document.getElementById("key").innerHTML.split(",")[0];
var domain = document.getElementById("key").innerHTML.split(",")[1];
var computername = $("#Name").val();
var site = $("#site").val();
var Description = $("#Description").val();
var manageby = document.getElementById("OUpathhide").innerHTML;
var oupath;
var ou1 = document.getElementById("ChoosedOu").innerHTML;
console.log(ou1);
if (ou1 != "") {
var temp = document.getElementById("ChoosedOu").innerHTML.split('LDAP://')[1];
oupath = temp.split('/')[1];
} else {
oupath = "";
}
$.ajax({
type: "post",
url: "/ComputerManagement/Update_Computer",
data: "name=" + name + "&computername=" + computername + "&site=" + site + "&Description=" + Description + "&domain=" + domain + "&manageby=" + manageby + "&oupath=" + oupath,
dataType: "json",
success: function (data) {
$("#MiddleMess").html(data.Message);
if (data.logined) {
var pageindex = table.page();
console.log(table.row(targrt).data());
var d = table.row(targrt).data();
d[1] = computername;
table.row(targrt).data(d).draw();
table.page(pageindex).draw(false);
table.$('tr.ModifyState').addClass('modified');
table.$('tr.ModifyState').removeClass('ModifyState');
table.$('tr.selected').addClass('ModifyState');
document.getElementById("modifybtn").disabled = true;
document.getElementById("managedBy").style.color = "black";
ComputerModifySubmited = false;
document.getElementById("Name").style.color = "black";
document.getElementById("site").style.color = "black";
document.getElementById("Description").style.color = "black";
document.getElementById("canclebtn").disabled = true;
}
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
function Computer_Delete_firm() {
//利用对话框返回的值 (true 或者 false)
if (confirm("Are you sure you want to delete the computer?")) {
//如果是true ,那么就把页面转向thcjp.cnblogs.com
Computer_delete();
}
else {
}
}
function Computer_delete() {
table.row('.selected').remove().draw(false);
$("#MiddleMess").html("");
var domain = document.getElementById("key").innerHTML.split(",")[1];
var computername = $("#Name").val();
$.ajax({
type: "post",
url: "/ComputerManagement/Delete",
data: "computername=" + computername + "&domain=" + domain,
dataType: "json",
success: function (data) {
$("#MiddleMess").html(data.Message);
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
function Computer_create() { //创建用户
$("#message").html("Computer being created, please wait. . .");
var domain = document.getElementById("Computerdomain").value;
var computername = $("#computername").val();
if (document.getElementById("ChoosedOu").innerHTML == "") {
alert("OuPath cannot be empty!!");
return;
}
var temp = document.getElementById("ChoosedOu").innerHTML.split('LDAP://')[1];
var OuPath = temp.split('/')[1];
var description = $("#description").val();
$.ajax({
type: "post",
url: "/ComputerManagement/Create",
data: "domain=" + domain + "&computername=" + computername + "&ou=" + OuPath + "&description=" + description,
dataType: "json",
success: function (data) {
$("#message").html(data.Message);
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function Computer_Create_Cancle() {
document.getElementById("computername").value = "";
document.getElementById("ou").value = "";
document.getElementById("description").value = "";
document.getElementById("Create_Cancle").disabled = true;
}
function Clear() {
$('#combotree').combotree('setText', "");
document.getElementById("Name").value = "";
document.getElementById("dNSHostName").value = "";
document.getElementById("site").value = "";
document.getElementById("Description").value = "";
document.getElementById("operatingSystem").value = "";
document.getElementById("operatingSystemVersion").value = "";
document.getElementById("managedBy").value = "";
}
var Computerchange = function (obj) { //获取点击用户的详细信息
ComputerModifySubmited = true;
$(obj).context.style.color = "green";
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn").disabled = false;
};
var times = 0;
$("#Computerdomain").on("change", function () {
times += 1;
if (times == 1) {
var chosed = $("#Userdomain").val();
if (document.getElementById("combotree") != null) {
$('#combotree').combotree({
url: '/UserManagement/Outree',
required: true,
onSelect: function (node) {
//alert(node.id);
document.getElementById("ChoosedOu").innerHTML = node.path;
}
});
}
times = 0;
}
});
var ManageByTable;
function Computer_UserSearch() {
$("#MiddleMess").html("");
$("#message").html("");
$("#ManageBytablespace").html("<h4 style=\"color:orange\">Searching....Please wait</h4>");
$.ajax({
type: "post",
url: "/ComputerManagement/Computer_UserSearch",
data: "domain=" + $("#Udomain").val() + "&searchfield=" + $("#Usearchfield").val() + " &searchcriteria=" + $("#Usearchcriteria").val() + "&searchkeyword=" + $("#Usearchkeyword").val(),
dataType: "json",
success: function (data) {
$("#ManageBytablespace").html(data.Message);
ManageByTable = $('#example2').DataTable({
"bAutoWidth": false, //是否启用自动适应列宽
"aoColumns": [ //设定各列宽度
{ "sWidth": "50px" },
{ "sWidth": "*" }, { "sWidth": "*" }]
});
$('#example2 tbody').on('click', 'tr', function () {
var d = ManageByTable.row(this).data();
console.log(d[2]);
document.getElementById("OUpathhide").innerHTML = d[2];
var host = "1";
var b = d[2].split(",");
var CNOUDC = "";
for (var i = 0; i < b.length; i++) {
CNOUDC += b[i];
console.log(CNOUDC);
}
var CNOU = CNOUDC.split("DC=");
for (var i = 1; i < CNOU.length; i++) {
host = host + "." + CNOU[i];
}
var CN = CNOU[0].split("OU=");
for (var i = 1; i < CN.length; i++) {
host = host + "/" + CN[i];
}
var c = CN[0].split("CN=");
for (var i = 1; i < c.length; i++) {
host = host + "/" + c[i];
}
host = host.split("1.")[1];
console.log(host);
document.getElementById("managedBy").value = host;
document.getElementById("managedBy").style.color = "green";
document.getElementById("canclebtn").disabled = false;
UserModifySubmited = true;
document.getElementById("modifybtn").disabled = false;
});
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function ouchange() {
document.getElementById("ManageByTab").style.visibility = "visible";
}
function clearousearch() {
document.getElementById("ManageByTab").style.visibility = "hidden";
document.getElementById("OUpathhide").innerHTML = oupathHidde;
console.log(formated);
document.getElementById("managedBy").value = formated;
}
function Computer_MoveOu() {
var name = document.getElementById("key").innerHTML.split(",")[0];
var domain = document.getElementById("key").innerHTML.split(",")[1];
$.ajax({
type: "post",
url: "/ComputerManagement/Computer_MoveOu",
data: "name=" + name + "&domain=" + domain + "&oupath=" + oupath,
dataType: "json",
success: function (data) {
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}<file_sep>/Ad Tools/Ad Tools/Models/GroupDetailModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ad_Tools.Models
{
public class GroupDetailModel
{
public List<GroupDetail> groupdetail { get; set; }
}
}<file_sep>/Ad Tools/Ad Tools/Models/UserDetailModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ad_Tools.Models
{
public class UserDetailModel
{
public List<UserDetail> userdetail { get; set; }
}
}<file_sep>/Ad Tools/Ad Tools/Global.asax.cs
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Configuration;
using ADTOOLS.AD;
using log4net.Config;
using System.Web.UI.WebControls;
using System.Web;
using Ad_Tools.Common;
using ADTOOLS.DTO;
using System.Xml;
using System.Linq;
namespace Ad_Tools
{
public class MvcApplication : System.Web.HttpApplication
{
string admin;
string password;
string domain;
Directory ad_directory;
Directory ad_directory_Outree;
List<String> domains;
System.Exception startup_exception;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
try
{
XmlConfigurator.Configure(); //程序启动时启动log4net来生成日志
admin = ConfigurationManager.AppSettings["ServiceAccount"];
password = ADTOOLS.Common.DotNetEncrypt.DESEncrypt.Decrypt(ConfigurationManager.AppSettings["ServiceAccountPWD"]);
domain = ConfigurationManager.AppSettings["ServiceAccountDomain"];
ad_directory = new Directory(admin, password);
if (!ad_directory.connected) throw new System.Exception("Not able connect to Active Directory, Please check up network settings!");
domains = ad_directory.GetAllDomainsNamesInForest();
Computers ad_computer = new Computers(admin, password, domain);
Users ad_user = new Users(admin, password, domain);
Groups ad_group = new Groups(admin, password, domain);
ADHelper ad_helper = new ADHelper(admin, password, domain);
Application["ad_directory"] = ad_directory;
Application["domains"] = domains;
Application["ad_computer"] = ad_computer;
Application["ad_user"] = ad_user;
Application["ad_group"] = ad_group;
Application["ad_helper"] = ad_helper;
for (int i = 0; i < domains.Count; i++) //程序启动时缓存domain对应的树状菜单
{
ad_directory_Outree = new Directory(admin, password, domains[i]);
TreeNodeCollection tnc = ad_directory_Outree.TreeView.Nodes;
OuTreeCache.SetCache(domains[i], tnc);
//程序启动时获取所有domain中的组名并写入xml文件
}
}
catch (Exception e)
{
Application["startup_exception"] = e;
}
finally
{
}
}
private void RedirectToAction(object p)
{
throw new NotImplementedException();
}
}
}
<file_sep>/Ad Tools/Ad Tools/Models/JsonData.cs
using ADTOOLS.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ad_Tools.Models
{
public class JsonData
{
public bool logined { get; set; }
public string Message { get; set; }
//public string Message2 { get; set; }
//public string Message3 { get; set; }
public JsonData(string message)
{
this.Message = message;
}
public JsonData(string message,bool logined)
{
this.Message = message;
this.logined = logined;
}
}
}<file_sep>/Ad Tools/Ad Tools/Controllers/UserManagementController.cs
using ADTOOLS.AD;
using ADTOOLS.DTO;
using Ad_Tools.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Ad_Tools.Log4net;
using System.Web.UI.WebControls;
using System.Xml;
using System.Configuration;
using Ad_Tools.Common;
namespace Ad_Tools.Controllers
{
public class UserManagementController : BaseController
{
[HttpGet]
// GET: UserManagement
public ActionResult SearchModify(string abc)
{
List<string> domainlist = new List<string>();
string currentdomain = (string)Session["domain"];
List<string> DomainLst = HttpContext.Application["domains"] as List<string>;
if (DomainLst.Count > 0)
{
List<SelectListItem> DomainItem = new List<SelectListItem>();
if (currentdomain != null)
{
DomainItem.Add(new SelectListItem { Text = currentdomain, Value = currentdomain });
}
foreach (var Item in DomainLst)
{
if (Item.ToString() != currentdomain) { DomainItem.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() }); }
}
List<SelectListItem> searchfield = new List<SelectListItem>(); //为searchfield添加下拉选项
searchfield.Add(new SelectListItem { Text = "UserID", Value = "0" });
searchfield.Add(new SelectListItem { Text = "First Name", Value = "1" });
searchfield.Add(new SelectListItem { Text = "Last Name", Value = "2" });
searchfield.Add(new SelectListItem { Text = "Full Name", Value = "3" });
searchfield.Add(new SelectListItem { Text = "Company", Value = "4" });
searchfield.Add(new SelectListItem { Text = "Mail", Value = "5" });
searchfield.Add(new SelectListItem { Text = "ID Manager", Value = "6" });
List<SelectListItem> searchcriteria = new List<SelectListItem>(); //为searchcriteria添加下拉选项
searchcriteria.Add(new SelectListItem { Text = "Equals", Value = "1" });
searchcriteria.Add(new SelectListItem { Text = "Contains", Value = "2" });
searchcriteria.Add(new SelectListItem { Text = "Stars with", Value = "3" });
searchcriteria.Add(new SelectListItem { Text = "Ends with", Value = "4" });
List<SelectListItem> searchtype = new List<SelectListItem>(); //为searchtype添加下拉选项
searchtype.Add(new SelectListItem { Text = "All", Value = "0" });
searchtype.Add(new SelectListItem { Text = "User Employee", Value = "1" });
searchtype.Add(new SelectListItem { Text = "User Consultant", Value = "2" });
searchtype.Add(new SelectListItem { Text = "User Extranet", Value = "3" });
searchtype.Add(new SelectListItem { Text = "Service Account", Value = "4" });
List<SelectListItem> Profile_connect = new List<SelectListItem>();
Profile_connect.Add(new SelectListItem { Text = "C:", Value = "C:" });
Profile_connect.Add(new SelectListItem { Text = "D:", Value = "D:" });
Profile_connect.Add(new SelectListItem { Text = "E:", Value = "E:" });
Profile_connect.Add(new SelectListItem { Text = "F:", Value = "F:" });
Profile_connect.Add(new SelectListItem { Text = "G:", Value = "G:" });
Profile_connect.Add(new SelectListItem { Text = "H:", Value = "H:" });
Profile_connect.Add(new SelectListItem { Text = "I:", Value = "I:" });
Profile_connect.Add(new SelectListItem { Text = "J:", Value = "J:" });
Profile_connect.Add(new SelectListItem { Text = "K:", Value = "K:" });
Profile_connect.Add(new SelectListItem { Text = "L:", Value = "L:" });
Profile_connect.Add(new SelectListItem { Text = "M:", Value = "M:" });
Profile_connect.Add(new SelectListItem { Text = "N:", Value = "N:" });
Profile_connect.Add(new SelectListItem { Text = "O:", Value = "O:" });
Profile_connect.Add(new SelectListItem { Text = "P:", Value = "P:" });
Profile_connect.Add(new SelectListItem { Text = "Q:", Value = "Q:" });
Profile_connect.Add(new SelectListItem { Text = "R:", Value = "R:" });
Profile_connect.Add(new SelectListItem { Text = "S:", Value = "S:" });
Profile_connect.Add(new SelectListItem { Text = "T:", Value = "T:" });
Profile_connect.Add(new SelectListItem { Text = "U:", Value = "U:" });
Profile_connect.Add(new SelectListItem { Text = "V:", Value = "V:" });
Profile_connect.Add(new SelectListItem { Text = "W:", Value = "W:" });
Profile_connect.Add(new SelectListItem { Text = "X:", Value = "X:" });
Profile_connect.Add(new SelectListItem { Text = "Y:", Value = "Y:" });
Profile_connect.Add(new SelectListItem { Text = "Z:", Value = "Z:" });
UserSearchModifyViewModel USVM = new UserSearchModifyViewModel()
{
domains = DomainItem,
searchcriteria = searchcriteria,
searchtype = searchtype,
searchfield = searchfield,
groupdomain = DomainItem,
Profile_connect = Profile_connect,
};
return View(USVM);
}
else
return View();//返回结果集合
}
[HttpPost]
public JsonResult SearchModify()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string domain = Request.Form["domain"].Trim().ToString();
string searchfield = Request.Form["searchfield"].Trim().ToString();
string searchcriteria = Request.Form["searchcriteria"].Trim().ToString();
string searchtype = Request.Form["searchtype"].Trim().ToString();
string searchkeyword = Request.Form["searchkeyword"].Trim().ToString();
string message1 = "domain:" + domain + ";searchcriteria:" + searchcriteria + ";searchfield:" + searchfield + ";searchtype:" + searchtype;
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col;
DateTime dt = new DateTime();
if (searchkeyword.Trim() == "")
{
col = ad_user.SearchAllUserDTO(searchkeyword, domain, Int32.Parse(searchfield), 0, Int32.Parse(searchtype));
}
else
{
col = ad_user.SearchAllUserDTO(searchkeyword, domain, Int32.Parse(searchfield), Int32.Parse(searchcriteria), Int32.Parse(searchtype));
}
string con = "<table id = \"example\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>UserID</th><th>First Name</th><th>Last Name</th><th>UserPrincipal Name</th><th>Full Name</th><th>Company</th><th>Mail</th><th>ID Manager</th><th>Exchange Modify</th></tr></thead><tbody>";
for (int i = 0; i < col.Count; i++)
{
UserDTO ud = col.ElementAt(i);
dt= ud.AccountExpDate;
con += "<tr onclick=\"User_detail(this)\"><td id=\"ID" + i + "\">" + i + "</td><td id=\"UserID" + i + "\">" + ud.UserID + "</td><td id=\"FirstName" + i + "\">" + ud.FirstName + "</td><td id=\"LastName" + i + "\">" + ud.LastName + "</td><td id=\"UserPrincipalName" + i + "\">" + simplify(ud.UserPrincipalName) + "</td><td id=\"FirstName" + i + "\">" + simplify(ud.DisplayName) + "</td><td id=\"Company" + i + "\">" + ud.Company + "</td><td id=\"mail" + i + "\">" + simplify(ud.mail) +
"</td><td id=\"managedBy" + i + "\">" + ud.managedBy + "</td><td ><a type=\"button\" onclick=\"verifyExchange(this)\" target=\"_blank\" class=\"btn btn - block\">Modify</a></td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
// LogHelper.WriteLog(typeof(UserManagementController),Operator,"Search%Users",true);
return Json(new JsonData(con));
}
public string simplify(string text) //表格部分文本太长只显示部分
{
if (text.Length>40)
{
string str = text.Substring(0, 35);
return str;
}
else
{
return text;
}
}
public JsonResult Details()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string userid = Request.Form["userid"].Trim().ToString();
string domainname = Request.Form["domainname"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(userid, domainname, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
Directory ad_directory = HttpContext.Application["ad_directory"] as Directory;
List<string> upnname = ad_directory.uPNSuffixes;
string con = "<table id = \"Memberof\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>GroupName</th></tr></thead><tbody>";
for (int i = 0; i < ud.MemberOf.Count; i++)
{
string memberof = ud.MemberOf.ElementAt(i);
con += "<tr><td>" + i + "</td><td>" + memberof + "</td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
userdto userdto = new userdto(ud, con,upnname);
return Json(userdto, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Modify()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
}
//Log日志要记录的用户名
string action = Request.Form["action"].Trim().ToString();
string upnname = Request.Form["upnname"].Trim().ToString();
string username = Request.Form["username"].Trim().ToString();
string userid = Request.Form["userid"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string oupath = Request.Form["oupath"].ToString();
string firstname = Request.Form["firstname"].Trim().ToString();
string lastname = Request.Form["lastname"].Trim().ToString();
string displayname = Request.Form["displayname"].Trim().ToString();
string description = Request.Form["description"].Trim().ToString();
string office = Request.Form["office"].Trim().ToString();
string telephone = Request.Form["telephone"].Trim().ToString();
string mail = Request.Form["mail"].Trim().ToString();
string Address = Request.Form["Address"].Trim().ToString();
string PostOfficeBox = Request.Form["PostOfficeBox"].Trim().ToString();
string City = Request.Form["City"].Trim().ToString();
string admindisplayname = Request.Form["admindisplayname"].Trim().ToString();
string comment = Request.Form["comment"].Trim().ToString();
string adminDescription = Request.Form["adminDescription"].Trim().ToString();
string Company = Request.Form["Company"].Trim().ToString();
string PostalCode = Request.Form["PostalCode"].Trim().ToString();
string LoginScript = Request.Form["LoginScript"].Trim().ToString();
string LocalPath = Request.Form["LocalPath"].Trim().ToString();
string Pager = Request.Form["Pager"].Trim().ToString();
string Province = Request.Form["Province"].Trim().ToString();
string MobilePhone = Request.Form["MobilePhone"].Trim().ToString();
string Title = Request.Form["Title"].Trim().ToString();
string Department = Request.Form["Department"].Trim().ToString();
string accountExpireDate = Request.Form["accountExpireDate"].ToString();
string profilePath = Request.Form["profilePath"].Trim().ToString();
string homeDrive = Request.Form["homeDrive"].Trim().ToString();
string scriptPath = Request.Form["scriptPath"].Trim().ToString();
string homeDirectory = Request.Form["homeDirectory"].Trim().ToString();
string numberof = Request.Form["numberof"].ToString();
int leng= numberof.Split(',').Length;
List<string> MemberOf = new List<string>();
for(int i = 0; i < leng-1; i++)
{
MemberOf.Add(numberof.Split(',')[i]);
}
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(username, domain, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
ud.FirstName = firstname;
ud.scriptPath = scriptPath;
ud.homeDrive = homeDrive;
ud.homeDirectory = homeDirectory;
ud.PostalCode = PostalCode;
ud.UserPrincipalName = upnname;
ud.Pager = Pager;
ud.Province = Province;
ud.profilePath = profilePath;
ud.MobilePhone = MobilePhone;
ud.Title = Title;
ud.Department = Department;
ud.UserID = userid;
if (accountExpireDate != "Never")
{
DateTime dt = Convert.ToDateTime(accountExpireDate);
ud.AccountExpDate = dt;
}else
{
ud.AccountExpDate = DateTime.MinValue;
}
ud.Address = Address;
ud.PostOfficeBox = PostOfficeBox;
ud.City = City;
ud.adminDescription = adminDescription;
ud.adminDisplayName = admindisplayname;
ud.comment = comment;
ud.LastName = lastname;
ud.DisplayName = displayname;
ud.Description = description;
ud.Office = office;
ud.Telephone = telephone;
ud.mail = mail;
ud.Company = Company;
ud.MemberOf = MemberOf;
if (action == "enable")
{
ud.AccountDisabled = false;
}
else
{
ud.AccountDisabled = true;
}
string m;
string a = "";
if (oupath != "")
{
if (ad_user.UpdateUserDTO(ud,ref a) && ad_user.MoveUserIntoNewOU(ud, oupath))
{
m = "Successful modification!";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Modify%the%information%of%" + upnname, true);
return Json(new JsonData(m, true));
}
else
{
m = "Modify failed!";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Modify%the%information%of%" + upnname, false);
return Json(new JsonData(m, false));
}
}
else
{
if (ad_user.UpdateUserDTO(ud,ref a))
{
m = "Successful modification!";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Modify%the%information%of%" + upnname, true);
return Json(new JsonData(m, true));
}
else
{
m = "Modify failed!";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Modify%the%information%of%" + upnname, false);
return Json(new JsonData(m, false));
}
}
}
public JsonResult Delete()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string userid = Request.Form["userid"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(userid, domain, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
string m;
if (ad_user.DeleteUserDTO(ud))
{
m = "Delete success";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Delete%a%user%named%" + userid, true);
}
else
{
m = "Delete failed";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Delete%a%user%named%" + userid, false);
}
return Json(new JsonData(m));
}
[HttpGet]
public ActionResult Create(string abc)
{
string currentdomain = (string)Session["domain"];
Users ad_user;
List<string> DomainLst = HttpContext.Application["domains"] as List<string>;
if (DomainLst.Count > 0)
{
ad_user = HttpContext.Application["ad_user"] as Users;
List<SelectListItem> DomainItem = new List<SelectListItem>();
if (currentdomain != null)
{
DomainItem.Add(new SelectListItem { Text = currentdomain, Value = currentdomain });
}
foreach (var Item in DomainLst)
{
if (Item.ToString() != currentdomain) { DomainItem.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() }); }
}
List<SelectListItem> accounttype = new List<SelectListItem>(); //为searchfield添加下拉选项
accounttype.Add(new SelectListItem { Text = "User Employee ", Value = "1" });
accounttype.Add(new SelectListItem { Text = "User Consultant", Value = "2" });
accounttype.Add(new SelectListItem { Text = "User Extranet", Value = "3" });
accounttype.Add(new SelectListItem { Text = "Service Account", Value = "4" });
UserCreateModel UCM = new UserCreateModel()
{
domains = DomainItem,
accounttype = accounttype,
};
return View(UCM);
}
else
return View();//返回结果集合
}
[HttpPost]
public JsonResult CreateUser()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string message = "";
string memberof = Request.Form["membersof"].Trim().ToString();
int leng = memberof.Split(',').Length;
List<string> MemberOf = new List<string>();
for (int i = 0; i < leng - 1; i++)
{
MemberOf.Add(memberof.Split(',')[i]);
}
string OuPath = Request.Form["OuPath"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string userlogonname = Request.Form["userlogonname"].Trim().ToString();
string firstname = Request.Form["firstname"].Trim().ToString();
string lastname = Request.Form["lastname"].Trim().ToString();
string fullname = Request.Form["fullname"].Trim().ToString();
string password = Request.Form["password"].Trim().ToString();
string umcpanl = Request.Form["umcpanl"].Trim().ToString();
string uccp = Request.Form["uccp"].Trim().ToString();
string pne = Request.Form["pne"].Trim().ToString();
string aid = Request.Form["aid"].Trim().ToString();
string AccountLockouttime = Request.Form["AccountLockouttime"].Trim().ToString();
string officephone = Request.Form["officephone"].Trim().ToString();
string Department = Request.Form["Department"].Trim().ToString();
string Manager = Request.Form["Manager"].Trim().ToString();
string Company = Request.Form["Company"].Trim().ToString();
string EmployeeID = Request.Form["EmployeeID"].Trim().ToString();
string Office = Request.Form["Office"].Trim().ToString();
string Country = Request.Form["Country"].Trim().ToString();
string City = Request.Form["City"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
UserDTO ud = new UserDTO();
ud.City = City;
ud.MemberOf = MemberOf;
ud.Company = Company;
ud.Office = Office;
ud.managedBy = Manager;
ud.Department = Department;
ud.FirstName = firstname;
ud.LastName = lastname;
if (pne.Equals("true"))
{
ud.PasswordNeverExpires = true;
}
if (uccp.Equals("true"))
{
ud.PasswordCantChange = true;
}
if (umcpanl.Equals("true"))
{
ud.MustChangePassword = true;
}
if (aid.Equals("true"))
{
ud.AccountLocked = true;
}
ud.UserPrincipalName = userlogonname + "@" + domain;
ud.DisplayName = firstname + " " + lastname;
ud.UserID = userlogonname;
string errLevel = "";
if (ad_user.CreateUserDTO(ud, OuPath, password, ref errLevel))
{
message = "User: <span style=\"color:green\">" + userlogonname + "</span> create successful";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Create%user%named%" + userlogonname, true);
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/UserDetail.xml"));
XmlNode rootnode = doc.SelectSingleNode("ADUserDetail");
XmlElement xe1 = doc.CreateElement("user");
xe1.SetAttribute("Name", userlogonname);
XmlElement xesub1 = doc.CreateElement("CreateBy");
xesub1.InnerText = Operator;
xe1.AppendChild(xesub1);
XmlElement xesub2 = doc.CreateElement("CreateTime");
xesub2.InnerText = DateTime.Today.ToString("yyyyMMdd");
xe1.AppendChild(xesub2);
XmlElement xesub3 = doc.CreateElement("LatestLogin");
xesub3.InnerText = "";
xe1.AppendChild(xesub3);
rootnode.AppendChild(xe1);
doc.Save(Server.MapPath("~/UserDetail.xml"));
}
else
{
message = "User created failed, may be the user <span style=\"color:green\">" + userlogonname + "</span> already exists.";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Create%user%named%" + userlogonname, false);
}
return Json(new JsonData(message));
}
[HttpPost]
public JsonResult RandomPass()
{
string randompass = COMMON.GenerateRandomPassword();
return Json(new JsonData(randompass), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult ChangePass()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string username = Request.Form["username"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string newpass = Request.Form["newpass"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(username, domain, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
string m;
if (ad_user.ResetUserDTOPwd(ud, newpass))
{
m = "Password modification success";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Modified%the%password%of" + username, true);
}
else
{
m = "Password modification failed";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Modified%the%password%of" + username, false);
}
return Json(new JsonData(m));
}
public JsonResult Outree()
{
string currentdomain = (string)Session["domain"];
string domain = Request.QueryString["domain"].ToString();
TreeNodeCollection tnc;
//string admin = ConfigurationManager.AppSettings["ServiceAccount"];
//string password = <PASSWORD>(ConfigurationManager.AppSettings["ServiceAccountPWD"]);
//Directory ad_directory = new Directory(admin,password,"<PASSWORD>");
// Directory ad_directory = HttpContext.Application["ad_directory"] as Directory;
if (OuTreeCache.GetCache(domain) != null)
{
tnc = (TreeNodeCollection)OuTreeCache.GetCache(domain);
}
else
{
tnc = (TreeNodeCollection)OuTreeCache.GetCache(currentdomain);
}
//TreeNodeCollection tnc = ad_directory.TreeView.Nodes;
OuTreeModel ou = getTree(tnc[0], 1);
List<OuTreeModel> result = new List<OuTreeModel>();
result.Add(ou);
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult inite_Outree()
{
string currentdomain = (string)Session["domain"];
//string admin = ConfigurationManager.AppSettings["ServiceAccount"];
//string password = <PASSWORD>.Decrypt(ConfigurationManager.AppSettings["ServiceAccountPWD"]);
//Directory ad_directory = new Directory(admin,password,"<PASSWORD>");
// Directory ad_directory = HttpContext.Application["ad_directory"] as Directory;
TreeNodeCollection tnc = (TreeNodeCollection)OuTreeCache.GetCache(currentdomain);
//TreeNodeCollection tnc = ad_directory.TreeView.Nodes;
OuTreeModel ou = getTree(tnc[0], 1);
List<OuTreeModel> result = new List<OuTreeModel>();
result.Add(ou);
return Json(result, JsonRequestBehavior.AllowGet);
}
public OuTreeModel getTree(TreeNode tnc, int m)
{
OuTreeModel model = new OuTreeModel();
model.id = m++;
model.text = tnc.Text;
model.path = tnc.ToolTip;
model.children = new List<OuTreeModel>();
if (tnc.ChildNodes.Count > 0)
{
foreach (TreeNode node in tnc.ChildNodes)
{
OuTreeModel childmodel = new OuTreeModel();
childmodel.children = new List<OuTreeModel>();
childmodel.text = node.Text;
m = 10 + m++;
childmodel.id = m;
childmodel.path = node.ToolTip;
if (node.ChildNodes.Count > 0)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
childmodel.state = "closed";
childmodel.children.Add(getTree(node.ChildNodes[i], m * 10));
}
}
model.children.Add(childmodel);
}
}
return model;
}
[HttpPost]
public JsonResult EnableLync()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string username = Request.Form["username"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string action = Request.Form["action"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(username, domain, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
SkypeForBusinessDTO sip = new SkypeForBusinessDTO(ud);
string mess = "";
string m;
if (action == "enable")
{
if (sip.EnableSIP(ref mess))
{
m = mess;
// LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Succeed", true);
}
else
{
m = mess;
// LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Failed", false);
}
}
else
{
if (sip.DisableSIP(ref mess))
{
m = mess;
//LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Succeed", true);
}
else
{
m = mess;
// LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Failed", false);
}
}
return Json(new JsonData(m));
}
[HttpPost]
public JsonResult EnableExchange()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string username = Request.Form["username"].Trim().ToString();
string exchangeType = Request.Form["exchangeType"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string action = Request.Form["action"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(username, domain, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
ExchangeMailboxDTO EMD = new ExchangeMailboxDTO(ud);
string m;
string mess = "";
if (action == "enable")
{
EMD.AccountType = exchangeType;
if (EMD.EnableMailbox(ref mess))
{
m = "Successful modification!";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Succeed", true);
}
else
{
m = mess;
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Failed", false);
}
}
else
{
if (EMD.DisableMailbox(ref mess))
{
m = "Successful modification!";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Succeed", true);
}
else
{
m = mess;
LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Failed", false);
}
}
return Json(new JsonData(m));
}
public JsonResult EnableAccount()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string username = Request.Form["username"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string action = Request.Form["action"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(username, domain, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
string m;
string a = "";
if (action == "enable")
{
ud.AccountDisabled = false;
if (ad_user.UpdateUserDTO(ud,ref a))
{
m = "Enable account success";
// LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Succeed", true);
}
else
{
m = "Enable account failed";
// LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Failed", false);
}
}
else
{
ud.AccountDisabled = true;
if (ad_user.UpdateUserDTO(ud,ref a))
{
m = "Disable account success";
// LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Succeed", true);
}
else
{
m = "Disable account failed";
// LogHelper.WriteLog(typeof(UserManagementController), Operator, "Disable%the%Lync%of%" + username + "Failed", false);
}
}
return Json(new JsonData(m));
}
[HttpPost]
public JsonResult AccountUnlock()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string username = Request.Form["username"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(username, domain, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
ud.AccountDisabled = false;
string m;
string a = "";
if (ad_user.UpdateUserDTO(ud,ref a))
{
m = "Unlock account success";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "UnLock%the%Account%of%" + username, true);
}
else
{
m = "Unlock failed!";
LogHelper.WriteLog(typeof(UserManagementController), Operator, "UnLock%the%Account%of%" + username, false);
}
return Json(new JsonData(m));
}
[HttpGet]
public ActionResult ModifyExchange(string abc)
{
string userid = Request.QueryString["userid"].Trim().ToString();
string domainname = Request.QueryString["domain"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(userid, domainname, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
ExchangeMailboxDTO EMD = new ExchangeMailboxDTO(ud);
List<SelectListItem> Database = new List<SelectListItem>();
string currentdb = EMD.homeMDB;
Database.Add(new SelectListItem { Text = currentdb, Value = currentdb });
foreach (var Item in EMD.MDBs)
{
if (Item.Name != currentdb)
{
Database.Add(new SelectListItem { Text = Item.Name, Value = Item.Name });
}
}
List<SelectListItem> EAitem = new List<SelectListItem>();
string currentaddress = EMD.PrimaryEmailAddress.Split('@')[1];
EAitem.Add(new SelectListItem { Text = currentaddress, Value = currentaddress });
foreach (var Item in EMD.AcceptedDomain)
{
if (Item.ToString() != currentaddress) { EAitem.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() }); }
}
List<SelectListItem> MailboxPolicys = new List<SelectListItem>();
string Policys = EMD.ActiveSyncMailboxPolicy;
MailboxPolicys.Add(new SelectListItem { Text = Policys, Value = Policys });
foreach (var Item in EMD.ActiveSyncMailboxPolicys)
{
if (Item.ToString() != Policys) { MailboxPolicys.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() }); }
}
List<SelectListItem> QuotaPlan = new List<SelectListItem>();
string Quotas = EMD.MailboxQuota.Name;
QuotaPlan.Add(new SelectListItem { Text = Quotas, Value = Quotas });
foreach (var Item in EMD.QuotaPlan)
{
if (Item.Name.ToString() != Quotas) { QuotaPlan.Add(new SelectListItem { Text = Item.Name.ToString(), Value = Item.Name.ToString() }); }
}
ExchangeModel Em = new ExchangeModel()
{
AccountType = EMD.AccountType,
DataCenter = EMD.DataCenter,
EmailAddress = EMD.PrimaryEmailAddress.Split('@')[0],
LinkedAccountname = EMD.LinkedAccount[1],
SendAsDelegates = EMD.SendAsDelegates,
FMADelegates = EMD.FMADelegates,
Database = Database,
EAitem = EAitem,
LinkedAccountdomain = EMD.LinkedAccount[0],
BlackBerryEnabled=EMD.BlackBerryEnabled,
IMAPEnabled =EMD.IMAPEnabled,
POP3Enabled =EMD.POP3Enabled,
HideFromOAB =EMD.HideFromOAB,
RestrictedUsage =EMD.RestrictedUsage,
MailboxPolicys = MailboxPolicys,
QuotaPlan=QuotaPlan,
DisplayName=EMD.DisplayName,
};
return View(Em);
}
public JsonResult Group_GroupSearch()
{
//Log日志要记录的用户名
string domain = Request.Form["groupdomain"].Trim().ToString();
string searchkeyword = Request.Form["searchkeyword"].ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col;
if (searchkeyword.Trim() == "")
{
col = ad_group.SearchAllGroupsDTO(domain);
}
else
{
col = ad_group.SearchAllGroupsDTO(searchkeyword, domain);
}
string con = "<table id = \"GroupChose\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>Name</th></tr></thead><tbody>";
for (int i = 0; i < col.Count; i++)
{
GroupsDTO gd = col.ElementAt(i);
con += "<tr><td>" + i + "</td><td>" + gd.Name + "</td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
return Json(new JsonData(con));
}
public JsonResult GroupSearch()
{
//Log日志要记录的用户名
string domain = Request.Form["groupdomain"].Trim().ToString();
string searchkeyword = Request.Form["searchkeyword"].ToString();
string userid = Request.Form["userid"].Trim().ToString();
string domainname = Request.Form["domainname"].Trim().ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col;
if (searchkeyword.Trim() == "")
{
col = ad_group.SearchAllGroupsDTO(domain);
}
else
{
col = ad_group.SearchAllGroupsDTO(searchkeyword, domain);
}
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col1 = ad_user.SearchAllUserDTO(userid, domainname, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col1.ElementAt(0);
string con = "<table id = \"GroupChose\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>Name</th></tr></thead><tbody>";
for (int i = 0; i < col.Count; i++)
{
GroupsDTO gd = col.ElementAt(i);
if (Array.IndexOf<string>(ud.MemberOf.ToArray(), gd.Name) == -1) {
con += "<tr><td>" + i + "</td><td>" + gd.Name + "</td></tr>";//数据行,字段对应数据库查询字段
}
}
con += " </tbody></table>";
return Json(new JsonData(con));
}
public JsonResult GroupSearch_Group()
{
//Log日志要记录的用户名
string domain = Request.Form["groupdomain"].Trim().ToString();
string searchkeyword = Request.Form["searchkeyword"].ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col;
if (searchkeyword.Trim() == "")
{
col = ad_group.SearchAllGroupsDTO(domain);
}
else
{
col = ad_group.SearchAllGroupsDTO(searchkeyword, domain);
}
string con = "<table id = \"GroupChose\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>Name</th></tr></thead><tbody>";
for (int i = 0; i < col.Count; i++)
{
GroupsDTO gd = col.ElementAt(i);
con += "<tr><td>" + i + "</td><td>" + gd.Name + "</td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
return Json(new JsonData(con));
}
public ActionResult Report()
{
List<UserDetail> data = new List<UserDetail>();
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/UserDetail.xml"));
XmlNode node = doc.SelectSingleNode("ADUserDetail");
XmlNodeList xnl = node.ChildNodes;
int i = 0;
foreach (XmlNode xn1 in xnl)
{
UserDetail user = new UserDetail();
// 将节点转换为元素,便于得到节点的属性值
XmlElement xe = (XmlElement)xn1;
// 得到Type和ISBN两个属性的属性值
user.id = i++;
user.name = xe.GetAttribute("Name").ToString();
XmlNodeList xnl0 = xe.ChildNodes;
user.Createby = xnl0.Item(0).InnerText;
user.CreateTime = xnl0.Item(1).InnerText;
user.LatestLogin = xnl0.Item(2).InnerText;
data.Add(user);
}
UserDetailModel UM = new UserDetailModel()
{
userdetail=data,
};
return View(UM);
}
public JsonResult verifyExchange()
{
string mess = "";
string userid = Request.Form["userid"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(userid, domain, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
if (ud.ExchangeEnabled)
{
mess = userid + "@" + domain;
return Json(new JsonData(mess, true));
}
else
{
mess = "Exchange is not yet enable, please enable before use! ";
return Json(new JsonData(mess,false));
}
}
public JsonResult UPNName()
{
string username = Request.Form["username"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = new List<UserDTO>();
int counter;
try
{
col = ad_user.SearchAllUserDTO(username, domain, 0, 1, 0);
counter = col.Count;
}catch(Exception e)
{
counter = 0;
}
return Json(new JsonData(counter.ToString()));
}
public JsonResult Testmanager() //创建用户时检测当前domain是否存在该用户
{
string userid = Request.Form["manager"].Trim().ToString();
string domainname = Request.Form["domain"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(userid, domainname, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
if (col.Count > 0)
{
string memeberof = "";
UserDTO ud = col.ElementAt(0);
for(int i = 0; i < ud.MemberOf.Count; i++)
{
memeberof += ud.MemberOf[i] + ",";
}
userdto userdto = new userdto(ud, memeberof,1);
return Json(userdto, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new JsonData("The User You Typed Is Not Existed!"));
}
}
}
}<file_sep>/Ad Tools/Ad Tools/Models/computerdto.cs
using Ad_Tools.Common;
using ADTOOLS.DTO;
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Net;
using System.Web;
namespace Ad_Tools.Models
{
public class computerdto
{
public string Address { get; set; }
public string ADName { get; set; }
public string AssetNumber { get; set; }
public string CNName { get; set; }
public string company { get; set; }
public string ComputerOnwer { get; set; }
// private ComputerPrincipal ComputerPrin { get; set; }
public string Description { get; set; }
// private DirectoryEntry DirEntry { get; set; }
public string DistinguishedName { get; set; }
public string dNSHostName { get; set; }
public string FPC { get; set; }
// public IPAddress[] ip { get; set; }
public string LastLoggedUser { get; set; }
public string LDAPPath { get; set; }
public string managedBy { get; set; }
public string Name { get; set; }
public string operatingSystem { get; set; }
public string operatingSystemVersion { get; set; }
public string OU_CNName { get; set; }
public string OUName { get; set; }
public string site { get; set; }
public string Telephone { get; set; }
public string TypeName { get; set; }
public computerdto(ComputerDTO dt)
{
this.Address = dt.Address;
this.ADName = dt.ADName;
this.AssetNumber = dt.AssetNumber;
this.CNName = dt.CNName;
this.company = dt.company;
this.ComputerOnwer = dt.ComputerOnwer;
this.Description = dt.Description;
this.DistinguishedName = dt.DistinguishedName;
this.dNSHostName = dt.dNSHostName;
this.FPC = dt.FPC;
this.LastLoggedUser = dt.LastLoggedUser;
this.LDAPPath = dt.LDAPPath;
this.managedBy = dt.managedBy;
this.Name = dt.Name;
this.operatingSystem = dt.operatingSystem;
this.operatingSystemVersion = dt.operatingSystemVersion;
this.OUName = OuString.OuStringFormat(dt.OUName);
this.site = dt.site;
this.Telephone = dt.Telephone;
this.TypeName = dt.TypeName;
}
}
}<file_sep>/Ad Tools/Ad Tools/Controllers/GroupsManagementController.cs
using Ad_Tools.Log4net;
using Ad_Tools.Models;
using ADTOOLS.AD;
using ADTOOLS.DTO;
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Web.Mvc;
using System.Xml;
namespace Ad_Tools.Controllers
{
public class GroupsManagementController : BaseController
{
// GET: GroupsManagement
public ActionResult SearchModify()
{
string currentdomain = (string)Session["domain"];
List<string> DomainLst = HttpContext.Application["domains"] as List<string>;
if (DomainLst.Count > 0)
{
List<SelectListItem> DomainItem = new List<SelectListItem>();
if (currentdomain != null)
{
DomainItem.Add(new SelectListItem { Text = currentdomain, Value = currentdomain });
}
foreach (var Item in DomainLst)
{
if (Item.ToString() != currentdomain) { DomainItem.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() }); }
}
List<SelectListItem> searchcriteria = new List<SelectListItem>();
searchcriteria.Add(new SelectListItem { Text = "Equals", Value = "1" });
searchcriteria.Add(new SelectListItem { Text = "Contains", Value = "2" });
searchcriteria.Add(new SelectListItem { Text = "Stars with", Value = "3" });
searchcriteria.Add(new SelectListItem { Text = "Ends with", Value = "4" });
List<SelectListItem> searchfield = new List<SelectListItem>(); //为searchfield添加下拉选项
searchfield.Add(new SelectListItem { Text = "UserID", Value = "0" });
searchfield.Add(new SelectListItem { Text = "First Name", Value = "1" });
searchfield.Add(new SelectListItem { Text = "Last Name", Value = "2" });
searchfield.Add(new SelectListItem { Text = "Full Name", Value = "3" });
searchfield.Add(new SelectListItem { Text = "Company", Value = "4" });
searchfield.Add(new SelectListItem { Text = "Mail", Value = "5" });
searchfield.Add(new SelectListItem { Text = "ID Manager", Value = "6" });
GroupSearchViewModels CSVM = new GroupSearchViewModels()
{
domains = DomainItem,
searchfield = searchfield,
searchcriteria = searchcriteria,
};
return View(CSVM);
}
else
return View();//返回结果集合
}
[HttpPost]
public JsonResult Search()
{
//Log日志要记录的用户名
string domain = Request.Form["domain"].Trim().ToString();
string searchkeyword = Request.Form["searchkeyword"].ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col;
if (searchkeyword.Trim() == "")
{
col = ad_group.SearchAllGroupsDTO(domain);
}
else
{
col = ad_group.SearchAllGroupsDTO(searchkeyword, domain);
}
string con = "<table id = \"example\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>Name</th><th>BelongsOUPath</th><th>Description</th><th>Exchange Modify</th></tr></thead><tbody>";
for (int i = 0; i < col.Count; i++)
{
GroupsDTO gd = col.ElementAt(i);
con += "<tr" + " " + "onclick=\"Group_detail(this)\"><td>" + i + "</td><td>" + gd.Name + "</td><td>" + gd.BelongsOUPath + "</td><td>" + gd.Description + "</td><td ><a type=\"button\" onclick=\"ExchangeEnabled(this)\" target=\"_blank\" class=\"btn btn - block\">Modify</a></td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
return Json(new JsonData(con));
}
public ActionResult Report()
{
List<GroupDetail> data = new List<GroupDetail>();
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/GroupDetail.xml"));
XmlNode node = doc.SelectSingleNode("ADGroupDetail");
// 得到根节点的所有子节点
XmlNodeList xnl = node.ChildNodes;
int i = 0;
foreach (XmlNode xn1 in xnl)
{
GroupDetail group = new GroupDetail();
// 将节点转换为元素,便于得到节点的属性值
XmlElement xe = (XmlElement)xn1;
// 得到Type和ISBN两个属性的属性值
group.id = i++;
group.name = xe.GetAttribute("Name").ToString();
XmlNodeList xnl0 = xe.ChildNodes;
group.Createby = xnl0.Item(0).InnerText;
group.CreateTime = xnl0.Item(1).InnerText;
data.Add(group);
}
GroupDetailModel GM = new GroupDetailModel()
{
groupdetail = data,
};
return View(GM);
}
[HttpGet]
public ActionResult Create(string abc)
{
string currentdomain = (string)Session["domain"];
List<string> DomainLst = HttpContext.Application["domains"] as List<string>;
if (DomainLst.Count > 0)
{
List<SelectListItem> DomainItem = new List<SelectListItem>();
if (currentdomain != null)
{
DomainItem.Add(new SelectListItem { Text = currentdomain, Value = currentdomain });
}
foreach (var Item in DomainLst)
{
if (Item.ToString() != currentdomain) { DomainItem.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() }); }
}
GroupCreateViewModels GCVM = new GroupCreateViewModels()
{
domains = DomainItem,
};
return View(GCVM);
}
else
return View();//返回结果集合
}
[HttpPost]
public JsonResult Create()
{
string msg = "";
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
}
string OuPath = Request.Form["OuPath"].Trim().ToString(); //Log日志要记录的用户名
string groupname = Request.Form["groupname"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string grouptype = Request.Form["grouptype"].Trim().ToString();
string groupscope = Request.Form["groupscope"].Trim().ToString();
string EnableExchange = Request.Form["EnableExchange"].Trim().ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
GroupsDTO gd = new GroupsDTO();
gd.BelongsOUPath = OuPath;
gd.SamAccountName = groupname;
if (grouptype.Equals("Security"))
{
gd.isSecurityGroup = true;
}
if (groupscope.Equals("DomainLocale"))
{
gd.GroupScope = GroupScope.Local;
}
else if (groupscope.Equals("Gloable"))
{
gd.GroupScope = GroupScope.Global;
}
else
{
gd.GroupScope = GroupScope.Universal;
}
string message;
if (ad_group.CreateUserGroup(gd))
{
if (EnableExchange.Equals("true"))
{
List<GroupsDTO> col = ad_group.SearchAllGroupsDTO(groupname, domain);
GroupsDTO gd2 = col.ElementAt(0);
ExchangeDistributionGroupDTO EDG = new ExchangeDistributionGroupDTO(gd2);
if (EDG.EnableDistributionGroup(ref msg))
{
gd2.ExchangeEnabled = true;
EDG = new ExchangeDistributionGroupDTO(gd2);
}
else
{
msg = "error";
}
}
message = "Group:<span style =\"color:green\">" + groupname + "</span> create successful";
LogHelper.WriteLog(typeof(GroupsManagementController), Operator, "Create%Group%named%" + groupname, true);
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/GroupDetail.xml"));
XmlNode rootnode = doc.SelectSingleNode("ADGroupDetail");
XmlElement xe1 = doc.CreateElement("user");
xe1.SetAttribute("Name", groupname);
XmlElement xesub1 = doc.CreateElement("CreateBy");
xesub1.InnerText = Operator;
xe1.AppendChild(xesub1);
XmlElement xesub2 = doc.CreateElement("CreateTime");
xesub2.InnerText = DateTime.Today.ToString("yyyyMMdd");
xe1.AppendChild(xesub2);
rootnode.AppendChild(xe1);
doc.Save(Server.MapPath("~/GroupDetail.xml"));
}
else
{
message = "Name for group <span style =\"color:green\">" + groupname + "</span>creation failed,It could be that the group already exists";
LogHelper.WriteLog(typeof(GroupsManagementController), Operator, "Create%Group%named%" + groupname, false);
}
return Json(new JsonData(message));
}
[HttpPost]
public JsonResult Details()
{
//Log日志要记录的用户名
string groupname = Request.Form["groupname"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col = ad_group.SearchAllGroupsDTO(groupname, domain);
GroupsDTO gd = col.ElementAt(0);
string con = "<table id = \"Memberof\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>GroupName</th></tr></thead><tbody>";
for (int i = 0; i < gd.MembersOf.Count; i++)
{
string memberof = gd.MembersOf.ElementAt(i);
con += "<tr><td>" + i + "</td><td>" + memberof + "</td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
string members = "<table id = \"Mem\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>MembersName</th></tr></thead><tbody>";
for (int i = 0; i < gd.Members.Count; i++)
{
string mem = gd.Members.ElementAt(i);
members += "<tr><td>" + i + "</td><td>" + mem + "</td></tr>";//数据行,字段对应数据库查询字段
}
members += " </tbody></table>";
groupdto gdt = new groupdto(gd, con, members);
return Json(gdt, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Update()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string name = Request.Form["name"].ToString();
string groupname = Request.Form["groupname"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string oupath = Request.Form["oupath"].ToString();
string description = Request.Form["description"].Trim().ToString();
string email = Request.Form["email"].Trim().ToString();
string note = Request.Form["note"].Trim().ToString();
string manageby = Request.Form["manageby"].ToString();
string numberof = Request.Form["numberof"].ToString();
string grouptype = Request.Form["grouptype"].Trim().ToString();
string groupscope = Request.Form["groupscope"].ToString();
int leng = numberof.Split(',').Length;
List<string> MemberOf = new List<string>();
for (int i = 0; i < leng - 1; i++)
{
MemberOf.Add(numberof.Split(',')[i]);
}
string members = Request.Form["Members"].ToString();
int len = members.Split(',').Length;
List<string> Members = new List<string>();
for (int i = 0; i < len - 1; i++)
{
Members.Add(members.Split(',')[i]);
}
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col = ad_group.SearchAllGroupsDTO(name, domain);
GroupsDTO gd = col.ElementAt(0);
if (groupscope.Equals("DomainLocale"))
{
gd.GroupScope = GroupScope.Local;
}
else if (groupscope.Equals("Gloable"))
{
gd.GroupScope = GroupScope.Global;
}
else
{
gd.GroupScope = GroupScope.Universal;
}
if (grouptype.Equals("Security"))
{
gd.isSecurityGroup = true;
}
gd.Description = description;
gd.SamAccountName = groupname;
gd.Email = email;
gd.Note = note;
gd.managedBy = manageby;
gd.MembersOf = MemberOf;
gd.Members = Members;
string m;
string msg = "";
if (oupath != "")
{
if (ad_group.UpdateGroupsDTO(gd, ref msg) && ad_group.MoveGroupIntoNewOU(gd, oupath))
{
m = "Successful modification!";
LogHelper.WriteLog(typeof(GroupsManagementController), Operator, "Modify%the%information%of%" + name.Replace(" ", ""), true);
return Json(new JsonData(m, true));
}
else
{
m = "Modify failed! " + msg;
LogHelper.WriteLog(typeof(GroupsManagementController), Operator, "Modify%the%information%of%" + name.Replace(" ", ""), false);
return Json(new JsonData(m, false));
}
}
else
{
if (ad_group.UpdateGroupsDTO(gd, ref msg))
{
m = "Successful modification!";
LogHelper.WriteLog(typeof(GroupsManagementController), Operator, "Modify%the%information%of%" + name.Replace(" ", ""), true);
return Json(new JsonData(m, true));
}
else
{
m = "Modify failed! " + msg;
LogHelper.WriteLog(typeof(GroupsManagementController), Operator, "Modify%the%information%of%" + name.Replace(" ", ""), false);
return Json(new JsonData(m, false));
}
}
}
[HttpPost]
public JsonResult Delete()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string groupname = Request.Form["groupname"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col = ad_group.SearchAllGroupsDTO(groupname, domain);
GroupsDTO gd = col.ElementAt(0);
string m;
if (ad_group.DeleteUserGroupsDTO(gd))
{
m = "Delete Success";
LogHelper.WriteLog(typeof(GroupsManagementController), Operator, "Delete%a%Group%named%" + groupname, true);
}
else
{
m = "Delete failed";
LogHelper.WriteLog(typeof(GroupsManagementController), Operator, "Delete%a%Group%named%" + groupname, false);
}
return Json(new JsonData(m));
}
public ActionResult AuthorityManagement(string abc)
{
string currentdomain = (string)Session["domain"];
List<string> DomainLst = HttpContext.Application["domains"] as List<string>;
if (DomainLst.Count > 0)
{
List<SelectListItem> DomainItem = new List<SelectListItem>();
if (currentdomain != null)
{
DomainItem.Add(new SelectListItem { Text = currentdomain, Value = currentdomain });
}
foreach (var Item in DomainLst)
{
if (Item.ToString() != currentdomain) { DomainItem.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() }); }
}
List<SelectListItem> searchcriteria = new List<SelectListItem>();
searchcriteria.Add(new SelectListItem { Text = "Equals", Value = "1" });
searchcriteria.Add(new SelectListItem { Text = "Contains", Value = "2" });
searchcriteria.Add(new SelectListItem { Text = "Stars with", Value = "3" });
searchcriteria.Add(new SelectListItem { Text = "Ends with", Value = "4" });
GroupSearchViewModels CSVM = new GroupSearchViewModels()
{
domains = DomainItem,
};
return View(CSVM);
}
else
return View();//返回结果集合
}
[HttpPost]
public JsonResult AuthorityManagement()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string domain = Request.Form["domain"].Trim().ToString();
string searchcriteria = Request.Form["searchcriteria"].Trim().ToString();
string searchkeyword = Request.Form["searchkeyword"].ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col;
if (searchkeyword.Trim() == "")
{
col = ad_group.SearchAllGroupsDTO(domain);
}
else
{
col = ad_group.SearchAllGroupsDTO(searchkeyword, domain);
}
string con = "<table id = \"example\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>Name</th></tr></thead><tbody>";
for (int i = 0; i < col.Count; i++)
{
GroupsDTO gd = col.ElementAt(i);
con += "<tr" + " " + "onclick=\"GetAuthorityCode(this)\"><td>" + i + "</td><td>" + gd.Name + "</td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
return Json(new JsonData(con));
}
public JsonResult GetAuthorityCode() //得到权限组的代码,读取per.xml文件
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string groupname = Request.Form["groupname"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string permission = "";
XmlDocument doc = new XmlDocument();
List<String> al = new List<String>();
doc.Load(Server.MapPath("~/per.xml"));
XmlElement root = doc.DocumentElement;
//从session得到用户
permission = "/Authority/" + domain +groupname.Replace(" ", "") + "/Permission";
XmlNode node=root.SelectSingleNode(permission);
if (node != null)
{
String p = node.InnerText;
String[] str = new String[] { };
str = p.Split(',');
for (int j = 0; j < str.Length; j++)
{
al.Add(str[j]);
}
}else
{
XmlNode rootnode = doc.SelectSingleNode("Authority");
XmlElement xe1 = doc.CreateElement(domain + groupname.Replace(" ", ""));
XmlElement xe11 = doc.CreateElement("Permission");
xe11.InnerText = "";
xe1.AppendChild(xe11);
rootnode.AppendChild(xe1);
doc.Save(Server.MapPath("~/per.xml"));
al.Add("");
}
//根据用户从配置文件中得到权限
return Json(al, JsonRequestBehavior.AllowGet);
}
public JsonResult SetAuthorityCode() //设置权限组的代码,存储到per.xml文件
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string message = "";
string groupname = Request.Form["groupname"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string codestr = Request.Form["code"].Trim().ToString();
string realgroupname = groupname.Replace(" ", "");
string permission = "";
XmlDocument doc = new XmlDocument();
List<String> al = new List<String>();
doc.Load(Server.MapPath("~/per.xml"));
XmlElement root = null;
root = doc.DocumentElement;
//从session得到用户
permission = "/Authority/" + domain+ groupname.Replace(" ", "") + "/Permission";
XmlNodeList listNodes = root.SelectNodes(permission);
int num = listNodes.Count;
message = "修改节点";
listNodes[0].InnerXml = codestr;
doc.Save(Server.MapPath("~/per.xml"));
return Json(new JsonData(message));
}
public JsonResult Group_UserSearch()
{
string domain = Request.Form["Udomain"].Trim().ToString();
string searchfield = Request.Form["Usearchfield"].Trim().ToString();
string searchcriteria = Request.Form["Usearchcriteria"].Trim().ToString();
string searchkeyword = Request.Form["Usearchkeyword"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col;
if (searchkeyword.Trim() == "")
{
col = ad_user.SearchAllUserDTO(searchkeyword, domain, Int32.Parse(searchfield), 0, 0);
}
else
{
col = ad_user.SearchAllUserDTO(searchkeyword, domain, Int32.Parse(searchfield), Int32.Parse(searchcriteria), 0);
}
string con = "<table id = \"example1\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>UserID</th><th>OU</th></tr></thead><tbody>";
for (int i = 0; i < col.Count; i++)
{
UserDTO ud = col.ElementAt(i);
con += "<tr><td id=\"ID" + i + "\">" + i + "</td><td>" + ud.UserID + "</td><td>" + ud.DistinguishedName + "</td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
return Json(new JsonData(con));
}
public JsonResult verifyExchange()
{
string mess = "";
string userid = Request.Form["userid"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(userid, domain, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
if (ud.ExchangeEnabled)
{
mess = userid + "@" + domain;
return Json(new JsonData(mess, true));
}
else
{
mess = "Exchange is not yet enable, please enable before use! ";
return Json(new JsonData(mess, false));
}
}
public JsonResult Group_UserSearch_Members()
{
string domain = Request.Form["Mdomain"].Trim().ToString();
string searchfield = Request.Form["Msearchfield"].Trim().ToString();
string searchcriteria = Request.Form["Msearchcriteria"].Trim().ToString();
string searchkeyword = Request.Form["Msearchkeyword"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col;
if (searchkeyword.Trim() == "")
{
col = ad_user.SearchAllUserDTO(searchkeyword, domain, Int32.Parse(searchfield), 0, 0);
}
else
{
col = ad_user.SearchAllUserDTO(searchkeyword, domain, Int32.Parse(searchfield), Int32.Parse(searchcriteria), 0);
}
string con = "<table id = \"MembersData\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>UserID</th></tr></thead><tbody>";
for (int i = 0; i < col.Count; i++)
{
UserDTO ud = col.ElementAt(i);
con += "<tr><td id=\"ID" + i + "\">" + i + "</td><td>" + ud.DisplayName + "</td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
return Json(new JsonData(con));
}
public ActionResult ModifyExchange()
{
string keyword = Request.QueryString["keyword"].Trim().ToString();
string domainname = Request.QueryString["domain"].Trim().ToString();
// string keyword = Request.Form["keyword"].Trim().ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col = ad_group.SearchAllGroupsDTO(keyword, domainname);
GroupsDTO gd = col.ElementAt(0);
ExchangeDistributionGroupDTO EDG = new ExchangeDistributionGroupDTO(gd);
List<SelectListItem> EmailHost = new List<SelectListItem>();
string currentdb = EDG.PrimaryEmailAddress.Split('@')[1];
EmailHost.Add(new SelectListItem { Text = "@" + currentdb, Value = currentdb });
foreach (var Item in EDG.AcceptedDomain)
{
if (Item.ToString() != currentdb)
{
EmailHost.Add(new SelectListItem { Text = "@" + Item.ToString(), Value = Item.ToString() });
}
}
List<SelectListItem> Manager = new List<SelectListItem>();
foreach (var Item in EDG.managedByList)
{
EmailHost.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() });
}
List<SelectListItem> SendersAllowedList = new List<SelectListItem>();
foreach (var Item in EDG.SendersAllowedList)
{
EmailHost.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() });
}
GroupExchangeModel GEM = new GroupExchangeModel()
{
Description = EDG.Description,
DisplayName = EDG.DisplayName,
GroupName = EDG.DisplayName,
managedByList = Manager,
SendersAllowedList = SendersAllowedList,
EmailHost = EmailHost,
Emailname = EDG.PrimaryEmailAddress.Split('@')[0],
HideFromAB = EDG.HideFromOAB,
RequireSenderAuthenticationEnabled = EDG.RequireSenderAuthenticationEnabled,
IndudeinGalsync = EDG.IncludedInGalsync,
};
return View(GEM);
} //显示数据
public JsonResult ExchangModfiy() //后台处理提交的数据并修改
{
string estr = "";
string userid = Request.Form["userid"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string DLShortname = Request.Form["DLShortname"].Trim().ToString();
string GroupName = Request.Form["GroupName"].Trim().ToString();
string Emailname = Request.Form["Emailname"].Trim().ToString();
string RequireSenderAuthenticationEnabled = Request.Form["RequireSenderAuthenticationEnabled"].Trim().ToString();
string IndudeinGalsync = Request.Form["IndudeinGalsync"].Trim().ToString();
string Description = Request.Form["Description"].Trim().ToString();
string DisplayName = Request.Form["DisplayName"].Trim().ToString();
string HideFromOAB = Request.Form["HideFromOAB"].Trim().ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col = ad_group.SearchAllGroupsDTO(userid, domain);
GroupsDTO gd = col.ElementAt(0);
ExchangeDistributionGroupDTO EDG = new ExchangeDistributionGroupDTO(gd);
EDG.Description = Description;
EDG.DisplayName = DisplayName;
if (HideFromOAB == "true")
{
EDG.HideFromOAB = true;
}
else
{
EDG.HideFromOAB = false;
}
if (RequireSenderAuthenticationEnabled == "true")
{
EDG.RequireSenderAuthenticationEnabled = true;
}
else
{
EDG.RequireSenderAuthenticationEnabled = false;
}
bool result = EDG.Update(ref estr);
if (result)
{
return Json(new JsonData("Successful modification!"), JsonRequestBehavior.AllowGet);
}
else
{
return Json(new JsonData(estr), JsonRequestBehavior.AllowGet);
}
}
public JsonResult ExchangeEnabled()
{
string msg = ""; //Log日志要记录的用户名
string groupname = Request.Form["groupname"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col = ad_group.SearchAllGroupsDTO(groupname, domain);
GroupsDTO gd = col.ElementAt(0);
if (gd.ExchangeEnabled)
{
msg = "1";
}
else
{
msg = "0";
}
return Json(new JsonData(msg));
}
public JsonResult EnableGroupExchange()
{
string msg = ""; //Log日志要记录的用户名
string groupname = Request.Form["groupname"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
Groups ad_group = HttpContext.Application["ad_group"] as Groups;
List<GroupsDTO> col = ad_group.SearchAllGroupsDTO(groupname, domain);
GroupsDTO gd = col.ElementAt(0);
if (gd.GroupScope != GroupScope.Universal)
{
gd.GroupScope = GroupScope.Universal;
}
bool result = ad_group.UpdateGroupsDTO(gd, ref msg);
if (result)
{
ExchangeDistributionGroupDTO EDG = new ExchangeDistributionGroupDTO(gd);
if (EDG.EnableDistributionGroup(ref msg))
{
gd.ExchangeEnabled = true;
EDG = new ExchangeDistributionGroupDTO(gd);
msg = "1";
}
else
{
msg = "0";
}
}
else
{
msg = "0";
}
return Json(new JsonData(msg));
}
}
}
<file_sep>/Ad Tools/Ad Tools/Models/ComputerManagementViewModels.cs
using ADTOOLS.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Ad_Tools.Models
{
public class ComputerCreateModels
{
public List<SelectListItem> domains { get; set; }
}
public class ComputerSearchViewModels
{
public List<SelectListItem> domains { get; set; }
public List<SelectListItem> searchcriteria { get; set; }
public string ComputerName { get; set; }
public IEnumerable<ComputerDTO> ComputerLst {get;set;}
public List<SelectListItem> searchfield { get; set; }
}
public class ComputerReport
{
public string ComputerNumber { get; set; }
}
}<file_sep>/Ad Tools/Ad Tools/Scripts/adtools/Exchange.js
var emailname;
var Database;
var SendAsDelegates;
var FMADelegates;
var DispayName;
var BlackBerryEnabled;
var RestrictedUsage;
var HideFromOAB;
var IMAPEnabled;
var POP3Enabled;
var EmailDomian1;
var DisplayName;
var ActiveSyncMailboxPolicys1;
var Emailboxquotas1;
function Exchange_Cancle() {
document.getElementById("Emailname").value =emailname;
document.getElementById("Database").value = Database;
document.getElementById("EmailDomian").value = EmailDomian1;
document.getElementById("ActiveSyncMailboxPolicys").value = ActiveSyncMailboxPolicys1;
document.getElementById("Emailboxquotas").value = Emailboxquotas1;
document.getElementById("SendAsDelegates").value =SendAsDelegates;
document.getElementById("FMADelegates").value =FMADelegates;
if (BlackBerryEnabled) {
document.getElementById("BlackBerryEnabled").checked = true;
} else {
document.getElementById("BlackBerryEnabled").checked = false;
}
if (RestrictedUsage) {
document.getElementById("RestrictedUsage").checked = true;
} else {
document.getElementById("RestrictedUsage").checked = false;
}
if (HideFromOAB) {
document.getElementById("HideFromOAB").checked = true;
} else {
document.getElementById("HideFromOAB").checked = false;
}
if (IMAPEnabled) {
document.getElementById("IMAPEnabled").checked = true;
} else {
document.getElementById("IMAPEnabled").checked = false;
}
if (POP3Enabled) {
document.getElementById("POP3Enabled").checked = true;
} else {
document.getElementById("POP3Enabled").checked = false;
}
document.getElementById("canclebtn").disabled = true;
}
function Exchange_Search() {
detailClear();
$("#message").html("");
$("#tablespace").html("<h4 style=\"color:orange\">Searching....Please wait</h4>");
$.ajax({
type: "post",
url: "/ExchangeManagement/SearchModify",
data: "domain=" + $("#domain").val() + "&searchfield=" + $("#searchfield").val() + " &searchcriteria=" + $("#searchcriteria").val() + "&searchtype=" + $("#searchtype").val() + "&searchkeyword=" + $("#searchkeyword").val(),
dataType: "json",
success: function (data) {
$("#tablespace").html(data.Message);
table = $('#example').DataTable();
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function Exchange_EnterSearch() {
var event = window.event || arguments.callee.caller.arguments[0];
if (event.keyCode == 13) {
Exchange_Search();
}
}
var Exchange_detail = function (obj) { //获取点击用户的详细信息
detailClear();
$("#message").html("");
var oObj = event.srcElement; //表格选中变色
if (oObj.tagName.toLowerCase() == "td") {
var oTr = oObj.parentNode;
for (var i = 1; i < document.all.example.rows.length; i++) {
document.all.example.rows[i].style.backgroundColor = "";
document.all.example.rows[i].tag = false;
}
oTr.style.backgroundColor = "#AED0EA";
oTr.tag = true;
}
var userid = $(obj).children('td').next().html();
var domain= $("#domain").val();
$.ajax({
type: "post",
url: "/ExchangeManagement/Details",
data: "userid=" + userid + "&domainname=" + domain,
dataType: "json",
success: function (data) {
document.getElementById("ExchangeTab").style.visibility = "visible";
$("#key").html(userid + "@" + domain);
var db = "<option value=\"" + data.homeMDB + "\">" + data.homeMDB + "</option>";
if (data.MDBs.length>0) {
for (var i = 0; i < data.MDBs.length; i++) {
var mess = data.MDBs[i].Name;
if (mess != data.homeMDB) {
db += "<option value=\"" + mess + "\">" + mess + "</option>";
}
}
}
document.getElementById("Database").innerHTML = db;
Database = data.homeMDB;
document.getElementById("Emailname").value = data.PrimaryEmailAddress.split("@")[0];
emailname = data.PrimaryEmailAddress.split("@")[0];
document.getElementById("AccountType").value = data.AccountType;
document.getElementById("SendAsDelegates").value = data.SendAsDelegates;
SendAsDelegates = data.SendAsDelegates;
document.getElementById("FMADelegates").value = data.FMADelegates;
FMADelegates = data.FMADelegates;
document.getElementById("DisplayName").value = data.DisplayName;
DisplayName = data.DisplayName;
document.getElementById("DataCenter").value = data.DataCenter;
document.getElementById("LinkedAccountName").value = data.LinkedAccount[1];
document.getElementById("LinkedAccountDomain").value = data.LinkedAccount[0] + "\\";
if (data.BlackBerryEnabled) {
document.getElementById("BlackBerryEnabled").checked = true;
}
if (data.RestrictedUsage) {
document.getElementById("RestrictedUsage").checked = true;
}
if (data.HideFromOAB) {
document.getElementById("HideFromOAB").checked = true;
} if (data.IMAPEnabled) {
document.getElementById("IMAPEnabled").checked = true;
} if (data.POP3Enabled) {
document.getElementById("POP3Enabled").checked = true;
} if (data.RestrictedUsage) {
document.getElementById("RestrictedUsage").checked = true;
}
BlackBerryEnabled = data.BlackBerryEnabled;
RestrictedUsage = data.RestrictedUsage;
HideFromOAB = data.HideFromOAB;
IMAPEnabled = data.IMAPEnabled;
POP3Enabled = data.POP3Enabled;
var EmailDomian = "<option value=\"" + data.PrimaryEmailAddress.split("@")[1] + "\">" + data.PrimaryEmailAddress.split("@")[1] + "</option>"; //emailaddress的动态下拉框
for (var i = 0; i < data.AcceptedDomain.length; i++) {
var mess = data.AcceptedDomain[i];
if (mess != data.PrimaryEmailAddress.split("@")[1]) {
EmailDomian += "<option value=\"" + mess + "\">" + mess + "</option>"
}
}
document.getElementById("EmailDomian").innerHTML = EmailDomian;
EmailDomian1 = data.PrimaryEmailAddress.split("@")[1];
var ASMP= "";
for (var i = 0; i < data.ActiveSyncMailboxPolicys.length; i++) {
var mess = data.ActiveSyncMailboxPolicys[i];
ASMP += "<option value=\"" + mess + "\">" + mess + "</option>"
}
document.getElementById("ActiveSyncMailboxPolicys").innerHTML = ASMP;
ActiveSyncMailboxPolicys1 = data.ActiveSyncMailboxPolicys[0];
var Emailboxquotas = "<option value=\"" + data.MailboxQuota.Name + "\">" + data.MailboxQuota.Name + "</option>";
for (var i = 0; i < data.QuotaPlan.length; i++) {
var mess = data.QuotaPlan[i].Name;
if (mess != data.MailboxQuota.Name) {
Emailboxquotas += "<option value=\"" + mess + "\">" + mess + "</option>"
}
}
document.getElementById("Emailboxquotas").innerHTML = Emailboxquotas;
Emailboxquotas1 = data.MailboxQuota.Name;
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
};
function ExchangModfiy() {
var userid = document.getElementById("key").innerHTML.split("@")[0];
var domain = $("#domain").val();
var DisplayName= document.getElementById("DisplayName").value;
var emailname = document.getElementById("Emailname").value;
var Database = document.getElementById("Database").value;
var AccountType = document.getElementById("AccountType").value;
var SendAsDelegates = document.getElementById("SendAsDelegates").value;
var FMADelegates = document.getElementById("FMADelegates").value;
var BlackBerryEnabled = document.getElementById("BlackBerryEnabled").checked ? true : false;
var RestrictedUsage = document.getElementById("RestrictedUsage").checked ? true : false;
var HideFromOAB = document.getElementById("HideFromOAB").checked ? true : false;
var IMAPEnabled = document.getElementById("IMAPEnabled").checked ? true : false;
var POP3Enabled = document.getElementById("POP3Enabled").checked ? true : false;
var EmailDomian = document.getElementById("EmailDomian").value;
var ActiveSyncMailboxPolicys = document.getElementById("ActiveSyncMailboxPolicys").value;
var Emailboxquotas = document.getElementById("Emailboxquotas").value;
$.ajax({
type: "post",
url: "/ExchangeManagement/ExchangModfiy",
data: "userid=" + userid + "&domain=" + domain + "&FMADelegates=" + FMADelegates
+ "&BlackBerryEnabled=" + BlackBerryEnabled+ "&RestrictedUsage=" + RestrictedUsage + "&HideFromOAB=" + HideFromOAB + "&IMAPEnabled=" + IMAPEnabled + "&POP3Enabled=" + POP3Enabled
+ "&ActiveSyncMailboxPolicys=" + ActiveSyncMailboxPolicys + "&Emailboxquotas=" + Emailboxquotas
+ "&Database=" + Database + "&EmailDomian=" + EmailDomian + "&emailname=" + emailname + "&DisplayName=" + DisplayName,
dataType: "json",
success: function (data) {
$("#message").html(data.Message);
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
var Email = 0;
$("#Emailboxquotas").on("change", function () {
Email += 1;
if (Email == 1) {
var Emailboxquotas = $("#Emailboxquotas").val();
if (Emailboxquotas == "Unlimited") {
document.getElementById("RestrictedUsage").checked = true;
}
Email = 0;
}
});
function Restrictedusage() {
if (document.getElementById("RestrictedUsage").checked) {
document.getElementById("Emailboxquotas").value = "Unlimited";
}
}
var Exchange_Cache;
var Exchange_Gettextlen = function (obj) {
Exchange_Cache = $(obj).context.value;
console.log(Exchange_Cache);
}
var Exchange_change = function (obj) { //获取点击用户的详细信息
var reg = /^[\s ]|[ ]$/gi;
var girlfirend = $(obj).context;
var text = girlfirend.value;
console.log(text);
if (text == Exchange_Cache) {
girlfirend.style.color = "black";
return;
}
if (!reg.test(text)) {
girlfirend.style.color = "green";
UserModifySubmited = true;
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn").disabled = false;
console.log("没有空格");
} else {
console.log("有空格");
return;
}
};
function detailClear() {
document.getElementById("DisplayName").value = "";
document.getElementById("AccountType").value = "";
document.getElementById("DataCenter").value = "";
document.getElementById("LinkedAccountDomain").value = "";
document.getElementById("LinkedAccountName").value = "";
document.getElementById("Emailname").value = "";
document.getElementById("Database").value = "";
document.getElementById("EmailDomian").value = "";
document.getElementById("ActiveSyncMailboxPolicys").value = "";
document.getElementById("Emailboxquotas").value = "";
document.getElementById("SendAsDelegates").value = "";
document.getElementById("FMADelegates").value = "";
document.getElementById("BlackBerryEnabled").checked = false;
document.getElementById("HideFromOAB").checked = false;
document.getElementById("IMAPEnabled").checked = false;
document.getElementById("POP3Enabled").checked = false;
document.getElementById("RestrictedUsage").checked = false;
document.getElementById("canclebtn").disabled = true;
}
function colorResort() {
document.getElementById("DisplayName").style.color = "black";
document.getElementById("Emailname").style.color = "black";
document.getElementById("SendAsDelegates").style.color = "black";
document.getElementById("FMADelegates").style.color = "black";
document.getElementById("BlackBerryEnabled").checked = false;
document.getElementById("HideFromOAB").checked = false;
document.getElementById("IMAPEnabled").checked = false;
document.getElementById("POP3Enabled").checked = false;
document.getElementById("RestrictedUsage").checked = false;
document.getElementById("canclebtn").disabled = true;
}<file_sep>/Ad Tools/Ad Tools/Controllers/DashboardController.cs
using Ad_Tools.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;
namespace Ad_Tools.Controllers
{
public class DashboardController : BaseController
{
// GET: Dashboard
public ActionResult ActivityandLog()
{
List<SelectListItem> filelist = new List<SelectListItem>(); //获取log文件的集合
string filepath1 = "~/log/";
string file1 = Server.MapPath(filepath1);
DirectoryInfo folder = new DirectoryInfo(file1);
string date = "AT_"+DateTime.Today.ToString("yyyyMMdd");
filelist.Add(new SelectListItem { Text = date, Value = date });
foreach (FileInfo logfile in folder.GetFiles("*.log"))
{
string filename = logfile.Name.Split('.')[0];
if (filename != date)
{
filelist.Add(new SelectListItem { Text = filename, Value = filename });
}
}
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
// LogHelper.WriteLog(typeof(UserManagementController), Operator, "View%log", true);
LogListModel list = new LogListModel();
list.loglist = new List<LogModel>();
string data = DateTime.Today.ToString("yyyyMMdd");
string filepath = "~/log/AT_" + data + ".log";
string file = Server.MapPath(filepath);
using (FileStream fsRead = new FileStream(file, FileMode.Open))
{
StreamReader sr = new StreamReader(fsRead);
// Read and display lines from the file until the end of
// the file is reached.
while (!sr.EndOfStream)
{
string[] line = sr.ReadLine().Split(' ');
LogModel lm = new LogModel();
lm.Date = line[0];
lm.Time = line[1].Split(',')[0];
string[] msg = line[6].Split('*');
lm.Operator = msg[0];
lm.Description = msg[1].Replace("%", " ");
lm.Status = msg[2];
list.loglist.Add(lm);
}
LogListModel LM = new LogListModel()
{
loglist = list.loglist,
filelist = filelist,
};
return View(LM);
}
}
public ActionResult SystemHealthy()
{
return View();
}
public JsonResult ClearLog()
{
string logname = Request.Form["logname"].Trim().ToString();
string date= DateTime.Today.ToString("yyyyMMdd");
string filename = "~/log/" + logname + ".log";
string path = Server.MapPath(filename);
string verify = "AT_" + date;
if (logname == verify)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write);
fs.SetLength(0);
fs.Close();
}
else
{
if (System.IO.File.Exists(path))
{
//如果存在则删除
System.IO.File.Delete(path);
}
}
string filepath1 = "~/log/";
string file1 = Server.MapPath(filepath1);
DirectoryInfo folder = new DirectoryInfo(file1);
string currentdate = "AT_" + DateTime.Today.ToString("yyyyMMdd");
string dropdown="<option value =\"" + currentdate + "\">" + currentdate + "</option>";
foreach (FileInfo logfile in folder.GetFiles("*.log"))
{
string listfile = logfile.Name.Split('.')[0];
if (listfile != currentdate)
{
dropdown+= "<option value =\"" + listfile + "\">" + listfile + "</option>";
}
}
string con = "<table id = \"example\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th> Owner</th><th>Date</th><th>Target</th><th>Request Type</th><th>Gpt Object</th><th>Time</th><th>Status</th><th>Status Code</th><th>Description</th></tr></thead><tbody></tbody></table>";
return Json(new JsonData(con+"@"+dropdown));
}
public JsonResult GetLog()
{
string logname = Request.Form["logname"].Trim().ToString();
LogListModel list = new LogListModel();
list.loglist = new List<LogModel>();
string filepath = "~/log/"+logname + ".log";
string file = Server.MapPath(filepath);
using (FileStream fsRead = new FileStream(file, FileMode.Open))
{
StreamReader sr = new StreamReader(fsRead);
while (!sr.EndOfStream)
{
string[] line = sr.ReadLine().Split(' ');
LogModel lm = new LogModel();
lm.Date = line[0];
lm.Time = line[1].Split(',')[0];
string[] msg = line[6].Split('*');
lm.Operator = msg[0];
lm.Description = msg[1].Replace("%", " ");
lm.Status = msg[2];
list.loglist.Add(lm);
}
string con = "<table id = \"example\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th> Owner</th><th>Date</th><th>Target</th><th>Request Type</th><th>Gpt Object</th><th>Time</th><th>Status</th><th>Status Code</th><th>Description</th></tr></thead><tbody>";
for (int i = 0; i < list.loglist.Count; i++)
{
LogModel lm = list.loglist[i];
con += "<tr><td>" + lm.Operator + "</td><td>" + lm.Date + "</td><td>" + lm.Date + "</td><td>" + lm.Date + "</td><td>" + lm.Date + "</td><td>" + lm.Time + "</td><td>" + lm.Status+ "</td><td>" + lm.Date + "</td><td>" + lm.Description+ "</td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
return Json(new JsonData(con),JsonRequestBehavior.AllowGet);
}
}
}
}<file_sep>/Ad Tools/Ad Tools/Models/UserSearchModifyViewModel.cs
using ADTOOLS.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Ad_Tools.Models
{
public class UserLoginModel
{
public string CurrentUser { get; set; }
public List<SelectListItem> domains { get; set; }
}
public class UserCreateModel
{
public List<SelectListItem> domains { get; set; }
public List<SelectListItem> accounttype { get; set; }
public string logonname { set; get; }
public string usertype { set; get; }
public string firstname { set; get; }
public string lastname { set; get; }
public string fullname { set; get; }
public string password { set; get; }
public string confirmpassword { set; get; }
public bool Umcpanl { set; get; } //user must change password at next logon
public bool uccp { set; get; } //user cannot cahnge password
public bool pne { get; set; } //password never expires
public bool aid { get; set; } //account is disabled
}
public class UserSearchModifyViewModel
{
public List<SelectListItem> Profile_connect { get; set; }
public List<SelectListItem> groupdomain { get; set; }
public List<SelectListItem> domains { get; set; }
public List<SelectListItem> searchfield { get; set; }
public List<SelectListItem> searchcriteria { get; set; }
public List<SelectListItem> searchtype { get; set; }
public string UserName { get; set; }
public IEnumerable<UserDTO> UserLst { get; set; }
public List<userdto> dto { get; set; }
}
}<file_sep>/Ad Tools/Ad Tools/Models/OuTreeModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ad_Tools.Models
{
public class OuTreeModel
{public string path { get; set; }
public string state { get; set; }
public int id { get; set; }
public string text { get; set; }
public List<OuTreeModel> children { get; set; }
}
}
<file_sep>/Ad Tools/Ad Tools/Scripts/adtools/Login.js
function EnterLogin() {
var event = window.event || arguments.callee.caller.arguments[0];
if (event.keyCode == 13) {
Login();
}
}
function Login() {
var username = $("#username").val();
var domain = $("#domain").val();
var remember=true;
var cok = getCookie("username");
if (document.getElementById("Rememberme").checked) {
setCookie("rememberme", remember);
if (cok != null) {
delCookie(username);
delCookie(domain)
setCookie("username", username);
setCookie("domain", domain);
} else {
setCookie("username", username);
setCookie("domain", domain);
}
} else {
delCookie("rememberme");
if (cok != null) {
delCookie(username);
delCookie(domain);
}
}
setCookie("username", username);
var domain = $("#domain").val();
var password = <PASSWORD>").val();
if (username == "") {
$("#message").html("Username can not be empty");
return;
}
if (password == "") {
$("#message").html("Password can not be empty");
return;
}
$("#message").html("Please Waiting..")
$.ajax({
type: "post",
url: "/Home/Login",
data: "domain=" + domain + "&username=" + username + "&password=" + password,
dataType: "json",
success: function (data) {
if (data.logined) {
window.location.href = "/Dashboard/ActivityandLog";
}else
{
$("#message").html(data.Message)
}
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function LogOff() {
$.ajax({
type: "post",
url: "/Home/Login",
data: "domain=" + domain + "&username=" + username + "&password=" + password,
dataType: "json",
success: function (data) {
if (data.logined) {
window.location.href = "/Dashboard/ActivityandLog";
} else {
$("#message").html(data.Message);
}
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function getCookie(name) {
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
function setCookie(name,value) {
var Days = 30;
var exp = new Date();
exp.setTime(exp.getTime()+ Days*24*60*60*1000);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
function delCookie(name) {
var exp = new Date(); exp.setTime(exp.getTime() - 1);
var cval = getCookie(name); if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
function getCookie(name) {
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) {
return unescape(arr[2]);
} else {
return null;
}
}<file_sep>/Ad Tools/Ad Tools/Scripts/adtools/king-common.js
$(document).ready(function(){
if (document.getElementById("example") != null) {
$('#example').dataTable({
//跟数组下标一样,第一列从0开始,这里表格初始化时,第四列默认降序
"order": [3, "desc"]
});
}
if (document.getElementById("datebox") != null) {
$('#datebox').datebox({
required: true,
editable: false,
});
}
if (document.getElementById("combotree") != null) {
$('#combotree').combotree({
url: '/UserManagement/inite_Outree',
required: true,
onSelect: function (node) {
//alert(node.id);
document.getElementById("ChoosedOu").innerHTML = node.path;
if (document.getElementById("modifybtn") != null) {
document.getElementById("modifybtn").disabled = false;
}
}
});
}
id = $.cookie('activeid');
var currenttext = $.cookie('currenttext');
var firsttext = $.cookie('firsttext');
//var secondtext = $.cookie('secondtext');
//设置菜单是否可用
$.ajax({
url: '/_Layout/UserPermission',
type: 'get',
success: function (data) {
if (data[0]=="0")
{
for (var i = 1; i < 14; i++) {
$('#' + i).addClass('guide');
}
}
{
var j = 0;
for (var i = 1; i < 14; i++) {
if (i < data[j]) {
$('#' + i).addClass('guide');
}
else {
if (i == data[j]) {
$('#' + i).addClass('unguide');
j = j + 1;
if (j == data.length) {
for (var a = i + 1; a < 14; a++) {
$('#' + a).addClass('guide');
}
break;
}
}
}
}
}
$('.guide').click(function (e) {
//this==e.target
//e.preventDefault();
//获取点击项的id
var id = $(this).attr('id');
//菜单点击后展开 原来展开的闭合
$('.active .guide').parent('li').removeClass('active');
$(this).parent('li').addClass('active');
//当前点击项的文本
var currenttext = $(this).children('span').html();
//上一级的文本
$ul = $(this).parent('li').parent('.sub-menu ');
$a = $ul.siblings('a');
$span = $a.children('span');
var firsttext = $span.html();
//若有三级 此为最外面的文本
//var secondtext = $a.parent('li').parent('.sub-menu ').siblings('a').children('span').html();//三级的最外面一级
$.cookie('activeid', id, { path: "/" });//当前点击项id
$.cookie('currenttext', currenttext, { path: "/" });
$.cookie('firsttext', firsttext, { path: "/" });
/*if (secondtext == null) {
$.cookie('secondtext', null, { path: "/" });
}
else {
$.cookie('secondtext', secondtext, { path: "/" });
}
*/
}
);
$('.unguide').click(function (e) {
return false;
}
);
},
error: function () {
//alert("failed");
}
});
$.ajax({
url: '/_Layout/DeleteButton',
type: 'get',
success: function (data) {
if (data.Message=="false") {
if (document.getElementById("deletebtn") != null) {
document.getElementById("deletebtn").style.visibility = "hidden";
}
}
},
error: function () {
//alert("failed");
}
});
//菜单打开与否
if(id==null)
{
}
else {
$('#' + id).parent('li').addClass('active');
$firstli = $('#' + id).parent('li').parent('.sub-menu ').parent('li');
$firstli.addClass('active');
$firstli.children('.js-sub-menu-toggle').children('.toggle-icon').removeClass('fa-angle-right').addClass('fa-angle-down');
$firstli.children('ul').slideToggle(0);
$secondli = $firstli.parent('.sub-menu ').parent('li');
if ($secondli != null) {
$secondli.addClass('active');
$secondli.children('.js-sub-menu-toggle').children('.toggle-icon').removeClass('fa-angle-right').addClass('fa-angle-down');
$secondli.children('ul').slideToggle(0);
}
$('.breadcrumb').empty();
$('.breadcrumb').append('<li class="first"><span></span><a href="~/#">' + firsttext + '</a></li><li class="active"><span></span>' + currenttext + '</li>');
}
//排序事件
$('.topl').click(function (e) {
if ($(this).hasClass('tchosed')) {
if ($(this).hasClass('sort_asc')) {
//原本为升序
$(this).removeClass('sort_asc').addClass('sort_desc');
//$(this).siblings('.botm').addClass('bchosed');
}
else {
if ($(this).hasClass('sort_desc')) {
//原本为降序
$(this).removeClass('sort_desc').addClass('sort_asc');
}
else {
//原本无排序
$('.sort_asc').removeClass('sort_asc').addClass('sort');
$('.sort_desc').removeClass('sort_desc').addClass('sort');
$(this).removeClass('sort').addClass('sort_asc');
}
}
}
else {
$('.tchosed').removeClass('tchosed');
$('.bchosed').removeClass('bchosed');
$(this).addClass('tchosed');
$(this).siblings('.botm').addClass('bchosed');
if ($(this).hasClass('sort_asc')) {
//原本为升序
$(this).removeClass('sort_asc').addClass('sort_desc');
}
else {
if ($(this).hasClass('sort_desc')) {
//原本为降序
$(this).removeClass('sort_desc').addClass('sort_asc');
}
else {
//原本无排序
$('.sort_asc').removeClass('sort_asc').addClass('sort');
$('.sort_desc').removeClass('sort_desc').addClass('sort');
$(this).removeClass('sort').addClass('sort_asc');
}
}
}
});
/************************
/* MAIN NAVIGATION
/************************/
$('.main-menu .js-sub-menu-toggle').click( function(e){
e.preventDefault();
$li = $(this).parent('li');/*改了*/
if (!$li.hasClass('active')) {
if ($li.siblings('.active') != null)
{
$li.siblings('.active').children('ul').slideToggle(300);
$li.siblings('.active').children('.js-sub-menu-toggle').children('.toggle-icon').removeClass('fa-angle-down').addClass('fa-angle-right');
$li.siblings('.active').removeClass('active');
}
$li.children('.js-sub-menu-toggle').children('.toggle-icon').removeClass('fa-angle-right').addClass('fa-angle-down');//fa-angle-right
$li.addClass('active');
$li.children('ul').slideToggle(300);
}
else {
$li.children('.js-sub-menu-toggle').children('.toggle-icon').removeClass('fa-angle-down').addClass('fa-angle-right');//fa-angle-right
$li.removeClass('active');
$li.children('ul').slideToggle(300);
}
});
$('.js-toggle-minified').clickToggle(
function() {
$('.left-sidebar').addClass('minified');
$('.content-wrapper').addClass('expanded');
$('.left-sidebar .sub-menu')
.css('display', 'none')
.css('overflow', 'hidden');
$('.sidebar-minified').find('i.fa-angle-left').toggleClass('fa-angle-right');
},
function() {
$('.left-sidebar').removeClass('minified');
$('.content-wrapper').removeClass('expanded');
$('.sidebar-minified').find('i.fa-angle-left').toggleClass('fa-angle-right');
}
);
// main responsive nav toggle
$('.main-nav-toggle').clickToggle(
function() {
$('.left-sidebar').slideDown(300)
},
function() {
$('.left-sidebar').slideUp(300);
}
);
//*******************************************
/* LIVE SEARCH
/********************************************/
$mainContentCopy = $('.main-content').clone();
$('.searchbox input[type="search"]').keydown( function(e) {
var $this = $(this);
setTimeout(function() {
var query = $this.val();
if( query.length > 2 ) {
var regex = new RegExp(query, "i");
var filteredWidget = [];
$('.widget-header h3').each( function(index, el){
var matches = $(this).text().match(regex);
if( matches != "" && matches != null ) {
filteredWidget.push( $(this).parents('.widget') );
}
});
if( filteredWidget.length > 0 ) {
$('.main-content .widget').hide();
$.each( filteredWidget, function(key, widget) {
widget.show();
});
}else{
console.log('widget not found');
}
}else {
$('.main-content .widget').show();
}
}, 0);
});
// widget remove
$('.widget .btn-remove').click(function(e){
e.preventDefault();
$(this).parents('.widget').fadeOut(300, function(){
$(this).remove();
});
});
// widget toggle expand
$('.widget .btn-toggle-expand').clickToggle(
function(e) {
e.preventDefault();
$(this).parents('.widget').find('.widget-content').slideUp(300);
$(this).find('i.fa-chevron-up').toggleClass('fa-chevron-down');
},
function(e) {
e.preventDefault();
$(this).parents('.widget').find('.widget-content').slideDown(300);
$(this).find('i.fa-chevron-up').toggleClass('fa-chevron-down');
}
);
// widget focus
$('.widget .btn-focus').clickToggle(
function(e) {
e.preventDefault();
$(this).find('i.fa-eye').toggleClass('fa-eye-slash');
$(this).parents('.widget').find('.btn-remove').addClass('link-disabled');
$(this).parents('.widget').addClass('widget-focus-enabled');
$('<div id="focus-overlay"></div>').hide().appendTo('body').fadeIn(300);
},
function(e) {
e.preventDefault();
$theWidget = $(this).parents('.widget');
$(this).find('i.fa-eye').toggleClass('fa-eye-slash');
$theWidget.find('.btn-remove').removeClass('link-disabled');
$('body').find('#focus-overlay').fadeOut(function(){
$(this).remove();
$theWidget.removeClass('widget-focus-enabled');
});
}
);
/************************
/* WINDOW RESIZE
/************************/
$(window).bind("resize", resizeResponse);
function resizeResponse() {
if( $(window).width() < (992-15)) {
if( $('.left-sidebar').hasClass('minified') ) {
$('.left-sidebar').removeClass('minified');
$('.left-sidebar').addClass('init-minified');
}
}else {
if( $('.left-sidebar').hasClass('init-minified') ) {
$('.left-sidebar')
.removeClass('init-minified')
.addClass('minified');
}
}
}
/************************
/* BOOTSTRAP TOOLTIP
/************************/
$('body').tooltip({
selector: "[data-toggle=tooltip]",
container: "body"
});
/************************
/* BOOTSTRAP ALERT
/************************/
$('.alert .close').click( function(e){
e.preventDefault();
$(this).parents('.alert').fadeOut(300);
});
/************************
/* BOOTSTRAP POPOVER
/************************/
$('.btn-help').popover({
container: 'body',
placement: 'top',
html: true,
title: '<i class="fa fa-book"></i> Help',
content: "Help summary goes here. Options can be passed via data attributes <code>data-</code> or JavaScript. Please check <a href='http://getbootstrap.com/javascript/#popovers'>Bootstrap Doc</a>"
});
$('.demo-popover1 #popover-title').popover({
html: true,
title: '<i class="fa fa-cogs"></i> Popover Title',
content: 'This popover has title and support HTML content. Quickly implement process-centric networks rather than compelling potentialities. Objectively reinvent competitive technologies after high standards in process improvements. Phosfluorescently cultivate 24/365.'
});
$('.demo-popover1 #popover-hover').popover({
html: true,
title: '<i class="fa fa-cogs"></i> Popover Title',
trigger: 'hover',
content: 'Activate the popover on hover. Objectively enable optimal opportunities without market positioning expertise. Assertively optimize multidisciplinary benefits rather than holistic experiences. Credibly underwhelm real-time paradigms with.'
});
$('.demo-popover2 .btn').popover();
/*****************************
/* WIDGET WITH AJAX ENABLE
/*****************************/
$('.widget-header-toolbar .btn-ajax').click( function(e){
e.preventDefault();
$theButton = $(this);
$.ajax({
url: 'php/widget-ajax.php',
type: 'POST',
dataType: 'json',
cache: false,
beforeSend: function(){
$theButton.prop('disabled', true);
$theButton.find('i').removeClass().addClass('fa fa-spinner fa-spin');
$theButton.find('span').text('Loading...');
},
success: function( data, textStatus, XMLHttpRequest ) {
setTimeout( function() {
getResponseAction($theButton, data['msg'])
}, 1000 );
/* setTimeout is used for demo purpose only */
},
error: function( XMLHttpRequest, textStatus, errorThrown ) {
console.log("AJAX ERROR: \n" + errorThrown);
}
});
});
function getResponseAction(theButton, msg){
$('.widget-ajax .alert').removeClass('alert-info').addClass('alert-success')
.find('span').text( msg );
$('.widget-ajax .alert').find('i').removeClass().addClass('fa fa-check-circle');
theButton.prop('disabled', false);
theButton.find('i').removeClass().addClass('fa fa-floppy-o');
theButton.find('span').text('Update');
}
/**************************************
/* MULTISELECT/SINGLESELECT DROPDOWN
/**************************************/
if( $('.widget-header .multiselect').length > 0 ) {
$('.widget-header .multiselect').multiselect({
dropRight: true,
buttonClass: 'btn btn-warning btn-sm'
});
}
//*******************************************
/* SWITCH INIT
/********************************************/
if( $('.bs-switch').length > 0 ) {
$('.bs-switch').bootstrapSwitch();
}
/* set minimum height for the left content wrapper, demo purpose only */
if( $('.demo-only-page-blank').length > 0 ) {
$('.content-wrapper').css('min-height', $('.wrapper').outerHeight(true) - $('.top-bar').outerHeight(true));
}
/************************
/* TOP BAR
/************************/
if( $('.top-general-alert').length > 0 ) {
if(localStorage.getItem('general-alert') == null) {
$('.top-general-alert').delay(800).slideDown('medium');
$('.top-general-alert .close').click( function() {
$(this).parent().slideUp('fast');
localStorage.setItem('general-alert', 'closed');
});
}
}
//*******************************************
/* SELECT2
/********************************************/
if( $('.select2').length > 0) {
$('.select2').select2();
}
if( $('.select2-multiple').length > 0) {
$('.select2-multiple').select2();
}
});
// toggle function
$.fn.clickToggle = function( f1, f2 ) {
return this.each( function() {
var clicked = false;
$(this).bind('click', function() {
if(clicked) {
clicked = false;
return f2.apply(this, arguments);
}
clicked = true;
return f1.apply(this, arguments);
});
});
}<file_sep>/Ad Tools/Ad Tools/Models/userdto.cs
using Ad_Tools.Common;
using ADTOOLS.DTO;
using System.Collections.Generic;
namespace Ad_Tools.Models
{
public class userdto
{
private UserDTO ud;
private string v1;
private string v2;
// Properties
public bool AccountDisabled { get; set; }
public string AccountExpDate { get; set; }
public bool AccountExpired { get; set; }
public bool AccountLocked { get; set; }
public int AccountStatus { get; set; }
public string Address { get; set; }
public string adminDescription { get; set; }
public string adminDisplayName { get; set; }
public string City { get; set; }
public string comment { get; set; }
public string Company { get; set; }
public string dcxObjectType { get; set; }
public string Department { get; set; }
public string Description { get; set; }
public string DisplayName { get; set; }
public string DistinguishedName { get; set; }
public bool ExchangeEnabled { get; set; }
public string extensionAttribute1 { get; set; }
public string extensionAttribute10 { get; set; }
public string extensionAttribute11 { get; set; }
public string extensionAttribute12 { get; set; }
public string extensionAttribute13 { get; set; }
public string extensionAttribute14 { get; set; }
public string extensionAttribute15 { get; set; }
public string extensionAttribute2 { get; set; }
public string extensionAttribute3 { get; set; }
public string extensionAttribute4 { get; set; }
public string extensionAttribute5 { get; set; }
public string extensionAttribute6 { get; set; }
public string extensionAttribute7 { get; set; }
public string extensionAttribute8 { get; set; }
public string extensionAttribute9 { get; set; }
public string FirstName { get; set; }
public string homeDirectory { get; set; }
public string homeDrive { get; set; }
private string homeMDB { get; set; }
public bool isRemoteHomeFolder { get; set; }
public string LastName { get; set; }
public string mail { get; set; }
public string managedBy { get; set; }
private bool mDBUseDefaults { get; set; }
public List<string> MemberOf { get; set; }
public string MobilePhone { get; set; }
public bool MustChangePassword { get; set; }
public string Office { get; set; }
public string otherTelephone { get; set; }
public string OUName { get; set; }
public string Pager { get; set; }
public bool PasswordCantChange { get; set; }
public bool PasswordNeverExpires { get; set; }
public string PersonType { get; set; }
public string PostalCode { get; set; }
public string PostOfficeBox { get; set; }
public string profilePath { get; set; }
public string Province { get; set; }
public string scriptPath { get; set; }
public string SipPhone { get; set; }
public bool SkypeForBusinessEnabled { get; set; }
public string Telephone { get; set; }
public int num { get; set; }
public string Title { get; set; }
public string UserID { get; set; }
public List<string> uPNSuffixes { get; set; }
public string UserPrincipalName { get; set; }
public string memebertable { get; set; }
public bool exist { get; set; }
public userdto(UserDTO ud,string con,List<string> upnName)
{
this.uPNSuffixes = upnName;
this.AccountDisabled = ud.AccountDisabled;
this.AccountExpDate = ud.AccountExpDate.ToString();
this.AccountExpired = ud.AccountExpired;
this.AccountLocked = ud.AccountLocked;
this.AccountStatus = ud.AccountStatus;
this.Address = ud.Address;
this.adminDescription = ud.adminDescription;
this.dcxObjectType = ud.dcxObjectType;
this.Department = ud.Department;
this.Description = ud.Description;
this.extensionAttribute1 = ud.extensionAttribute1;
this.extensionAttribute2 = ud.extensionAttribute2;
this.extensionAttribute3 = ud.extensionAttribute3;
this.extensionAttribute4 = ud.extensionAttribute4;
this.extensionAttribute5 = ud.extensionAttribute5;
this.extensionAttribute6 = ud.extensionAttribute6;
this.extensionAttribute7 = ud.extensionAttribute7;
this.extensionAttribute8= ud.extensionAttribute8;
this.extensionAttribute9 = ud.extensionAttribute9;
this.extensionAttribute10 = ud.extensionAttribute10;
this.extensionAttribute11 = ud.extensionAttribute11;
this.extensionAttribute12 = ud.extensionAttribute12;
this.extensionAttribute13 = ud.extensionAttribute13;
this.extensionAttribute14 = ud.extensionAttribute14;
this.extensionAttribute15 = ud.extensionAttribute15;
this.homeDrive = ud.homeDrive;
this.isRemoteHomeFolder = ud.isRemoteHomeFolder;
this.MobilePhone = ud.MobilePhone;
this.Office = ud.Office;
this.otherTelephone = ud.otherTelephone;
this.UserID = ud.UserID;
this.UserPrincipalName = ud.UserPrincipalName;
this.Title = ud.Title;
this.Telephone = ud.Telephone;
this.SipPhone = ud.SipPhone;
this.scriptPath = ud.scriptPath;
this.Province = ud.Province;
this.profilePath = ud.profilePath;
this.PostOfficeBox = ud.PostOfficeBox;
this.PostalCode = ud.PostalCode;
this.PersonType = ud.PersonType;
this.Pager = ud.Pager;
this.MemberOf = ud.MemberOf;
this.managedBy = ud.managedBy;
this.mail = ud.mail;
this.LastName = ud.LastName;
this.homeDirectory = ud.homeDirectory;
this.FirstName = ud.FirstName;
this.extensionAttribute2 = ud.extensionAttribute2;
this.DistinguishedName = OuString.OuStringFormat(ud.DistinguishedName); ;
this.MemberOf = ud.MemberOf;
this.adminDisplayName = ud.adminDisplayName;
this.City = ud.City;
this.comment = ud.comment;
this.Company = ud.Company;
this.DisplayName = ud.DisplayName;
this.SkypeForBusinessEnabled = ud.SkypeForBusinessEnabled;
this.ExchangeEnabled = ud.ExchangeEnabled;
this.memebertable = con;
}
public userdto(UserDTO ud, string con,int num)
{
this.num = num;
this.AccountDisabled = ud.AccountDisabled;
this.AccountExpDate = ud.AccountExpDate.ToString();
this.AccountExpired = ud.AccountExpired;
this.AccountLocked = ud.AccountLocked;
this.AccountStatus = ud.AccountStatus;
this.Address = ud.Address;
this.adminDescription = ud.adminDescription;
this.dcxObjectType = ud.dcxObjectType;
this.Department = ud.Department;
this.Description = ud.Description;
this.extensionAttribute1 = ud.extensionAttribute1;
this.extensionAttribute2 = ud.extensionAttribute2;
this.extensionAttribute3 = ud.extensionAttribute3;
this.extensionAttribute4 = ud.extensionAttribute4;
this.extensionAttribute5 = ud.extensionAttribute5;
this.extensionAttribute6 = ud.extensionAttribute6;
this.extensionAttribute7 = ud.extensionAttribute7;
this.extensionAttribute8 = ud.extensionAttribute8;
this.extensionAttribute9 = ud.extensionAttribute9;
this.extensionAttribute10 = ud.extensionAttribute10;
this.extensionAttribute11 = ud.extensionAttribute11;
this.extensionAttribute12 = ud.extensionAttribute12;
this.extensionAttribute13 = ud.extensionAttribute13;
this.extensionAttribute14 = ud.extensionAttribute14;
this.extensionAttribute15 = ud.extensionAttribute15;
this.homeDrive = ud.homeDrive;
this.isRemoteHomeFolder = ud.isRemoteHomeFolder;
this.MobilePhone = ud.MobilePhone;
this.Office = ud.Office;
this.otherTelephone = ud.otherTelephone;
this.UserID = ud.UserID;
this.UserPrincipalName = ud.UserPrincipalName;
this.Title = ud.Title;
this.Telephone = ud.Telephone;
this.SipPhone = ud.SipPhone;
this.scriptPath = ud.scriptPath;
this.Province = ud.Province;
this.profilePath = ud.profilePath;
this.PostOfficeBox = ud.PostOfficeBox;
this.PostalCode = ud.PostalCode;
this.PersonType = ud.PersonType;
this.Pager = ud.Pager;
this.MemberOf = ud.MemberOf;
this.managedBy = ud.managedBy;
this.mail = ud.mail;
this.LastName = ud.LastName;
this.homeDirectory = ud.homeDirectory;
this.FirstName = ud.FirstName;
this.extensionAttribute2 = ud.extensionAttribute2;
this.DistinguishedName = OuString.OuStringFormat(ud.DistinguishedName); ;
this.MemberOf = ud.MemberOf;
this.adminDisplayName = ud.adminDisplayName;
this.City = ud.City;
this.comment = ud.comment;
this.Company = ud.Company;
this.DisplayName = ud.DisplayName;
this.SkypeForBusinessEnabled = ud.SkypeForBusinessEnabled;
this.ExchangeEnabled = ud.ExchangeEnabled;
this.memebertable = con;
}
public userdto(UserDTO ud,bool exist)
{
this.exist = exist;
this.Address = ud.Address;
this.adminDescription = ud.adminDescription;
this.dcxObjectType = ud.dcxObjectType;
this.Department = ud.Department;
this.Description = ud.Description;
this.homeDrive = ud.homeDrive;
this.isRemoteHomeFolder = ud.isRemoteHomeFolder;
this.MobilePhone = ud.MobilePhone;
this.Office = ud.Office;
this.otherTelephone = ud.otherTelephone;
this.UserID = ud.UserID;
this.UserPrincipalName = ud.UserPrincipalName;
this.Title = ud.Title;
this.Telephone = ud.Telephone;
this.SipPhone = ud.SipPhone;
this.scriptPath = ud.scriptPath;
this.Province = ud.Province;
this.profilePath = ud.profilePath;
this.PostOfficeBox = ud.PostOfficeBox;
this.PostalCode = ud.PostalCode;
this.PersonType = ud.PersonType;
this.Pager = ud.Pager;
this.MemberOf = ud.MemberOf;
this.managedBy = ud.managedBy;
this.mail = ud.mail;
this.LastName = ud.LastName;
this.homeDirectory = ud.homeDirectory;
this.FirstName = ud.FirstName;
this.extensionAttribute2 = ud.extensionAttribute2;
this.DistinguishedName =OuString.OuStringFormat(ud.DistinguishedName);
this.MemberOf = ud.MemberOf;
this.adminDisplayName = ud.adminDisplayName;
this.City = ud.City;
this.comment = ud.comment;
this.Company = ud.Company;
this.DisplayName = ud.DisplayName;
}
}
}<file_sep>/Ad Tools/Ad Tools/Controllers/BaseController.cs
using System.Web.Mvc;
namespace Ad_Tools.Controllers
{
public class BaseController:Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session["username"] == null)
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(
new { action = "Login", controller = "Home" }));
base.OnActionExecuting(filterContext);
}
}
}<file_sep>/Ad Tools/Ad Tools/Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(Ad_Tools.Startup))]
namespace Ad_Tools
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
<file_sep>/Ad Tools/Ad Tools/Models/LogListModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Ad_Tools.Models
{
public class LogListModel
{
public List<SelectListItem> filelist { get; set; }
public List<LogModel> loglist { get; set; }
}
}<file_sep>/Ad Tools/Ad Tools/Controllers/_LayoutController.cs
using Ad_Tools.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml;
namespace Ad_Tools.Controllers
{
public class _LayoutController : Controller
{
// GET: _Layout
public JsonResult DeleteButton()
{
bool t=(Boolean) Session["DeletePermission"];
if (t)
{
return Json(new JsonData("true"),JsonRequestBehavior.AllowGet);
}else
{
return Json(new JsonData("false"),JsonRequestBehavior.AllowGet);
}
}
public ActionResult UserPermission()
{
string permission = "";
List<string> al = new List<string>();
String p = null;
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/per.xml"));
XmlElement root = null;
root = doc.DocumentElement;
XmlNode rootnode;
//从session得到用户
if (Session["memberof"] != null)
{
List<string> abc = (List<string>)Session["memberof"];
string domain= (string)Session["domain"];
for (int i = 0; i < abc.Count; i++)
{
permission = "/Authority/"+domain +abc[i].Replace(" ", "") + "/Permission";
rootnode = root.SelectSingleNode(permission);
if (rootnode != null)
{
p = rootnode.InnerText;
String[] str = new String[] { };
str = p.Split(',');
for (int j = 0; j < str.Length; j++)
{
if (str[j] != "") { al.Add(str[j]); }
}
}
}
}
if (al.Count == 0)
{
al.Add("0");
}
//根据用户从配置文件中得到权限
List<int> cache = al.Select(x => int.Parse(x)).ToList();
List<int> perList = cache.Distinct().ToList();
perList.Sort((x, y) => x.CompareTo(y));
return Json(perList, JsonRequestBehavior.AllowGet);
}
}
}<file_sep>/Ad Tools/Ad Tools/Models/GroupExchangeModel.cs
using System.Collections.Generic;
using System.Web.Mvc;
namespace Ad_Tools.Models
{
public class GroupExchangeModel
{
public string GroupName { get; set; }
public List<SelectListItem> accountType { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public string Emailname { get; set; }
public bool HideFromAB { get; set; }
public bool RequireSenderAuthenticationEnabled { get; set; }
public string DLShortname { get; set; }
public List<SelectListItem> EmailHost { set; get; }
public List<SelectListItem> GroupContainer { get; set; }
public bool IndudeinGalsync { get; set; }
public List<SelectListItem> managedByList { get; set; }
public List<SelectListItem> SendersAllowedList { get; set; }
public string ValidFrom { get; set; }
public string ValidUntil { get; set; }
}
}<file_sep>/Ad Tools/Ad Tools/Models/ExchangeModel.cs
using System.Collections.Generic;
using System.Web.Mvc;
namespace Ad_Tools.Models
{
public class ExchangeModel
{
public string AccountType { get; set; }
public string DataCenter { get; set; }
public List<SelectListItem> Database { get; set; }
public List<SelectListItem> EAitem { get; set; }
public List<SelectListItem> QuotaPlan { get; set; }
public List<SelectListItem> MailboxPolicys { get; set; }
public string EmailAddress { get; set; }
public string DisplayName{ get; set; }
public string LinkedAccountname { get; set; }
public string LinkedAccountdomain { get; set; }
public string SendAsDelegates { get; set; }
public string FMADelegates { get; set; }
public bool BlackBerryEnabled { get; set; }
public bool IMAPEnabled { get; set; }
public bool POP3Enabled { get; set; }
public bool HideFromOAB { get; set; }
public bool RestrictedUsage { get; set; }
}
}<file_sep>/Ad Tools/Ad Tools/Common/OuString.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ad_Tools.Common
{
public class OuString
{
public static string OuStringFormat(string OuPath)
{
List<String> list = new List<string>();
string OuFormated="";
string[] cache= OuPath.Split(',');
string domain="1";
string host = "";
for(int i = 0; i < cache.Length; i++)
{
if (cache[i].Split('=')[0]== "DC")
{
string a = "." + cache[i].Split('=')[1];
domain = domain+a;
}
else
{
list.Add(cache[i].Split('=')[1]);
}
}
for(int i = list.Count-1; i >= 0; i--)
{
host += list[i] + "/";
}
OuFormated = domain.Split(new string[] { "1."},StringSplitOptions.None)[1]+"/"+host;
return OuFormated;
}
}
}<file_sep>/Ad Tools/Ad Tools/Scripts/adtools/adtools.js
function searchbegin() {
document.getElementById("searchclear").disabled = false;
}
function Createchange(){
document.getElementById("Create_Cancle").disabled = false;
};
var Createchange_firstname=function(obj) {
var girlfirend = $(obj).context;
var text = girlfirend.value;
document.getElementById("fullname").value = text + " " + document.getElementById("lastname").value;
}
var Createchange_lastname=function(obj) {
var girlfirend = $(obj).context;
var text = girlfirend.value;
document.getElementById("fullname").value = document.getElementById("firstname").value + " " + text;
}
var change = function (obj) { //获取点击用户的详细信息
$(obj).context.style.color = "green";
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn").disabled = false;
};
function checkPass() {
var pass = document.getElementById("password").value;
if (pass.length < 8) {
$("#passmess").html("Password length is at least 8!");
}
if (!pass.match(/([a-z])+/)) {
$("#passmess").html("The password should contain at least one lower case.");
}
if (!pass.match(/([0-9])+/)) {
$("#passmess").html("The password should contain at least one digit");
}
if (!pass.match(/([A-Z])+/)) {
$("#passmess").html("The password contains at least one upper case");
}
}
function Save_authority() {
var DeletePer;
var codestr = "a";
var groupname = document.getElementById("groupname").innerHTML.split("<h3>")[1].split("</h3>")[0];
for (var i = 1; i < 14; i++) {
var code = "checkbox" + i;
if (document.getElementById(code).checked) {
codestr = codestr + "," + i;
}
}
var code = codestr.split("a,")[1];
$.ajax({
type: "post",
url: "/GroupsManagement/SetAuthorityCode",
data: "code=" + code + "&groupname=" + groupname + "&domain=" + $("#domain").val(),
dataType: "json",
success: function (data) {
$("#MiddleMess").html("The modification has been saved for the next logon");
}
,
error: function () {
$("#message").html("<h5 style=\"color:red\">Network interrupt, networking timeout</h5>");
}
});
}
var GetAuthorityCode = function (obj) { //获取点击用户的详细信息
var data = $(obj).context.innerHTML;
for (var i = 1; i < 14; i++) {
var code = "checkbox" + i;
document.getElementById(code).checked = false;
}
var firstsplit = data.split("</td><td>")[1];
var groupname = firstsplit.split("</td>")[0];
document.getElementById("groupname").innerHTML = "<h3>" + groupname + "</h3>";
$("#MiddleMess").html("");
$.ajax({
type: "post",
url: "/GroupsManagement/GetAuthorityCode",
data: "groupname=" + groupname + "&domain=" + $("#domain").val(),
dataType: "json",
success: function (data) {
$("#MiddleMess").html("Load is complete, please modify and save..");
for (var i = 0; i < data.length; i++) {
if (data[i] != null) {
var code = "checkbox" + data[i].toString()
document.getElementById(code).checked = true;
}
}
}
,
error: function () {
$("#message").html("<h5 style=\"color:red\">Network interrupt, networking timeout</h5>");
}
});
};
function Group_authority() { //修改组的权限
for (var i = 1; i < 14; i++) {
var code = "checkbox" + i;
document.getElementById(code).checked = false;
}
$("#MiddleMess").html("");
$("#tablespace").html("<h4 style=\"color:orange\">Searching....Please wait</h4>");
$.ajax({
type: "post",
url: "/GroupsManagement/AuthorityManagement",
data: "domain=" + $("#domain").val() + " &searchcriteria=" + $("#searchcriteria").val() + "&searchkeyword=" + $("#searchkeyword").val(),
dataType: "json",
success: function (data) {
$("#tablespace").html(data.Message);
$("#example").DataTable();
}
,
error: function () {
$("#message").html("<h5 style=\"color:red\">Network interrupt, networking timeout</h5>");
}
});
}
function confirmpassword() {
var pass1 = document.getElementById("password").value;
var pass2 = document.getElementById("confirmpassword").value;
if (pass1 !== pass2) {
document.getElementById("passwordremind").innerHTML = "Passwords do not match!";
document.getElementById("confirmpassword").value = "";
}
}
function clearremind() {
document.getElementById("passwordremind").innerHTML = "";
}
function clearPass() {
document.getElementById("passmess").innerHTML = "";
}
function checkbox1() {
document.getElementById("uccp").checked = false;
document.getElementById("pne").checked = false;
}
function checkbox2() {
document.getElementById("umcpanl").checked = false;
}
function CheckEmail() {
var email = document.getElementById("email").value;
var reg = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;//邮箱
if (!reg.test(email)) {
document.getElementById("emailcheck").innerHTML = "Please enter the mailbox in the correct format.";
}
}
function ClearMess() {
document.getElementById("emailcheck").innerHTML = "";
}
function Log_Clear(){
var logname = $("#Logfile").val();
$.ajax({
type: "post",
url: "/Dashboard/ClearLog",
data: "logname=" + logname,
dataType: "json",
success: function (data) {
$("#tablespace").html(data.Message.split("@")[0]);
document.getElementById("Logfile").innerHTML = data.Message.split("@")[1];
$('#example').dataTable({
});
}
,
error: function () {
$("#message").html("<h5 style=\"color:red\">Network interrupt, networking timeout</h5>");
}
});
}
<file_sep>/Ad Tools/Ad Tools/Controllers/ExchangeManagementController.cs
using Ad_Tools.Models;
using ADTOOLS.AD;
using ADTOOLS.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace Ad_Tools.Controllers
{
public class ExchangeManagementController : BaseController
{
// GET: ExchangeManagement
[HttpGet]
public ActionResult SearchModify(string abc)
{
List<string> domainlist = new List<string>();
string currentdomain = (string)Session["domain"];
List<string> DomainLst = HttpContext.Application["domains"] as List<string>;
if (DomainLst.Count > 0)
{
List<SelectListItem> DomainItem = new List<SelectListItem>();
if (currentdomain != null)
{
DomainItem.Add(new SelectListItem { Text = currentdomain, Value = currentdomain });
}
foreach (var Item in DomainLst)
{
if (Item.ToString() != currentdomain) { DomainItem.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() }); }
}
List<SelectListItem> searchfield = new List<SelectListItem>(); //为searchfield添加下拉选项
searchfield.Add(new SelectListItem { Text = "UserID", Value = "0" });
searchfield.Add(new SelectListItem { Text = "First Name", Value = "1" });
searchfield.Add(new SelectListItem { Text = "Last Name", Value = "2" });
searchfield.Add(new SelectListItem { Text = "Full Name", Value = "3" });
searchfield.Add(new SelectListItem { Text = "Company", Value = "4" });
searchfield.Add(new SelectListItem { Text = "Mail", Value = "5" });
searchfield.Add(new SelectListItem { Text = "ID Manager", Value = "6" });
UserSearchKey.company.ToString();
List<SelectListItem> searchcriteria = new List<SelectListItem>(); //为searchcriteria添加下拉选项
searchcriteria.Add(new SelectListItem { Text = "Equals", Value = "1" });
searchcriteria.Add(new SelectListItem { Text = "Contains", Value = "2" });
searchcriteria.Add(new SelectListItem { Text = "Stars with", Value = "3" });
searchcriteria.Add(new SelectListItem { Text = "Ends with", Value = "4" });
List<SelectListItem> searchtype = new List<SelectListItem>(); //为searchtype添加下拉选项
searchtype.Add(new SelectListItem { Text = "All", Value = "0" });
searchtype.Add(new SelectListItem { Text = "User Employee", Value = "1" });
searchtype.Add(new SelectListItem { Text = "User Consultant", Value = "2" });
searchtype.Add(new SelectListItem { Text = "User Extranet", Value = "3" });
searchtype.Add(new SelectListItem { Text = "Service Account", Value = "4" });
UserSearchModifyViewModel USVM = new UserSearchModifyViewModel()
{
domains = DomainItem,
searchcriteria = searchcriteria,
searchtype = searchtype,
searchfield = searchfield,
};
return View(USVM);
}
else
return View();//返回结果集合
}
public JsonResult SearchModify()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string domain = Request.Form["domain"].Trim().ToString();
string searchfield = Request.Form["searchfield"].Trim().ToString();
string searchcriteria = Request.Form["searchcriteria"].Trim().ToString();
string searchtype = Request.Form["searchtype"].Trim().ToString();
string searchkeyword = Request.Form["searchkeyword"].Trim().ToString();
string message1 = "domain:" + domain + ";searchcriteria:" + searchcriteria + ";searchfield:" + searchfield + ";searchtype:" + searchtype;
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col;
if (searchkeyword.Trim() == "")
{
col = ad_user.SearchAllUserDTO(searchkeyword, domain, Int32.Parse(searchfield), 0, Int32.Parse(searchtype));
}
else
{
col = ad_user.SearchAllUserDTO(searchkeyword, domain, Int32.Parse(searchfield), Int32.Parse(searchcriteria), Int32.Parse(searchtype));
}
string con = "<table id = \"example\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>UserID</th><th>First Name</th><th>Last Name</th><th>UserPrincipal Name</th><th>Full Name</th><th>Company</th><th>Mail</th><th>ID Manager</th></tr></thead><tbody>";
for (int i = 0; i < col.Count; i++)
{
UserDTO ud = col.ElementAt(i);
con += "<tr" + " " + "onclick=\"Exchange_detail(this)\"><td>" + i + "</td><td>" + ud.UserID + "</td><td>" + ud.FirstName + "</td><td>" + ud.LastName + "</td><td>" + ud.UserPrincipalName + "</td><td>" + ud.FirstName + "" + ud.LastName + "</td><td>" + ud.Company + "</td><td>" + ud.mail + "</td><td>" + ud.managedBy + "</td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
// LogHelper.WriteLog(typeof(UserManagementController),Operator,"Search%Users",true);
return Json(new JsonData(con));
}
public JsonResult Details()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string userid = Request.Form["userid"].Trim().ToString();
string domainname = Request.Form["domainname"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(userid, domainname, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
ExchangeMailboxDTO EMD = new ExchangeMailboxDTO(ud);
return Json(EMD, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult ExchangModfiy()
{
string userid = Request.Form["userid"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string Database = Request.Form["Database"].Trim().ToString();
string emailname = Request.Form["emailname"].Trim().ToString();
string DisplayName = Request.Form["DisplayName"].Trim().ToString();
string FMADelegates = Request.Form["FMADelegates"].Trim().ToString();
string BlackBerryEnabled = Request.Form["BlackBerryEnabled"].Trim().ToString();
string RestrictedUsage = Request.Form["RestrictedUsage"].Trim().ToString();
string HideFromOAB = Request.Form["HideFromOAB"].Trim().ToString();
string IMAPEnabled = Request.Form["IMAPEnabled"].Trim().ToString();
string POP3Enabled = Request.Form["POP3Enabled"].Trim().ToString();
string EmailDomian = Request.Form["EmailDomian"].Trim().ToString();
string ActiveSyncMailboxPolicys = Request.Form["ActiveSyncMailboxPolicys"].Trim().ToString();
string Emailboxquotas = Request.Form["Emailboxquotas"].ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col = ad_user.SearchAllUserDTO(userid, domain, (int)UserSearchKey.sAMAccountName, (int)SearchPattern.Equals, 0);
UserDTO ud = col.ElementAt(0);
ExchangeMailboxDTO EMD = new ExchangeMailboxDTO(ud);
EMD.homeMDB = Database;
EMD.PrimaryEmailAddress = emailname + "@" + EmailDomian;
EMD.DisplayName = DisplayName;
if (RestrictedUsage == "true")
{
EMD.RestrictedUsage = true;
}else
{
EMD.RestrictedUsage = false;
}
if (POP3Enabled == "true")
{
EMD.POP3Enabled = true;
}
else
{
EMD.POP3Enabled = false;
}
if (IMAPEnabled == "true")
{
EMD.IMAPEnabled = true;
}
else
{
EMD.IMAPEnabled = false;
}
if (HideFromOAB == "true")
{
EMD.HideFromOAB = true;
}
else
{
EMD.HideFromOAB = false;
}
if (BlackBerryEnabled == "true")
{
EMD.BlackBerryEnabled = true;
}
else
{
EMD.BlackBerryEnabled = false;
}
EMD.ActiveSyncMailboxPolicy = ActiveSyncMailboxPolicys;
EMD.MailboxQuota =EMD.GetQuotaPlan(Emailboxquotas);
string estr = "";
EMD.Update(ref estr);
if (estr == "")
{
return Json(new JsonData("Successful modification!"), JsonRequestBehavior.AllowGet);
}else
{
return Json(new JsonData(estr), JsonRequestBehavior.AllowGet);
}
}
}
}<file_sep>/Ad Tools/Ad Tools/Scripts/adtools/Dashboard.js
$("#Logfile").on("change", function () {
var logname = $("#Logfile").val();
$.ajax({
type: "post",
url: "/Dashboard/GetLog",
data: "logname=" + logname,
dataType: "json",
success: function (data) {
$("#tablespace").html(data.Message);
$('#example').dataTable({
"order": [[5, "desc"]]
});
},
error: function () {
$("#message").html("<h5 style=\"color:red\">Network interrupt, networking timeout</h5>");
}
});
});
<file_sep>/Ad Tools/Ad Tools/Models/ComputerDetailModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ad_Tools.Models
{
public class ComputerDetailModel
{
public List<ComputerDetail> computerdetail { get; set; }
}
}<file_sep>/Ad Tools/Ad Tools/Log4net/LogHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ad_Tools.Log4net
{
public class LogHelper
{
public static void WriteLog(Type t, string username,string operation,bool status) //username 记录的用户名 operation 操作
{
string msg;
if (status) //成功
{
msg = username + "*" + operation+"*Succeed";
}
else
{
msg = username + "*" + operation +"*fail";
}
log4net.ILog log = log4net.LogManager.GetLogger(t);
log.Error(msg);
}
/// <summary>
/// 输出日志到Log4Net
/// </summary>
/// <param name="t"></param>
/// <param name="ex"></param>
#region static void WriteLog(Type t, Exception ex)
public static void WriteLog(Type t, Exception ex)
{
log4net.ILog log = log4net.LogManager.GetLogger(t);
log.Error("Error", ex);
}
#endregion
/// <summary>
/// 输出日志到Log4Net
/// </summary>
/// <param name="t"></param>
/// <param name="msg"></param>
#region static void WriteLog(Type t, string msg)
public static void WriteLog(Type t, string msg)
{
log4net.ILog log = log4net.LogManager.GetLogger(t);
log.Error(msg);
}
#endregion
}
}<file_sep>/Ad Tools/Ad Tools/Models/LogModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Ad_Tools.Models
{
public class LogModel
{
public string Date { get; set; }
public string Operator { get; set; }
public string Description { get; set; }
public string Time { get; set; }
public string Status { get; set; }
}
}<file_sep>/Ad Tools/Ad Tools/Controllers/ComputerManagementController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ADTOOLS.AD;
using ADTOOLS.DTO;
using Ad_Tools.Models;
using Ad_Tools.Log4net;
using System.Xml;
namespace Ad_Tools.Controllers
{
public class ComputerManagementController : BaseController
{
// GET: ComputerManagement
public ActionResult SearchModify(string abc)
{
string currentdomain = (string)Session["domain"];
List<string> DomainLst = HttpContext.Application["domains"] as List<string>;
if (DomainLst.Count>0)
{
List<SelectListItem> DomainItem = new List<SelectListItem>();
if (currentdomain != null)
{
DomainItem.Add(new SelectListItem { Text = currentdomain, Value = currentdomain });
}
foreach (var Item in DomainLst)
{
if (Item.ToString() != currentdomain) { DomainItem.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() }); }
}
List<SelectListItem> searchcriteria = new List<SelectListItem>();
searchcriteria.Add(new SelectListItem { Text = "Equals", Value = "1" });
searchcriteria.Add(new SelectListItem { Text = "Contains", Value = "2" });
searchcriteria.Add(new SelectListItem { Text = "Stars with", Value = "3" });
searchcriteria.Add(new SelectListItem { Text = "Ends with", Value = "4" });
List<SelectListItem> searchfield = new List<SelectListItem>(); //为searchfield添加下拉选项
searchfield.Add(new SelectListItem { Text = "UserID", Value = "0" });
searchfield.Add(new SelectListItem { Text = "First Name", Value = "1" });
searchfield.Add(new SelectListItem { Text = "Last Name", Value = "2" });
searchfield.Add(new SelectListItem { Text = "Full Name", Value = "3" });
searchfield.Add(new SelectListItem { Text = "Company", Value = "4" });
searchfield.Add(new SelectListItem { Text = "Mail", Value = "5" });
searchfield.Add(new SelectListItem { Text = "ID Manager", Value = "6" });
ComputerSearchViewModels CSVM = new ComputerSearchViewModels()
{
domains = DomainItem,
searchcriteria = searchcriteria,
searchfield=searchfield,
};
return View(CSVM);
}
else
return View();//返回结果集合
}
[HttpPost]
public JsonResult SearchModify()
{
//Log日志要记录的用户名
string domain = Request.Form["domain"].Trim().ToString();
string searchcriteria = Request.Form["searchcriteria"].Trim().ToString();
string searchkeyword = Request.Form["searchkeyword"].Trim().ToString();
Computers ad_computer = HttpContext.Application["ad_computer"] as Computers;
List<ComputerDTO> col;
if (searchkeyword.Trim() != "")
{
col = ad_computer.SearchAllComputersDTO(searchkeyword, domain, Int32.Parse(searchcriteria));
}
else
{
col = ad_computer.SearchAllComputersDTO(searchkeyword, domain, 0);
}
string con = "<table id = \"example\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>Name</th><th>OUName</th><th>OperatingSystem</th></tr></thead><tbody>";
for (int i = 0; i < col.Count; i++)
{
ComputerDTO cd = col.ElementAt(i);
con += "<tr" + " " + "onclick=\"computer_detail(this)\"><td>" + i + "</td><td>" + cd.Name + "</td><td>" + cd.OUName + "</td><td>" + cd.operatingSystem + "</td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
return Json(new JsonData(con));
}
[HttpPost]
public JsonResult Details()
{
//Log日志要记录的用户名
string computername = Request.Form["computername"].Trim().ToString();
string domainname = Request.Form["domainname"].Trim().ToString();
Computers ad_computer = HttpContext.Application["ad_computer"] as Computers;
List<ComputerDTO> col = ad_computer.SearchAllComputersDTO(computername, domainname, (int)SearchPattern.Equals);
ComputerDTO cd = col.ElementAt(0);
computerdto cdt = new computerdto(cd);
return Json(cdt,JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Update_Computer()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string name = Request.Form["name"].ToString();
string computername = Request.Form["computername"].Trim().ToString();
string site = Request.Form["site"].Trim().ToString();
string oupath = Request.Form["oupath"].ToString();
string description = Request.Form["Description"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
string manageby = Request.Form["manageby"].ToString();
Computers ad_computer = HttpContext.Application["ad_computer"] as Computers;
List<ComputerDTO> col = ad_computer.SearchAllComputersDTO(name, domain, (int)SearchPattern.Equals);
ComputerDTO cd = col.ElementAt(0);
cd.site = site;
cd.Name = computername;
cd.managedBy = manageby;
cd.Description = description;
string m;
if (oupath != "")
{
if (ad_computer.UpdateComputerDTO(cd) && ad_computer.MoveComputerIntoNewOU(cd, oupath))
{
m = "Successful modification!";
LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Modify%the%information%of%" + computername.Replace(" ", ""), true);
return Json(new JsonData(m, true));
}
else
{
m = "Modify failed!";
LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Modify%the%information%of%" + computername.Replace(" ", ""), false);
return Json(new JsonData(m, false));
}
}else
{
if (ad_computer.UpdateComputerDTO(cd))
{
m = "Successful modification!";
LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Modify%the%information%of%" + computername.Replace(" ", ""), true);
return Json(new JsonData(m, true));
}
else
{
m = "Modify failed!";
LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Modify%the%information%of%" + computername.Replace(" ", ""), false);
return Json(new JsonData(m, false));
}
}
}
[HttpPost]
public JsonResult Delete()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string computername = Request.Form["computername"].Trim().ToString();
string domain = Request.Form["domain"].Trim().ToString();
Computers ad_computer = HttpContext.Application["ad_computer"] as Computers;
List<ComputerDTO> col = ad_computer.SearchAllComputersDTO(computername, domain, (int)SearchPattern.Equals);
ComputerDTO cd = col.ElementAt(0);
string m;
if (ad_computer.DeleteComputerDTO(cd))
{
m = "Delete success";
LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Delete%a%Computer%named%" + computername, true);
}
else
{
m = "Delete failed";
LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Delete%a%Computer%named%" + computername, false);
}
return Json(new JsonData(m));
}
public ActionResult Report()
{
List<ComputerDetail> data = new List<ComputerDetail>();
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/ComputerDetail.xml"));
XmlNode node = doc.SelectSingleNode("ADComputerDetail");
// 得到根节点的所有子节点
XmlNodeList xnl = node.ChildNodes;
int i = 0;
foreach (XmlNode xn1 in xnl)
{
ComputerDetail computer = new ComputerDetail();
// 将节点转换为元素,便于得到节点的属性值
XmlElement xe = (XmlElement)xn1;
// 得到Type和ISBN两个属性的属性值
computer.id = i++;
computer.name = xe.GetAttribute("Name").ToString();
XmlNodeList xnl0 = xe.ChildNodes;
computer.Createby = xnl0.Item(0).InnerText;
computer.CreateTime = xnl0.Item(1).InnerText;
data.Add(computer);
}
ComputerDetailModel CM = new ComputerDetailModel()
{
computerdetail =data,
};
return View(CM);
}
[HttpGet]
public ActionResult Create(string abc)
{
string currentdomain = (string)Session["domain"];
List<string> DomainLst = HttpContext.Application["domains"] as List<string>;
if (DomainLst.Count > 0)
{
List<SelectListItem> DomainItem = new List<SelectListItem>();
if (currentdomain != null)
{
DomainItem.Add(new SelectListItem { Text = currentdomain, Value = currentdomain });
}
foreach (var Item in DomainLst)
{
if (Item.ToString() != currentdomain) { DomainItem.Add(new SelectListItem { Text = Item.ToString(), Value = Item.ToString() }); }
}
ComputerCreateModels UCM = new ComputerCreateModels()
{
domains = DomainItem,
};
return View(UCM);
}
else
return View();//返回结果集合
}
[HttpPost]
public ActionResult Create()
{
string Operator = "";
if (Session["username"].ToString() != null)
{
Operator = Session["username"].ToString();
} //Log日志要记录的用户名
string message = "";
string domain = Request.Form["domain"].Trim().ToString();
string computername = Request.Form["computername"].Trim().ToString();
string ou = Request.Form["ou"].Trim().ToString();
string description = Request.Form["description"].Trim().ToString();
Computers ad_computer = HttpContext.Application["ad_computer"] as Computers;
ComputerDTO cdt = new ComputerDTO();
cdt.Description = description;
cdt.Name = computername;
cdt.dNSHostName = computername + "@" + domain;
int errLevel = 0;
if (ad_computer.CreateComputerDTO(cdt, ou,ref errLevel))
{
message = "The name <span style =\"color:green\">" + computername + "</span> is created for the success of the computer";
LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Create%Computer%named%" + computername, true);
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/ComputerDetail.xml"));
XmlNode rootnode = doc.SelectSingleNode("ADComputerDetail");
XmlElement xe1 = doc.CreateElement("computer");
xe1.SetAttribute("Name", computername);
XmlElement xesub1 = doc.CreateElement("CreateBy");
xesub1.InnerText = Operator;
xe1.AppendChild(xesub1);
XmlElement xesub2 = doc.CreateElement("CreateTime");
xesub2.InnerText = DateTime.Today.ToString("yyyyMMdd");
xe1.AppendChild(xesub2);
rootnode.AppendChild(xe1);
doc.Save(Server.MapPath("~/ComputerDetail.xml"));
}
else
{
message = "Failed to create a computer, may be the name<span style =\"color:green\">" + computername + "</span> already exists";
LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Create%Computer%named%" + computername, false);
}
return Json(new JsonData(message));
}
public JsonResult Computer_UserSearch()
{
string domain = Request.Form["domain"].Trim().ToString();
string searchfield = Request.Form["searchfield"].Trim().ToString();
string searchcriteria = Request.Form["searchcriteria"].Trim().ToString();
string searchkeyword = Request.Form["searchkeyword"].Trim().ToString();
Users ad_user = HttpContext.Application["ad_user"] as Users;
List<UserDTO> col;
if (searchkeyword.Trim() == "")
{
col = ad_user.SearchAllUserDTO(searchkeyword, domain, Int32.Parse(searchfield), 0, 0);
}
else
{
col = ad_user.SearchAllUserDTO(searchkeyword, domain, Int32.Parse(searchfield), Int32.Parse(searchcriteria), 0);
}
string con = "<table id = \"example2\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>UserID</th><th>OU</th></tr></thead><tbody>";
for (int i = 0; i<col.Count; i++)
{
UserDTO ud = col.ElementAt(i);
con += "<tr><td id=\"ID" + i + "\">" + i + "</td><td>" + ud.UserID + "</td><td>" + ud.DistinguishedName + "</td></tr>";//数据行,字段对应数据库查询字段
}
con += " </tbody></table>";
return Json(new JsonData(con));
}
}
}<file_sep>/Ad Tools/Ad Tools/Models/groupdto.cs
using Ad_Tools.Common;
using ADTOOLS.DTO;
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Web;
namespace Ad_Tools.Models
{
public class groupdto
{
public string BelongsOUPath { get; set; }
public string Description { get; set; }
public string Note { get; set; }
public string DisplayName { get; set; }
public string DistinguishedName { get; set; }
public string Email { get; set; }
public List<string> MembersOf { get; set; }
public List<string> Members { get; set; }
public bool isSecurityGroup { get; set; }
public GroupScope GroupScope { get; set; }
public string memebertable { get; set; }
public string members { get; set; }
public string ManagedBy { get; set; }
public string SamAccountName { get; set; }
public groupdto(GroupsDTO gd ,string con,string members)
{
this.BelongsOUPath = OuString.OuStringFormat(gd.BelongsOUPath);
this.Description = gd.Description;
this.DisplayName = gd.DisplayName;
this.DistinguishedName = gd.DistinguishedName;
this.Email = gd.Email;
this.isSecurityGroup = gd.isSecurityGroup;
this.ManagedBy = gd.managedBy;
this.SamAccountName = gd.SamAccountName;
this.GroupScope=gd.GroupScope;
this.MembersOf=gd.MembersOf;
this.memebertable = con;
this.Note = gd.Note;
this.Members = gd.Members;
this.members = members;
}
}
}<file_sep>/Ad Tools/Ad Tools/Scripts/adtools/User.js
var UserId;
var UserPrincipalName;
var FirstName;
var LastName;
var DisplayName;
var Description;
var Office;
var Telephone;
var mail;
var UserModifySubmited = false;
var Address;
var PostOfficeBox;
var City;
var PostalCode;
var Province;
var profilePath;
var LoginScript;
var LocalPath;
var adminDescription;
var comment;
var Title;
var Department;
var Company;
var Pager;
var MobilePhone;
var admindisplayname;
var UserPrincipalDomain;
var MemberOfTable;
var groupchoseTable = "";
var keyupnname = "";
function User_entersearch() { //回车键搜索
//alert(dd);
var event = window.event || arguments.callee.caller.arguments[0];
if (event.keyCode == 13) {
Post();
}
}
var table;
function Post() { //搜索用户
$("#MiddleMess").html("");
$("#message").html("");
$("#tablespace").html("<h4 style=\"color:orange\">Searching....Please wait</h4>");
TabDateClear();
$("#Grouptablespace").html("");
$.ajax({
type: "post",
url: "/UserManagement/SearchModify",
data: "domain=" + $("#domain").val() + "&searchfield=" + $("#searchfield").val() + " &searchcriteria=" + $("#searchcriteria").val() + "&searchtype=" + $("#searchtype").val() + "&searchkeyword=" + $("#searchkeyword").val(),
dataType: "json",
success: function (data) {
$("#tablespace").html(data.Message);
table = $('#example').DataTable();
$('#example tbody').on('click', 'tr', function () {
});
$('#example tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function User_ChangePass() {
$("#MiddleMess").html("");
$("#message").html("");
var username = document.getElementById("key").innerHTML.split("@")[0];
var domain = document.getElementById("key").innerHTML.split("@")[1];
var newpass = $("#password").val();
var datas = {
"username": username, "domain": domain, "newpass": newpass
};
$.ajax({
type: "post",
url: "/UserManagement/ChangePass",
data: datas,
dataType: "json",
success: function (data) {
$("#MiddleMess").html(data.Message);
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
function DisableLync_confirm() {
if (confirm("Sure to submit the current user's modification?")) {
DisableLync();
}
else {
return;
}
}
function DisableExchange_confirm() {
if (confirm("Sure to submit the current user's modification?")) {
DisableExchange();
}
else {
return;
}
}
function User_Update_Confirm() {
if (confirm("Sure to submit the current user's modification?")) {
User_update();
}
else {
return;
}
}
function User_update() { //更新用户的信息
$("#message").html("");
$("#MiddleMess").html("");
var action;
if(document.getElementById("EnableAccount").checked){
action = "enable";
} else if (document.getElementById("DisableAccount").checked) {
action = "disable";
}
var username = document.getElementById("key").innerHTML.split("@")[0];
var upnname = $("#UserPrincipalName").val() + "@" + document.getElementById("upnname").value;
var oupath;
var ou1 = document.getElementById("ChoosedOu").innerHTML;
if (ou1 != "") {
var temp = document.getElementById("ChoosedOu").innerHTML.split('LDAP://')[1];
oupath = temp.split('/')[1];
} else {
oupath = "";
}
var accountExpireDate = "";
var v = $('#datebox').datebox('getValue');
var d = v.split("/");
if (document.getElementById("AccountExpiresNever").checked) {
accountExpireDate = "Never";
} else {
accountExpireDate = d[2]+"/"+d[0]+"/"+d[1]+" 16:00:00";
}
var profilePath = document.getElementById("profilePath").value;
var scriptPath = document.getElementById("LoginScript").value;
var homeDirectory;
var homeDrive;
if (document.getElementById("LocalPathRadio").checked) {
homeDrive = "";
homeDirectory = document.getElementById("LocalPath").value;
} else {
homeDirectory = document.getElementById("Connect").value;
homeDrive = document.getElementById("Profileconnect").value;
}
var domain = $("#domain").val();
var userid = $("#UserId").val();
var firstname = $("#FirstName").val();
var lastname = $("#LastName").val();
var displayname = $("#DisplayName").val();
var description = $("#Description").val();
var office = $("#Office").val();
var telephone = $("#Telephone").val();
var mail = $("#mail").val();
var Address= $("#Address").val();
var PostOfficeBox = $("#PostOfficeBox").val();
var City = $("#City").val();
var PostalCode = $("#PostalCode").val();
var Province = $("#Province").val();
var LoginScript = $("#LoginScript").val();
var LocalPath = $("#LocalPath").val();
var Pager = $("#Pager").val();
var MobilePhone = $("#MobilePhone").val();
var Title = $("#Title").val();
var Department = $("#Department").val();
var Company = $("#Company").val();
var adminDescription = $("#adminDescription").val();
var admindisplayname = $("#admindisplayname").val();
var comment = $("#comment").val();
var numberof="";
var rownum = document.getElementById("Memberof_info").innerHTML.split(" ")[5];
for (var i = 0; i < rownum; i++) {
numberof += Memberoftable.row(i).data()[1]+",";
}
$.ajax({
type: "post",
url: "/UserManagement/Modify",
data: "username=" + username + "&userid=" + userid + "&domain=" +
domain + "&firstname=" + firstname + "&lastname=" + lastname + "&displayname=" + displayname + "&description=" +
description + "&office=" + office + "&telephone=" + telephone + "&mail=" + mail + "&accountExpireDate=" + accountExpireDate
+ "&Address=" + Address+ "&PostOfficeBox=" + PostOfficeBox+ "&City=" + City+ "&PostalCode=" + PostalCode+ "&Province=" + Province
+ "&LoginScript=" + LoginScript+ "&LocalPath=" + LocalPath+ "&Pager=" + Pager+ "&MobilePhone=" + MobilePhone+ "&Title=" + Title+ "&Department=" + Department
+ "&Company=" + Company + "&adminDescription=" + adminDescription + "&admindisplayname=" + admindisplayname + "&comment=" +
comment + "&numberof=" + numberof + "&upnname=" + upnname + "&profilePath=" + profilePath + "&homeDrive=" + homeDrive + "&scriptPath=" +
scriptPath + "&homeDirectory=" + homeDirectory + "&action=" + action + "&oupath=" + oupath,
dataType: "json",
success: function (data) {
$("#MiddleMess").html(data.Message);
if (data.logined) {
keyupnname = "";
UserModifySubmited = false;
console.log(UserModifySubmited);
TabColorBlack();
document.getElementById("canclebtn").disabled = true;
var pageindex = table.page();
var d = table.row(targrt).data();
d[1] = userid;
d[2] = firstname;
d[3] = lastname;
d[4] = upnname;
d[5] = displayname;
d[6] = Company;
d[7] = mail;
table.row(targrt).data(d).draw();
table.page(pageindex).draw(false);
table.$('tr.ModifyState').addClass('modified');
table.$('tr.ModifyState').removeClass('ModifyState');
table.$('tr.selected').addClass('ModifyState');
document.getElementById("modifybtn").disabled = true;
if ( action = "enable") { //账户不可用
document.getElementById("DisableAccount").disabled = false;
document.getElementById("EnableAccount").disabled = true;
document.getElementById("AccountEn").style.color = "green";
} else if(action = "disable") { //账户可用
document.getElementById("EnableAccount").disabled = false;
document.getElementById("DisableAccount").disabled = true;
document.getElementById("AccountDis").style.color = "green";
}
}
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function User_Clear() {
$("#MiddleMess").html("");
document.getElementById("searchkeyword").value = "";
document.getElementById("searchclear").disabled = true;
}
function User_Cancle() {
$("#message").html("");
document.getElementById("userlogonname").value = "";
document.getElementById("lastname").value = "";
document.getElementById("firstname").value = "";
document.getElementById("fullname").value = "";
document.getElementById("password").value = "";
document.getElementById("confirmpassword").value = "";
document.getElementById("umcpanl").checked = false;
document.getElementById("uccp").checked = false;
document.getElementById("pne").checked = false;
document.getElementById("aid").checked = false;
document.getElementById("Create_Cancle").disabled = true;
}
function User_Create() { //创建用户
var membersof= document.getElementById("hidekey").innerHTML;
var domain = document.getElementById("Userdomain").value;
var userlogonname = $("#userlogonname").val();
if (userlogonname == "") {
alert("User name cannot be empty!!");
return;
}
var temp = document.getElementById("ChoosedOu").innerHTML.split('LDAP://')[1];
var OuPath = temp.split('/')[1];
var firstname = $("#firstname").val();
console.log(firstname);
var lastname = $("#lastname").val(); console.log(lastname);
if (document.getElementById("firstname").value== "" || document.getElementById("lastname").value == "") {
alert("FirstName Or LastName cannot be empty!!");
return;
}
var fullname = $("#fullname").val();
var password = $("#password").val();
if (document.getElementById("password").value == "") {
alert("Password cannot be empty!!");
return;
}
var umcpanl = document.getElementById("umcpanl").checked ? true : false;
var uccp = document.getElementById("uccp").checked ? true : false;
var pne = document.getElementById("pne").checked ? true : false;
var aid = document.getElementById("aid").checked ? true : false;
var AccountLockouttime = $("#AccountLockouttime").val();
var officephone = $("#officephone").val();
var Department = $("#Department").val();
var Manager = $("#ManageBy").val();
var Company = $("#Company").val();
var EmployeeID = $("#EmployeeID").val();
var Office = $("#Office").val();
var Country = $("#Country").val();
var City = $("#City").val();
$("#message").html("User being created, please wait. . .");
var datas = {
"OuPath" : OuPath ,"domain" : domain, "userlogonname":userlogonname , "email":email ,
"firstname": firstname, "lastname": lastname , "fullname" : fullname ,"password":
<PASSWORD> ,"umcpanl" : umcpanl , "uccp": uccp, "pne": pne, "aid": aid
,"AccountLockouttime": AccountLockouttime
,"officephone" : officephone
,"Department": Department
, "Manager" : Manager
,"Company" : Company
,"EmployeeID": EmployeeID
, "Office":Office,
"Country":Country
,"City" : City , "membersof" : membersof
};
$.ajax({
type: "post",
url: "/UserManagement/CreateUser",
data: datas
// "OuPath=" + OuPath + "&domain=" + domain + "&userlogonname=" + userlogonname + "&email=" + email +
// "&firstname=" + firstname + "&lastname=" + lastname + "&fullname=" + fullname + "&password=" +
// password + "&umcpanl=" + umcpanl + "&uccp=" + uccp + "&pne=" + pne + "&aid=" + aid
// + "&AccountLockouttime=" + AccountLockouttime
// + "&officephone=" + officephone
// + "&Department=" + Department
// + "&Manager=" + Manager
// + "&Company=" + Company
// + "&EmployeeID=" + EmployeeID
// + "&Office=" + Office
// + "&Country=" + Country
// + "&City=" + City + "&membersof=" + membersof
,
dataType: "json",
success: function (data) {
$("#message").html(data.Message);
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function Delete_firm() {
if (confirm("Are you sure you want to delete the user?")) {
User_Delete();
}
else {
//alert("你按了取消,那就是返回false");
}
}
function User_Delete() { //点击删除某个用户
$("#message").html("");
$("#MiddleMess").html("");
table.row('.selected').remove().draw(false);
var username = document.getElementById("key").innerHTML.split("@")[0];
var domain = document.getElementById("key").innerHTML.split("@")[1];
$.ajax({
type: "post",
url: "/UserManagement/Delete",
data: "userid=" + username + "&domain=" + domain,
dataType: "json",
success: function (data) {
$("#message").html(data.Message);
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function User_Detail_Cancle() {
$("#MiddleMess").html("");
$("#message").html("");
document.getElementById("modifybtn").disabled = true;
document.getElementById("canclebtn").disabled = true;
TabColorBlack();
document.getElementById("UserId").value = UserId; //tab页下general
document.getElementById("UserPrincipalName").value = UserPrincipalName;
document.getElementById("FirstName").value = FirstName;
document.getElementById("LastName").value = LastName;
document.getElementById("DisplayName").value = DisplayName;
document.getElementById("Description").value = Description;
document.getElementById("Office").value = Office;
document.getElementById("Telephone").value = Telephone;
document.getElementById("mail").value = mail;
document.getElementById("Address").value = Address;
document.getElementById("PostOfficeBox").value=PostOfficeBox;
document.getElementById("City").value = City;
document.getElementById("PostalCode").value = PostalCode;
document.getElementById("Province").value = Province;
document.getElementById("profilePath").value= profilePath; //tab页profile下
document.getElementById("LoginScript").value = LoginScript;
document.getElementById("LocalPath").value = LocalPath;
document.getElementById("adminDescription").value = adminDescription; //tab页下others
document.getElementById("comment").value = comment;
document.getElementById("Title").value =Title;//tab页下organization
document.getElementById("Department").value = Department;
document.getElementById("Company").value = Company;
document.getElementById("Pager").value = Pager; //tab页下telephones
document.getElementById("MobilePhone").value =MobilePhone;
document.getElementById("admindisplayname").value = admindisplayname;
document.getElementById("upnname").value = UserPrincipalDomain;
$("#membertable").html(MemberOfTable);
Memberoftable = $('#Memberof').DataTable({
"bAutoWidth": false, //是否启用自动适应列宽
"aoColumns": [ //设定各列宽度
{ "sWidth": "50px" },
{ "sWidth": "*" }]
});
$('#Memberof tbody').on('click', 'tr', function () {
var rownum = document.getElementById("GroupChose_info").innerHTML.split(" ")[5];
var d = Memberoftable.row(this).data();
console.log("d1:" + d[1]);
GroupChooser.row.add([
rownum,
d[1],
]).draw().nodes().to$().addClass('modified');
Memberoftable.row(this).remove().draw(false);
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn1").disabled = false;
UserModifySubmited = true;
console.log(UserModifySubmited);
});
if (groupchoseTable != "") {
$("#Grouptablespace").html(groupchoseTable);
GroupChooser = $("#GroupChose").DataTable({
"bAutoWidth": false, //是否启用自动适应列宽
"aoColumns": [ //设定各列宽度
{ "sWidth": "50px" },
{ "sWidth": "*" }]
});
$('#GroupChose tbody').on('click', 'tr', function () {
var rownum = document.getElementById("Memberof_info").innerHTML.split(" ")[5];
var d = GroupChooser.row(this).data();
console.log("d1:" + d[1]);
var arr = new Array()
for (var i = 0; i < rownum; i++) {
arr[i] = Memberoftable.row(i).data()[1];
console.log(Memberoftable.row(i).data()[1]);
}
if (arr.indexOf(d[1]) != -1) {
alert("You selected group name already exists!");
}
else {
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn1").disabled = false;
Memberoftable.row.add([
rownum,
d[1],
]).draw().nodes().to$().addClass('modified');
GroupChooser.row(this).remove().draw(false);
UserModifySubmited = true;
console.log(UserModifySubmited);
}
});
}
}
var targrt;
var Memberoftable;
var User_detail = function (obj) { //获取点击用户的详细信息
$("#message").html("");
$("#MiddleMess").html("");
document.getElementById("TabContent").style.visibility = "visible";
var oObj = event.srcElement; //表格选中变色
if (oObj.tagName.toLowerCase() == "td") {
var oTr = oObj.parentNode;
for (var i = 1; i < document.all.example.rows.length; i++) {
document.all.example.rows[i].style.backgroundColor = "";
document.all.example.rows[i].tag = false;
}
oTr.style.backgroundColor = "#AED0EA";
oTr.tag = true;
}
var userid = $(obj).children('td').next().html();
if (UserModifySubmited) {
if (confirm("Whether to submit the current user's modification?")) {
User_update();
}
else {
table.$('tr.ModifyState').removeClass('ModifyState');
UserModifySubmited = false; //提示修改的时候取消丢弃已作出的更改
console.log(UserModifySubmited);
}
}
TabColorBlack();
TabDateClear();
$.ajax({
type: "post",
url: "/UserManagement/Details",
data: "userid=" + userid + "&domainname=" + $("#domain").val(),
dataType: "json",
success: function (data) {
groupchoseTable = "";
$('#combotree').combotree('setText', data.DistinguishedName);
document.getElementById("deletebtn").disabled = false;
table.$('tr.ModifyState').removeClass('ModifyState');
targrt = obj;
table.$('tr.selected').addClass('ModifyState');
document.getElementById("TabContent").style.visibility = "visible";
$("#key").html(data.UserID+"@"+data.UserPrincipalName.split("@")[1]);
document.getElementById("Address").value = data.Address; //tab页address下
Address = data.Address;
document.getElementById("PostOfficeBox").value = data.PostOfficeBox;
PostOfficeBox = data.PostOfficeBox;
document.getElementById("City").value = data.City;
City = data.City;
document.getElementById("PostalCode").value = data.PostalCode;
PostalCode = data.PostalCode;
document.getElementById("Province").value = data.Province;
Province = data.Province;
document.getElementById("UserId").value = data.UserID; //tab页下general
document.getElementById("UserId").style.color = "gray";
UserId = data.UserID;
document.getElementById("UserPrincipalName").value = data.UserPrincipalName.split("@")[0];
UserPrincipalName = data.UserPrincipalName.split("@")[0];
document.getElementById("FirstName").value = data.FirstName;
FirstName = data.FirstName;
document.getElementById("LastName").value = data.LastName;
LastName = data.LastName;
document.getElementById("DisplayName").value = data.DisplayName;
DisplayName = data.DisplayName;
document.getElementById("Description").value = data.Description;
Description = data.Description;
document.getElementById("Office").value = data.Office;
Office = data.Office;
document.getElementById("Telephone").value = data.Telephone;
Telephone = data.Telephone;
document.getElementById("mail").value = data.mail;
mail = data.mail;
document.getElementById("profilePath").value = data.profilePath; //tab页profile下
profilePath = data.profilePath;
document.getElementById("LoginScript").value = data.scriptPath;
LoginScript = data.scriptPath;
if (data.isRemoteHomeFolder) {
document.getElementById("ConnectRadio").checked = true;
document.getElementById("Profileconnect").value = data.homeDrive;
document.getElementById("Connect").value = data.homeDirectory;
} else {
document.getElementById("LocalPathRadio").checked = true;
document.getElementById("LocalPath").value = data.homeDirectory;
}
LocalPath = data.homeDirectory;
document.getElementById("adminDescription").value = data.adminDescription; //tab页下others
adminDescription = data.adminDescription;
if (data.admindisplayname) {
document.getElementById("admindisplayname").value = checked;
}
if (data.AccountLocked) { //账户被锁
document.getElementById("UnlockAccount").disabled = false;
document.getElementById("AccountState").style.color = "green";
} else { //账户没有被锁
document.getElementById("AccountState").style.color = "black";
document.getElementById("UnlockAccount").disabled = true;
}
document.getElementById("comment").value = data.comment;
comment = data.comment;
document.getElementById("Title").value = data.Title;//tab页下organization
Title = data.Title;
document.getElementById("Department").value = data.Department;
Department = data.Department;
document.getElementById("Company").value = data.Company;
Company = data.Company;
$("#membertable").html(data.memebertable);
MemberOfTable = data.memebertable;
Memberoftable = $('#Memberof').DataTable({
"bAutoWidth": false, //是否启用自动适应列宽
"aoColumns": [ //设定各列宽度
{ "sWidth": "50px" },
{ "sWidth": "*" }]
});
$('#Memberof tbody').on('click', 'tr', function () {
var rownum = document.getElementById("GroupChose_info").innerHTML.split(" ")[5];
var d = Memberoftable.row(this).data();
console.log("d1:" + d[1]);
GroupChooser.row.add([
rownum,
d[1],
]).draw().nodes().to$().addClass('modified');
Memberoftable.row(this).remove().draw(false);
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn1").disabled = false;
UserModifySubmited = true;
console.log(UserModifySubmited);
});
var timefirst = "0001/1/1";
var aed = data.AccountExpDate.split(" ")[0];
if (aed != timefirst) {
document.getElementById("AccountExpiresEndOf").checked = true;
var date = aed.split("/");
$('#datebox').datebox('setValue', date[1]+"/"+date[2]+"/"+date[0]);
$("#datebox").datebox("enable");
} else {
document.getElementById("AccountExpiresNever").checked = true;
$("#datebox").datebox("disable");
}
document.getElementById("Pager").value = data.Pager; //tab页下telephones
Pager = data.Pager;
document.getElementById("MobilePhone").value = data.MobilePhone;
MobilePhone = data.MobilePhone;
document.getElementById("admindisplayname").value = data.DisplayName;
admindisplayname = data.DisplayName;
var upnname = "<option value=\""+data.UserPrincipalName.split("@")[1] + "\">" + "@"+data.UserPrincipalName.split("@")[1] + "</option>";
if (data.uPNSuffixes.length > 0) {
for (var i = 0; i < data.uPNSuffixes.length; i++) {
var mess = data.uPNSuffixes[i];
if (mess != data.UserPrincipalName.split("@")[1]) {
upnname += "<option value=\"" + mess + "\">" + "@" + mess + "</option>";
}
}
}
UserPrincipalDomain = data.UserPrincipalName.split("@")[1];
document.getElementById("upnname").innerHTML = upnname;
keyupnname = data.UserPrincipalName.split("@")[1];
if (data.AccountDisabled) { //账户不可用
document.getElementById("EnableAccount").checked = false;
document.getElementById("DisableAccount").checked = true;
document.getElementById("DisableAccount").disabled = true;
} else { //账户可用
document.getElementById("EnableAccount").checked = true;
document.getElementById("EnableAccount").disabled = true;
document.getElementById("DisableAccount").checked = false;
}
if (data.SkypeForBusinessEnabled) {
document.getElementById("EnableLync").checked = true;
document.getElementById("EnableLync").disabled = true;
document.getElementById("DisableLync").checked = false;
} else {
document.getElementById("EnableLync").checked = false;
document.getElementById("DisableLync").checked = true;
document.getElementById("DisableLync").disabled = true;
}
if (data.ExchangeEnabled) {
document.getElementById("EnableExchange").disabled = true;
document.getElementById("EnableExchange").checked = true;
document.getElementById("DisableExchange").checked = false;
} else {
document.getElementById("DisableExchange").disabled = true;
document.getElementById("EnableExchange").checked = false;
document.getElementById("DisableExchange").checked = true;
}
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
};
function RandomPass() {
document.getElementById("passmess").innerHTML = "";
document.getElementById("passwordremind").innerHTML = "";
//获取随即密码
$.ajax({
type: "post",
url: "/UserManagement/RandomPass",
dataType: "json",
success: function (data) {
document.getElementById("password").value = data.Message;
//document.getElementById("confirmpassword").value = data.Message;
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function verify() {
var newpass = $("#password").val();
var confirmpass = $("#confirmpassword").val();
if(newpass==confirmpass){
document.getElementById("changePassbtn").disabled = false;
}
}
function EnableLync() { //Enable/Disable Lync
var username = document.getElementById("key").innerHTML.split("@")[0];
$("#MiddleMess").html("Waiting...");
var action = "enable";
$.ajax({
type: "post",
url: "/UserManagement/EnableLync",
data: "username=" + username + "&domain=" + $("#domain").val() + "&action=" + action,
dataType: "json",
success: function (data) {
$("#MiddleMess").html(data.Message);
$("#UcMess").html("");
document.getElementById("EnableLync").disabled = true;
document.getElementById("DisableLync").disabled = false;
document.getElementById("LyncEn").style.color = "green";
document.getElementById("LyncDis").style.color = "black";
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
function DisLyncConfirm() {
if (confirm("Are you sure you want to Disable the Lync?")) {
DisableLync();
}
else {
document.getElementById("EnableLync").checked = true;
document.getElementById("DisableLync").checked = false;
//alert("你按了取消,那就是返回false");
}
}
function DisableLync() { //Enable/Disable Lync
$("#MiddleMess").html("Waiting...");
var username = document.getElementById("key").innerHTML.split("@")[0];
var action = "disable";
$.ajax({
type: "post",
url: "/UserManagement/EnableLync",
data: "username=" + username + "&domain=" + $("#domain").val() + "&action=" + action,
dataType: "json",
success: function (data) {
$("#MiddleMess").html(data.Message);
$("#UcMess").html("");
document.getElementById("EnableLync").disabled = false;
document.getElementById("DisableLync").disabled = true;
document.getElementById("LyncEn").style.color = "black";
document.getElementById("LyncDis").style.color = "green";
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
function EnableConfirm() {
document.getElementById("exchangeType").style.visibility = "visible";
}
function EnableExchange() { //Enable/Disable Exchange
var exchangeType;
if (document.getElementById("Person").checked) {
exchangeType = "UserMailbox";
} else if (document.getElementById("Room").checked) {
exchangeType = "RoomMailbox";
} else if (document.getElementById("Share").checked) {
exchangeType = "SharedMailbox";
}else{
exchangeType = "EquipmentMailbox";
}
document.getElementById("key").innerHTML.split("@")[0]
$("#MiddleMess").html("Waiting...");
var username = document.getElementById("key").innerHTML.split("@")[0];
var action = "enable";
$.ajax({
type: "post",
url: "/UserManagement/EnableExchange",
data: "username=" + username + "&domain=" + $("#domain").val() + "&action=" + action + "&exchangeType=" + exchangeType,
dataType: "json",
success: function (data) {
$("#MiddleMess").html(data.Message);
document.getElementById("ExchangeEn").style.color = "green";
document.getElementById("EnableExchange").disabled = true;
document.getElementById("ExchangeDis").style.color = "black";
document.getElementById("DisableExchange").disabled = false;
var d = table.row(targrt).data();
d[9] = "<a type=\"button\" href=\"ModifyExchange?userid=" + d[1] + "&domain=" + $("#domain").val() + "\" target=\"_blank\" class=\"btn btn - block\">Modify</a>";
table.row(targrt).data(d).draw();
table.$('tr.selected').addClass('modified');
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
function DisExchangeConfirm() {
if (confirm("Are you sure you want to Disable the Exchange?")) {
DisableExchange();
}
else {
document.getElementById("EnableExchange").checked = true;
document.getElementById("DisableExchange").checked = false;
}
}
function DisableExchange() { //Enable/Disable Exchange
$("#MiddleMess").html("Waiting...");
var username = document.getElementById("key").innerHTML.split("@")[0];
var action = "disable";
$.ajax({
type: "post",
url: "/UserManagement/EnableExchange",
data: "username=" + username + "&domain=" + $("#domain").val() + "&action=" + action,
dataType: "json",
success: function (data) {
$("#MiddleMess").html(data.Message);
$("#MiddleMess").html("");
document.getElementById("ExchangeEn").style.color = "black";
document.getElementById("EnableExchange").disabled = false;
document.getElementById("ExchangeDis").style.color = "green";
document.getElementById("DisableExchange").disbled = true;
var d = table.row(targrt).data();
d[9] = " ";
table.row(targrt).data(d).draw();
table.$('tr.selected').addClass('modified');
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
function UnlockAccount() {
$("#MiddleMess").html("Waiting...");
var username = document.getElementById("key").innerHTML.split("@")[0];
$.ajax({
type: "post",
url: "/UserManagement/AccountUnlock",
data: "username=" + username + "&domain=" + $("#domain").val() ,
dataType: "json",
success: function (data) {
document.getElementById("AccountState").style.color = "black";
document.getElementById("UnlockAccount").disabled = true;
$("#MiddleMess").html(data.Message);
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
}
var Userchange = function (obj) { //获取点击用户的详细信息
var reg = /^[\s ]|[ ]$/gi;
var girlfirend = $(obj).context;
var text = girlfirend.value;
if (text == Cache) {
girlfirend.style.color = "black";
return;
}
if (!reg.test(text)) {
girlfirend.style.color = "green";
UserModifySubmited = true;
console.log(UserModifySubmited);
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn1").disabled = false;
} else {
return;
}
};
var Userchange_firstname = function (obj) { //获取点击用户的详细信息
var reg = /^[\s ]|[ ]$/gi;
var girlfirend = $(obj).context;
var text = girlfirend.value;
document.getElementById("DisplayName").value = text + " " + document.getElementById("LastName").value;
if (text == Cache) {
girlfirend.style.color = "black";
return;
}
if (!reg.test(text)) {
girlfirend.style.color = "green";
UserModifySubmited = true;
console.log(UserModifySubmited);
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn1").disabled = false;
} else {
return;
}
};
var Userchange_lastname = function (obj) { //获取点击用户的详细信息
var reg = /^[\s ]|[ ]$/gi;
var girlfirend = $(obj).context;
var text = girlfirend.value;
document.getElementById("DisplayName").value = document.getElementById("FirstName").value + " " + text;
if (text == Cache) {
girlfirend.style.color = "black";
return;
}
if (!reg.test(text)) {
girlfirend.style.color = "green";
UserModifySubmited = true;
console.log(UserModifySubmited);
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn1").disabled = false;
} else {
return;
}
};
function TabColorBlack() {
document.getElementById("AccountDis").style.color = "black";
document.getElementById("AccountEn").style.color = "black";
document.getElementById("UserId").style.color = "black";
document.getElementById("UserPrincipalName").style.color = "black";
document.getElementById("FirstName").style.color = "black";
document.getElementById("LastName").style.color = "black";
document.getElementById("DisplayName").style.color = "black";
document.getElementById("Description").style.color = "black";
document.getElementById("Office").style.color = "black";
document.getElementById("Telephone").style.color = "black";
document.getElementById("mail").style.color = "black";
document.getElementById("Address").style.color = "black";
document.getElementById("PostOfficeBox").style.color = "black";
document.getElementById("City").style.color = "black";
document.getElementById("PostalCode").style.color = "black";
document.getElementById("Province").style.color = "black";
document.getElementById("profilePath").style.color = "black";
document.getElementById("LoginScript").style.color = "black";
document.getElementById("LocalPath").style.color = "black";
document.getElementById("Pager").style.color = "black";
document.getElementById("MobilePhone").style.color = "black";
document.getElementById("Title").style.color = "black";
document.getElementById("Department").style.color = "black";
document.getElementById("Company").style.color = "black";
document.getElementById("adminDescription").style.color = "black";
document.getElementById("admindisplayname").style.color = "black";
document.getElementById("comment").style.color = "black";
document.getElementById("LyncEn").style.color = "black";
document.getElementById("LyncDis").style.color = "black";
document.getElementById("ExchangeEn").style.color = "black";
document.getElementById("ExchangeDis").style.color = "black";
document.getElementById("AccountDis").style.color = "black";
document.getElementById("AccountEn").style.color = "black";
}
function TabDateClear() {
$("#AccountMess").html("");
$('#combotree').combotree('setText', "");
document.getElementById("Connect").value = "";
document.getElementById("Profileconnect").value = "D:";
document.getElementById("UnlockAccount").checked = false;
document.getElementById("UnlockAccount").disabled = false;
document.getElementById("EnableAccount").checked = false;
document.getElementById("EnableAccount").disabled = false;
document.getElementById("DisableAccount").checked = false;
document.getElementById("DisableAccount").disabled = false;
document.getElementById("AccountExpiresEndOf").checked = false;
document.getElementById("AccountExpiresNever").disabled = false;
document.getElementById("AccountExpiresEndOf").disabled = false;
document.getElementById("AccountExpiresNever").checked = false;
document.getElementById("DisableLync").checked = false;
document.getElementById("EnableLync").checked = false;
document.getElementById("EnableExchange").checked = false;
document.getElementById("DisableExchange").checked = false;
document.getElementById("DisableLync").disabled = false;
document.getElementById("EnableLync").disabled = false;
document.getElementById("EnableExchange").disabled = false;
document.getElementById("DisableExchange").disabled = false;
document.getElementById("Address").value = "";
document.getElementById("PostOfficeBox").value = "";
document.getElementById("upnname").value = "";
document.getElementById("City").value = "";
document.getElementById("PostalCode").value = "";
document.getElementById("Province").value = "";
document.getElementById("UserId").value = "";
document.getElementById("UserPrincipalName").value = "";
document.getElementById("FirstName").value = "";
document.getElementById("LastName").value = "";
document.getElementById("DisplayName").value = "";
document.getElementById("Description").value = "";
document.getElementById("Office").value = "";
document.getElementById("Telephone").value = "";
document.getElementById("mail").value = "";
document.getElementById("profilePath").value = "";
document.getElementById("LoginScript").value = "";
document.getElementById("LocalPath").value = "";
document.getElementById("adminDescription").value = "";
document.getElementById("comment").value = "";
document.getElementById("Title").value = "";
document.getElementById("Department").value = "";
document.getElementById("Company").value = "";
document.getElementById("Pager").value = "";
document.getElementById("MobilePhone").value = "";
}
var GroupChooser;
function User_Group_Search() {
$("#MiddleMess").html("");
$("#Grouptablespace").html("<h4 style=\"color:orange\">Searching....Please wait</h4>");
var rownum = document.getElementById("Memberof_info").innerHTML.split(" ")[5];
for (var i = 0; i < rownum; i++) {
}
var userid= document.getElementById("key").innerHTML.split("@")[0];
var userdomain= document.getElementById("key").innerHTML.split("@")[1];
$.ajax({
type: "post",
url: "/UserManagement/GroupSearch",
data: "groupdomain=" + $("#groupdomain").val() + "&searchkeyword=" + $("#groupkeyword").val() + "&userid=" + userid + "&domainname=" +userdomain,
dataType: "json",
success: function (data) {
groupchoseTable = data.Message;
console.log(groupchoseTable);
$("#Grouptablespace").html(data.Message);
GroupChooser = $("#GroupChose").DataTable({
"bAutoWidth": false, //是否启用自动适应列宽
"aoColumns": [ //设定各列宽度
{ "sWidth": "50px" },
{ "sWidth": "*" }]
});
$('#GroupChose tbody').on('click', 'tr', function () {
var rownum = document.getElementById("Memberof_info").innerHTML.split(" ")[5];
var d = GroupChooser.row(this).data();
console.log("d1:"+d[1]);
var arr = new Array()
for (var i = 0; i < rownum; i++) {
arr[i] = Memberoftable.row(i).data()[1];
console.log(Memberoftable.row(i).data()[1]);
}
if(arr.indexOf(d[1])!=-1){
alert("You selected group name already exists!");
}
else {
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn1").disabled = false;
Memberoftable.row.add([
rownum,
d[1],
]).draw().nodes().to$().addClass('modified');
GroupChooser.row(this).remove().draw(false);
UserModifySubmited = true;
console.log(UserModifySubmited);
}
});
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
var times = 0;
$("#Userdomain").on("change", function () {
$("#MiddleMess").html("");
times += 1;
if (times == 1) {
var chosed = $("#Userdomain").val();
console.log(chosed);
if (document.getElementById("combotree") != null) {
$('#combotree').combotree({
url:'/UserManagement/Outree?domain='+chosed,
required: true,
onSelect: function (node) {
//alert(node.id);
document.getElementById("ChoosedOu").innerHTML = node.path;
}
});
}
times = 0;
}
});
$("#upnname").on("change", function () {
$("#MiddleMess").html("");
var domain = $("#upnname").val();
var username = document.getElementById("key").innerHTML.split("@")[0];
if (keyupnname != domain) {
$.ajax({
type: "post",
url: "/UserManagement/UPNName",
data: "username=" + username + "&domain=" + domain,
dataType: "json",
success: function (data) {
if (data.Message == "1") {
alert("The Specified user Logon name already exists in the enterprise!")
document.getElementById("upnname").value = UserPrincipalDomain;
} else {
document.getElementById("canclebtn").disabled = false;
document.getElementById("modifybtn1").disabled = false;
UserModifySubmited = true;
console.log(UserModifySubmited);
}
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
});
function User_Group_Search_begin() {
var event = window.event || arguments.callee.caller.arguments[0];
if (event.keyCode == 13) {
User_Group_Search();
}
}
var verifyExchange = function (obj) {
$("#MiddleMess").html("");
var userid = $(obj).parent().parent().children('td').next().html();
var domain = $("#domain").val();
$.ajax({
type: "post",
url: "/UserManagement/verifyExchange",
data: "userid=" + userid + "&domain=" + $("#domain").val(),
dataType: "json",
success: function (data) {
if (data.logined) {
window.open("ModifyExchange?userid=" + data.Message.split("@")[0] + "&domain=" + data.Message.split("@")[1]);
window.targrt = "_blank";
} else {
alert(data.Message);
}
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
return;
}
function AccountNever() {
$("#datebox").datebox("disable");
}
function AccountEndof() {
$("#datebox").datebox("enable");
}
var Cache;
var Gettextlen = function (obj){
Cache = $(obj).context.value;
}
function User_Exchange_Modify() {
var userid = document.getElementById("key").innerHTML.split("@")[0];
var domain = $("#domain").val();
var DisplayName = document.getElementById("DisplayName").value;
var emailname = document.getElementById("Emailname").value;
var Database = document.getElementById("Database").value;
var AccountType = document.getElementById("AccountType").value;
var SendAsDelegates = document.getElementById("SendAsDelegates").value;
var FMADelegates = document.getElementById("FMADelegates").value;
var BlackBerryEnabled = document.getElementById("BlackBerryEnabled").checked ? true : false;
var RestrictedUsage = document.getElementById("RestrictedUsage").checked ? true : false;
var HideFromOAB = document.getElementById("HideFromOAB").checked ? true : false;
var IMAPEnabled = document.getElementById("IMAPEnabled").checked ? true : false;
var POP3Enabled = document.getElementById("POP3Enabled").checked ? true : false;
var EmailDomian = document.getElementById("EmailDomian").value;
var ActiveSyncMailboxPolicys = document.getElementById("ActiveSyncMailboxPolicys").value;
var Emailboxquotas = document.getElementById("Emailboxquotas").value;
$.ajax({
type: "post",
url: "/ExchangeManagement/ExchangModfiy",
data: "userid=" + userid + "&domain=" + domain + "&FMADelegates=" + FMADelegates
+ "&BlackBerryEnabled=" + BlackBerryEnabled + "&RestrictedUsage=" + RestrictedUsage + "&HideFromOAB=" + HideFromOAB + "&IMAPEnabled=" + IMAPEnabled + "&POP3Enabled=" + POP3Enabled
+ "&ActiveSyncMailboxPolicys=" + ActiveSyncMailboxPolicys + "&Emailboxquotas=" + Emailboxquotas
+ "&Database=" + Database + "&EmailDomian=" + EmailDomian + "&emailname=" + emailname + "&DisplayName=" + DisplayName,
dataType: "json",
success: function (data) {
$("#message").html(data.Message);
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function EnableAccount() {
$("#message").html("");
$("#AccountMess").html("Waiting...");
var username = document.getElementById("key").innerHTML.split("@")[0];
var action = "enable";
$.ajax({
type: "post",
url: "/UserManagement/EnableAccount",
data: "username=" + username + "&domain=" + $("#domain").val() + "&action=" + action,
dataType: "json",
success: function (data) {
$("#AccountMess").html(data.Message);
document.getElementById("EnableAccount").disabled = true;
document.getElementById("DisableAccount").disabled = false;
document.getElementById("AccountEn").style.color = "green";
document.getElementById("AccountDis").style.color = "black";
table.$('tr.selected').addClass('modified');
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function DisAccountConfirm() {
if (confirm("Are you sure you want to Disable the Account?")) {
DisableAccount();
}
else {
}
}
function DisableAccount() {
$("#message").html("");
$("#AccountMess").html("Waiting...");
var username = document.getElementById("key").innerHTML.split("@")[0];
var action = "disable";
$.ajax({
type: "post",
url: "/UserManagement/EnableAccount",
data: "username=" + username + "&domain=" + $("#domain").val() + "&action=" + action,
dataType: "json",
success: function (data) {
$("#AccountMess").html(data.Message);
document.getElementById("DisableAccount").disabled = true;
document.getElementById("AccountDis").style.color = "green";
document.getElementById("EnableAccount").disabled = false;
document.getElementById("AccountEn").style.color = "black";
table.$('tr.selected').addClass('modified');
}
,
error: function () {
$("#message").html("Network interrupt, networking timeout");
}
});
}
function User_create_manager() {
var domain = document.getElementById("Userdomain").value;
var manager = document.getElementById("ManageBy").value;
$.ajax({
type: "post",
url: "/UserManagement/Testmanager",
data: "domain=" + domain + "&manager=" + manager ,
dataType: "json",
success: function (data) {
if (data.num > 0) {
if (data.Company != "") {
document.getElementById("Company").value = data.Company;
}
if (data.Department != "") {
document.getElementById("Department").value = data.Department;
}
if (data.Office != "") {
document.getElementById("Office").value = data.Office;
}
if (data.City != "") {
document.getElementById("City").value = data.City;
}
if (data.Telephone != "") {
document.getElementById("officephone").value = data.Telephone;
}
if (data.memebertable != "") {
$("#hidekey").html(data.memebertable);
}
} else {
if (confirm("The User You Typed Is Not Existed!")) {
document.getElementById("ManageBy").value = "";
document.getElementById("ManageBy").style.color = "";
}
else {
document.getElementById("ManageBy").value = "";
document.getElementById("ManageBy").style.color = "";
}
}
}
,
error: function () {
$("#MiddleMess").html("Network interrupt, networking timeout");
}
});
} | 6d8ea398325f57f14e683eeb3b1cc82a094c7aad | [
"JavaScript",
"C#"
] | 36 | C# | chezhenjun110/ManagementSystem | e038eaed8af044bc6fe2da05c8f7ef4051fadeff | ac4801c8d62f46061d7d2cd440ebd9aa5fa2dfb0 |
refs/heads/main | <file_sep>#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
# In[2]:
commercial = pd.read_csv('./commercial.csv')
commercial
# In[3]:
# 끝에 5개 데이터만 추출
commercial.tail(5)
# In[5]:
list(commercial), len(list(commercial))
# In[7]:
commercial.groupby('상가업소번호')['상권업종소분류명'].count().sort_values(ascending=False)
# In[10]:
category_range = set(commercial['상권업종소분류명'])
category_range, len(category_range)
# In[11]:
commercial['도로명주소']
# In[15]:
# 서울시 데이터만 가져오기
# 3덩어리로 쪼갠 후 새로운 칼럼 추가
commercial[['시','구','상세주소']] = commercial['도로명주소'].str.split(' ',n=2, expand=True)
# In[16]:
commercial.tail(5)
# In[18]:
# 서울특별시의 데이터만 추출
seoul_data = commercial[ commercial['시'] == '서울특별시']
seoul_data.tail(5)
# In[22]:
# 서울만 있는지 확인하기(집합연산)
city_type = set(seoul_data['시'])
city_type
# In[24]:
# 서울 치킨집만 추출
seoul_chicken_data = seoul_data[ seoul_data['상권업종소분류명'] == '후라이드/양념치킨' ]
seoul_chicken_data
# In[31]:
sorted_chicken_count_by_gu = seoul_chicken_data.groupby('구')['상권업종소분류명'].count().sort_values(ascending=False)
sorted_chicken_count_by_gu
# In[33]:
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Malgun Gothic'
# In[34]:
plt.figure(figsize=(10,5))
plt.bar(sorted_chicken_count_by_gu.index, sorted_chicken_count_by_gu)
plt.title('구에 따른 치킨 매장 수')
plt.xticks(rotation = 90)
plt.show()
# In[38]:
# 지도에 그리기
import folium
import json
# In[41]:
# 지도정보 불러오기
seoul_geo = './seoul_geo.json'
geo_data = json.load(open(seoul_geo, encoding = 'utf-8'))
geo_data
# In[50]:
# 지도 만들기
map = folium.Map(location=[37.5502, 126.982], zoom_start=11)
map
# In[51]:
folium.Choropleth(geo_data = geo_data,
data=sorted_chicken_count_by_gu,
colums=[sorted_chicken_count_by_gu.index, sorted_chicken_count_by_gu],
fill_color='PuRd',
key_on='properties.name').add_to(map)
map
# In[ ]:
| 41ea7dd69aab797bca15aa6b862b9e20ae5cadb3 | [
"Python"
] | 1 | Python | dleorud111/chicken_data_geo_graph | e61a3c21252ceb18c133488dfb8ef8849c542da9 | b6c0091cc7dc0610fd7df35a70da7548ab60a322 |
refs/heads/master | <file_sep>import React from 'react';
import PropTypes from 'prop-types';
const CreatorCard = ({
id,
fullName,
comics: { items },
thumbnail: { path, extension },
history,
saveResource,
showSaveItemErrorModal,
isSignedIn,
}) => {
const selectCreator = () => history.push(`/creators/${id}`);
const saveResourceApiCall = () => saveResource({ id, name: fullName, resourceType: history.location.pathname.slice(1) });
const saveItemFunction = isSignedIn ? saveResourceApiCall : showSaveItemErrorModal;
return (
<div className="column is-half">
<div className="box">
<article className="media">
<div className="media-left">
<figure className="image is-64x64">
<img src={`${path}.${extension}`} alt="http://bulma.io/images/placeholders/128x128.png" />
</figure>
</div>
<div className="media-content">
<div className="content">
<p>
<strong>{ fullName }</strong>
<br />
</p>
{ items.length ? <p><em>Comics:</em></p> : null }
{ items.map(comic => <p>{ comic.name }</p>) }
</div>
<nav className="level is-mobile">
<div className="level-left">
<a className="level-item icon-sm-screen">
<span className="icon is-small r-mar-5">
<i className="fa fa-bookmark" />
</span>
<span className="is-small save-btn" role="presentation" onClick={saveItemFunction}>Save</span>
</a>
<a className="level-item">
<span className="icon is-small r-mar-5">
<i className="fa fa-info-circle" />
</span>
<span className="is-small details-btn" role="presentation" onClick={selectCreator}>Details</span>
</a>
</div>
</nav>
</div>
</article>
</div>
</div>
);
};
CreatorCard.propTypes = {
id: PropTypes.number.isRequired,
fullName: PropTypes.string.isRequired,
comics: PropTypes.shape({
items: PropTypes.array.isRequired,
}).isRequired,
thumbnail: PropTypes.shape({
extension: PropTypes.string.isRequired,
path: PropTypes.string.isRequired,
}).isRequired,
history: PropTypes.object.isRequired,
saveResource: PropTypes.func.isRequired,
showSaveItemErrorModal: PropTypes.func.isRequired,
isSignedIn: PropTypes.bool.isRequired,
};
export default CreatorCard;
<file_sep>import React from 'react';
import { compose, lifecycle, branch, renderComponent } from 'recompose';
import InfiniteScrollHOC from './infiniteScroll';
import LoadingHOC from './loading';
import NoResultsFound from '../components/misc/noResultsFound';
export default compose(
lifecycle({
componentDidMount() {
const { getUser, apiCall, match = {}, isSignedIn } = this.props;
const id = match.params && match.params.id;
if (isSignedIn) {
getUser();
}
if (apiCall) {
apiCall(id);
}
},
componentWillUnmount() {
this.props.clearApiData();
this.props.clearSearchTerm();
this.props.clearLetter();
}
}),
InfiniteScrollHOC,
LoadingHOC,
branch(
props => !props.display.get('loading') && !Object.keys(props.data).length,
renderComponent(NoResultsFound),
),
);
<file_sep>import React from 'react';
export default () => (
<div>
<div className="sp sp-circle" />
<div id="overlay" />
</div>
);
<file_sep>import { call, put, takeEvery, takeLatest } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import * as Api from '../utils/api';
import {
LOADING,
FETCH_FAILED,
SET_SEARCH_TERM,
CLEAR_SEARCH_TERM,
SET_PAGINATION_DATA,
SET_LETTER,
CLEAR_LETTER,
} from '../constants/display';
import {
CREATORS_FETCH_SUCCEEDED,
SELECTED_CREATOR_FETCH_SUCCEEDED,
GET_CREATORS,
GET_SELECTED_CREATOR,
SEARCH_CREATORS,
CREATORS_SEARCH_SUCCEEDED,
SEARCH_CREATORS_BY_LETTER,
} from '../constants/creators';
function* fetchCreators({ offset, searchTerm }) {
try {
yield put({ type: LOADING, payload: true });
const creators = yield call(Api.fetchCreators, offset, searchTerm);
const { data, total, count } = creators.data;
yield put({ type: CREATORS_FETCH_SUCCEEDED, creators: data.filter(v => v.fullName) });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* fetchSelectedCreator({ id }) {
try {
yield put({ type: LOADING, payload: true });
const creator = yield call(Api.fetchSelectedCreator(id));
yield put({ type: SELECTED_CREATOR_FETCH_SUCCEEDED, creator: creator.data.data[0] });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* searchCreators({ searchTerm }) {
try {
yield put({ type: SET_SEARCH_TERM, payload: searchTerm });
yield put({ type: CLEAR_LETTER });
yield call(delay, 500);
yield put({ type: LOADING, payload: true });
const creators = yield call(Api.searchCreators, searchTerm);
const { data, total, count } = creators.data;
yield put({ type: CREATORS_SEARCH_SUCCEEDED, creators: data });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* searchCreatorsByLetter({ searchTerm }) {
try {
yield put({ type: SET_LETTER, letter: searchTerm });
yield put({ type: CLEAR_SEARCH_TERM });
yield put({ type: LOADING, payload: true });
const creators = yield call(Api.searchCreators, searchTerm);
const { data, total, count } = creators.data;
yield put({ type: CREATORS_SEARCH_SUCCEEDED, creators: data });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* getCreators() {
yield takeEvery(GET_CREATORS, fetchCreators);
yield takeEvery(GET_SELECTED_CREATOR, fetchSelectedCreator);
yield takeLatest(SEARCH_CREATORS, searchCreators);
yield takeLatest(SEARCH_CREATORS_BY_LETTER, searchCreatorsByLetter);
}
export default getCreators;
<file_sep>import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import ComicCard from '../../components/cards/comicCard';
Enzyme.configure({ adapter: new Adapter() })
describe('Comic Card', () => {
const props = {
id: 123,
title: 'Spiderman',
issueNumber: 4,
series: { name: 'Spiderman vs Venom' },
prices: [ { price: 15 } ],
thumbnail: {
path: 'test',
extension: 'com',
},
history: {
location: { pathname: '/comics/:id'},
push: jest.fn(),
},
saveResource: jest.fn(),
showSaveItemErrorModal: jest.fn(),
isSignedIn: true,
};
it('Should render correctly', () => {
const wrapper = shallow(
<ComicCard
id={props.id}
title={props.title}
issueNumber={props.issueNumber}
series={props.series}
prices={props.prices}
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
expect(wrapper).toMatchSnapshot();
});
it('Should call save button on click when logged in', () => {
const wrapper = shallow(
<ComicCard
id={props.id}
title={props.title}
issueNumber={props.issueNumber}
series={props.series}
prices={props.prices}
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
wrapper.find(".save-btn").simulate('click');
expect(props.saveResource.mock.calls.length).toBe(1);
expect(props.saveResource.mock.calls[0][0])
.toEqual({
id: 123,
name: 'Spiderman',
resourceType: 'comics/:id'
});
});
it('Should call more details button on click', () => {
const wrapper = shallow(
<ComicCard
id={props.id}
title={props.title}
issueNumber={props.issueNumber}
series={props.series}
prices={props.prices}
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
wrapper.find(".details-btn").simulate('click');
expect(props.history.push.mock.calls.length).toBe(1);
expect(props.history.push.mock.calls[0][0]).toBe('/comics/123');
});
});
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
const RenderField = ({ input, type, placeholder, iconClasses, meta: { error } }) => {
const inputClasses = error ? 'input is-medium is-danger' : 'input is-medium';
return (
<div className="field">
<p className="control has-icons-left">
<input {...input} className={inputClasses} type={type} placeholder={placeholder} />
<span className="icon is-small is-left">
<i className={iconClasses} />
</span>
</p>
<p className="help is-danger">{ error }</p>
</div>
);
};
RenderField.propTypes = {
input: PropTypes.shape({
name: PropTypes.string.isRequired,
onBlur: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
onDragStart: PropTypes.func.isRequired,
onDrop: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,
value: PropTypes.string.isRequired,
}).isRequired,
type: PropTypes.string.isRequired,
placeholder: PropTypes.string.isRequired,
iconClasses: PropTypes.string.isRequired,
meta: PropTypes.shape({ error: PropTypes.string }).isRequired,
};
export default RenderField;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import Immutable from 'immutable';
const RegistrationSuccessful = ({ user }) => (
<div className="is-size-4 has-text-centered">
Congratulations { user.get('user').name }!
You have successfully registered with email address { user.get('user').email }.
Click <Link to="/sign-in">here</Link> to sign in!
</div>
);
RegistrationSuccessful.propTypes = {
user: PropTypes.instanceOf(Immutable.Map).isRequired,
};
export default RegistrationSuccessful;
<file_sep>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { Map } from 'immutable';
import reducer from '../../reducers/series';
import {
SERIES_FETCH_SUCCEEDED,
SELECTED_SERIES_FETCH_SUCCEEDED,
SERIES_SEARCH_SUCCEEDED,
} from '../../constants/series';
Enzyme.configure({ adapter: new Adapter() });
describe('Series Reducer', () => {
const initialState = new Map({
series: [],
selectedSeries: {},
});
it('Should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(initialState);
});
it('Should handle SERIES_FETCH_SUCCEEDED', () => {
expect(
reducer(new Map(), {
type: SERIES_FETCH_SUCCEEDED,
series: [
{ id: 1, name: 'spiderman' },
],
}),
).toEqual(new Map({
series: [
{ id: 1, name: 'spiderman' },
],
}));
});
it('Should handle SERIES_SEARCH_SUCCEEDED', () => {
expect(
reducer(new Map(), {
type: SERIES_SEARCH_SUCCEEDED,
series: [
{ id: 1, name: 'spiderman' },
],
}),
).toEqual(new Map({
series: [
{ id: 1, name: 'spiderman' },
],
}));
});
it('Should handle SELECTED_SERIES_FETCH_SUCCEEDED', () => {
expect(
reducer(new Map(), {
type: SELECTED_SERIES_FETCH_SUCCEEDED,
series: { id: 1, name: 'spiderman' },
}),
).toEqual(new Map({
selectedSeries: { id: 1, name: 'spiderman' },
}));
});
});
<file_sep>import charactersSaga from './characters';
import comicsSaga from './comics';
import creatorsSaga from './creators';
import eventsSaga from './events';
import authSaga from './auth';
import userSaga from './user';
import seriesSaga from './series';
export default function* root() {
yield [
charactersSaga(),
comicsSaga(),
creatorsSaga(),
eventsSaga(),
authSaga(),
userSaga(),
seriesSaga(),
];
}
<file_sep>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { call, takeEvery } from 'redux-saga/effects';
import { runSaga } from 'redux-saga';
import { signIn, logout } from '../../__mocks__/auth';
Enzyme.configure({ adapter: new Adapter() });
describe('Auth Sagas', () => {
it('Should test sign in saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
getState: () => ({
form: {
signIn: {
values: {
email: '<EMAIL>',
password: '<PASSWORD>'
}
}
}
})
}, signIn).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'SIGN_IN_SUCCEEDED',
user: {
username: 'Pikachu',
email: '<EMAIL>',
}
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
});
<file_sep>const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyWebpackPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const cssnano = require('cssnano');
exports.devServer = ({ host, port } = {}) => ({
devServer: {
stats: 'errors-only', // Only display errors to reduce output.
host, // Defaults to localhost
port, // Defaults to port 8080
historyApiFallback: true, // Enabled if using HTML5 History API based routing.
overlay: { // equivalent to overlay: true; provides an overlay in the browser for capturing errors and warnings
errors: true,
warnings: true,
},
compress: true,
},
});
exports.loadCSS = ({ include, exclude } = {}) => ({
module: {
rules: [
{
test: /\.scss$/,
include,
exclude,
use: [
'style-loader',
'css-loader', // add sourceMap true?
{
loader: 'postcss-loader',
options: {
sourceMap: true,
plugins: () => [require('autoprefixer')],
},
},
'sass-loader', // add sourceMap true?
],
},
],
},
});
exports.extractCSS = ({ include, exclude, use }) => {
const plugin = new ExtractTextPlugin({
// `allChunks` is needed with CommonsChunkPlugin to extract
// from extracted chunks as well
allChunks: true,
filename: '[name].[contenthash].css',
});
return {
module: {
rules: [
{
test: /\.scss$/,
include,
exclude,
use: plugin.extract({
use,
fallback: 'style-loader',
}),
},
],
},
plugins: [plugin],
};
};
exports.loadImages = ({ include, exclude, options } = {}) => ({
module: {
rules: [
{
test: /\.(png|jpg|svg)$/,
include,
exclude,
use: {
loader: 'url-loader',
options,
},
},
],
},
}); //look into compressing images with image-webpack-loader
exports.loadFonts = ({ include, exclude, options } = {}) => ({
module: {
rules: [
{
// Capture eot, ttf, woff, and woff2
test: /\.(eot|ttf|woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
include,
exclude,
use: {
loader: 'file-loader',
options,
},
},
],
},
});
exports.loadJavascript = ({ include, exclude } = {}) => ({
module: {
rules: [
{
test: /\.jsx?$/,
include,
exclude,
use: 'babel-loader',
},
],
},
});
exports.generateSourceMaps = ({ type }) => ({
devtool: type,
});
exports.extractBundles = bundles => ({
plugins: bundles.map(
bundle => new webpack.optimize.CommonsChunkPlugin(bundle)
),
});
exports.minifyJavascript = () => ({
plugins: [new UglifyWebpackPlugin({
exclude: /node_modules/,
parallel: true,
sourceMap: true,
uglifyOptions: {
ie8: false,
ecma: 8,
compress: {
warnings: false,
drop_console: true,
},
},
})],
});
exports.minifyCSS = ({ options }) => ({
plugins: [
new OptimizeCSSAssetsPlugin({
cssProcessor: cssnano,
cssProcessorOptions: options,
canPrint: false,
}),
],
});
exports.setVariable = (key, value) => {
const env = {};
env[key] = JSON.stringify(value);
return {
plugins: [new webpack.DefinePlugin(env)],
};
};
<file_sep>import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import CreatorCard from '../../components/cards/creatorCard';
Enzyme.configure({ adapter: new Adapter() })
describe('Creator Card', () => {
const props = {
id: 123,
fullName: '<NAME>',
comics: { items: [] },
thumbnail: {
path: 'test',
extension: 'com',
},
history: {
location: { pathname: '/creators/:id'},
push: jest.fn(),
},
saveResource: jest.fn(),
showSaveItemErrorModal: jest.fn(),
isSignedIn: true,
};
it('Should render correctly', () => {
const wrapper = shallow(
<CreatorCard
id={props.id}
fullName={props.fullName}
comics={props.comics}
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
expect(wrapper).toMatchSnapshot();
});
it('Should call save button on click', () => {
const wrapper = shallow(
<CreatorCard
id={props.id}
fullName={props.fullName}
comics={props.comics}
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
wrapper.find(".save-btn").simulate('click');
expect(props.saveResource.mock.calls.length).toBe(1);
expect(props.saveResource.mock.calls[0][0])
.toEqual({
id: 123,
name: '<NAME>',
resourceType: 'creators/:id'
});
});
it('Should call more details button on click', () => {
const wrapper = shallow(
<CreatorCard
id={props.id}
fullName={props.fullName}
comics={props.comics}
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
wrapper.find(".details-btn").simulate('click');
expect(props.saveResource.mock.calls.length).toBe(1);
});
});
<file_sep>import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import CharacterCard from '../../components/cards/characterCard';
Enzyme.configure({ adapter: new Adapter() })
describe('Character Card', () => {
const props = {
id: 123,
name: 'Spiderman',
thumbnail: {
path: 'test',
extension: 'com',
},
history: {
location: { pathname: '/characters/:id'},
push: jest.fn(),
},
saveResource: jest.fn(),
showSaveItemErrorModal: jest.fn(),
isSignedIn: true,
};
it('Should render correctly', () => {
const wrapper = shallow(
<CharacterCard
id={props.id}
name={props.name}
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
expect(wrapper).toMatchSnapshot();
});
it('Should call save button on click', () => {
const wrapper = shallow(
<CharacterCard
id={props.id}
name={props.name}
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
wrapper.find(".save-btn").simulate('click');
expect(props.saveResource.mock.calls.length).toBe(1);
expect(props.saveResource.mock.calls[0][0])
.toEqual({
id: 123,
name: 'Spiderman',
resourceType: 'characters/:id'
});
});
it('Should call more details button on click', () => {
const wrapper = shallow(
<CharacterCard
id={props.id}
name={props.name}
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
wrapper.find(".details-btn").simulate('click');
expect(props.saveResource.mock.calls.length).toBe(1);
});
});
<file_sep>import React from 'react';
export default () => (
<div className="column is-three-fifths is-offset-one-fifth">
<h2 className="is-size-4">No results found</h2>
</div>
);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Immutable from 'immutable';
import { Link } from 'react-router-dom';
import { Field, reduxForm, SubmissionError } from 'redux-form';
import { validateCredentials } from '../../utils/validators';
import renderField from '../forms/renderField';
const SignIn = ({ handleSubmit, display, signIn }) => {
const submit = ({ email, password }) => {
const errors = validateCredentials(email, password);
if (Object.keys(errors).length) {
throw new SubmissionError(errors);
}
signIn();
};
return (
<div className="columns is-centered">
<div className="column is-two-thirds">
<form onSubmit={handleSubmit(submit)}>
<Field
name="email"
type="text"
placeholder="Email"
iconClasses="fa fa-envelope"
component={renderField}
/>
<Field
name="password"
type="<PASSWORD>"
placeholder="<PASSWORD>"
iconClasses="fa fa-lock"
component={renderField}
/>
{ display.get('apiError').message && (
<div className="field">
<div className="message is-danger">
<div className="message-body">
{ display.get('apiError').message }
</div>
</div>
</div>
)}
<div className="field">
<p className="control">
<button className="button is-dark is-medium">
Sign In
</button>
</p>
</div>
<div className="level">
<div className="level-left">
<div className="level-item">
<span>
Don't have an account yet? Click <Link to="register">here</Link> to register!
</span>
</div>
</div>
</div>
</form>
</div>
</div>
);
};
SignIn.propTypes = {
handleSubmit: PropTypes.func.isRequired,
display: PropTypes.instanceOf(Immutable.Map).isRequired,
signIn: PropTypes.func.isRequired,
};
export default reduxForm({
form: 'signIn',
})(SignIn);
<file_sep>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import * as DisplayActions from '../../actions/display';
import * as DisplayConstants from '../../constants/display';
Enzyme.configure({ adapter: new Adapter() });
describe('Display Actions', () => {
it('Should create an action for hiding flash messages', () => {
const expectedAction = {
type: DisplayConstants.HIDE_FLASH_MESSAGE,
};
expect(DisplayActions.hideFlashMessage()).toEqual(expectedAction);
});
it('Should create an action for showing save item error modal', () => {
const expectedAction = {
type: DisplayConstants.SHOW_SAVE_ITEM_ERROR_MODAL,
};
expect(DisplayActions.showSaveItemErrorModal()).toEqual(expectedAction);
});
it('Should create an action for hiding save item error modal', () => {
const expectedAction = {
type: DisplayConstants.HIDE_SAVE_ITEM_ERROR_MODAL,
};
expect(DisplayActions.hideSaveItemErrorModal()).toEqual(expectedAction);
});
});
<file_sep>export const COMICS_FETCH_SUCCEEDED = 'COMICS_FETCH_SUCCEEDED';
export const SELECTED_COMIC_FETCH_SUCCEEDED = 'SELECTED_COMIC_FETCH_SUCCEEDED';
export const GET_COMICS = 'GET_COMICS';
export const GET_SELECTED_COMIC = 'GET_SELECTED_COMIC';
export const SEARCH_COMICS = 'SEARCH_COMICS';
export const SEARCH_COMICS_BY_LETTER = 'SEARCH_COMICS_BY_LETTER';
export const COMICS_SEARCH_SUCCEEDED = 'COMICS_SEARCH_SUCCEEDED';
<file_sep>import { call, put } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import * as Api from '../utils/api';
import { LOADING, FETCH_FAILED } from '../constants/display';
import {
CREATORS_FETCH_SUCCEEDED,
SELECTED_CREATOR_FETCH_SUCCEEDED,
CREATORS_SEARCH_SUCCEEDED,
} from '../constants/creators';
const mockFetchCreatorsApiResponse = jest.fn()
.mockReturnValue({
data: {
data: [{
id: 5,
fullName: '<NAME>',
}],
},
});
export const fetchCreators = function* fetchCreators() {
try {
yield put({ type: LOADING, payload: true });
const creators = yield call(mockFetchCreatorsApiResponse);
yield put({ type: CREATORS_FETCH_SUCCEEDED, creators: creators.data.data });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
export const fetchSelectedCreator = function* fetchSelectedCreator({ id }) {
try {
yield put({ type: LOADING, payload: true });
const creator = yield call(mockFetchCreatorsApiResponse, id);
yield put({ type: SELECTED_CREATOR_FETCH_SUCCEEDED, creator: creator.data.data[0] });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
export const searchCreators = function* searchCreators({ searchTerm }) {
try {
yield call(delay, 500);
yield put({ type: LOADING, payload: true });
const creators = yield call(mockFetchCreatorsApiResponse, searchTerm);
yield put({ type: CREATORS_SEARCH_SUCCEEDED, creators: creators.data.data });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
<file_sep>import { call, put } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import * as Api from '../utils/api';
import { LOADING, FETCH_FAILED } from '../constants/display';
import {
SERIES_FETCH_SUCCEEDED,
SELECTED_SERIES_FETCH_SUCCEEDED,
SERIES_SEARCH_SUCCEEDED,
} from '../constants/series';
const mockFetchSeriesApiResponse = jest.fn()
.mockReturnValue({
data: {
data: [{
id: 5,
title: 'Wolverine',
}],
},
});
export const fetchSeries = function* fetchSeries() {
try {
yield put({ type: LOADING, payload: true });
const series = yield call(mockFetchSeriesApiResponse);
yield put({ type: SERIES_FETCH_SUCCEEDED, series: series.data.data });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
export const fetchSelectedSeries = function* fetchSelectedSeries({ id }) {
try {
yield put({ type: LOADING, payload: true });
const series = yield call(mockFetchSeriesApiResponse, id);
yield put({ type: SELECTED_SERIES_FETCH_SUCCEEDED, series: series.data.data[0] });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
export const searchSeries = function* searchSeries({ searchTerm }) {
try {
yield call(delay, 500);
yield put({ type: LOADING, payload: true });
const series = yield call(mockFetchSeriesApiResponse, searchTerm);
yield put({ type: SERIES_SEARCH_SUCCEEDED, series: series.data.data });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
<file_sep>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { Map } from 'immutable';
import reducer from '../../reducers/characters';
import {
CHARACTERS_FETCH_SUCCEEDED,
SELECTED_CHARACTER_FETCH_SUCCEEDED,
CHARACTERS_SEARCH_SUCCEEDED,
} from '../../constants/characters';
Enzyme.configure({ adapter: new Adapter() });
describe('Characters Reducer', () => {
const initialState = new Map({
characters: [],
selectedCharacter: {},
});
it('Should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(initialState);
});
it('Should handle CHARACTERS_FETCH_SUCCEEDED', () => {
expect(
reducer(new Map(), {
type: CHARACTERS_FETCH_SUCCEEDED,
characters: [
{ id: 1, name: 'spiderman' },
],
}),
).toEqual(new Map({
characters: [
{ id: 1, name: 'spiderman' },
],
}));
});
it('Should handle CHARACTERS_SEARCH_SUCCEEDED', () => {
expect(
reducer(new Map(), {
type: CHARACTERS_SEARCH_SUCCEEDED,
characters: [
{ id: 1, name: 'spiderman' },
],
}),
).toEqual(new Map({
characters: [
{ id: 1, name: 'spiderman' },
],
}));
});
it('Should handle SELECTED_CHARACTER_FETCH_SUCCEEDED', () => {
expect(
reducer(new Map(), {
type: SELECTED_CHARACTER_FETCH_SUCCEEDED,
character: { id: 1, name: 'spiderman' },
}),
).toEqual(new Map({
selectedCharacter: { id: 1, name: 'spiderman' },
}));
});
});
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import SideBar from '../navigation/sidebar';
const Main = ({ children, displayFlashMessage, hideFlashMessage, currentPage }) => {
const flashMessageClasses = displayFlashMessage
? 'message flash-message is-success fadeIn'
: 'message hide-flash-message flash-message is-success';
if (displayFlashMessage) {
setTimeout(() => {
hideFlashMessage();
}, 3000);
}
return (
<div className="section">
<div className="container">
<div className="columns">
<SideBar currentPage={currentPage} />
<div className="column is-three-quarters">
{ children }
</div>
</div>
</div>
<article className={flashMessageClasses}>
<div className="message-body">
Item successfully added.
</div>
</article>
</div>
);
};
Main.propTypes = {
children: PropTypes.element.isRequired,
displayFlashMessage: PropTypes.bool.isRequired,
hideFlashMessage: PropTypes.func.isRequired,
currentPage: PropTypes.string.isRequired,
};
export default Main;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import LoadWithInfiniteScroll from '../../containers/loadWithInfiniteScroll';
import EventCard from '../cards/eventCard';
const EventList = ({ history, saveResource, showSaveItemErrorModal, data, isSignedIn }) => (
<div className="columns is-multiline">
{ data.map(item => (
<EventCard
{...item}
history={history}
saveResource={saveResource}
showSaveItemErrorModal={showSaveItemErrorModal}
isSignedIn={isSignedIn}
key={item.id}
/>
)) }
</div>
);
EventList.propTypes = {
history: PropTypes.object.isRequired,
saveResource: PropTypes.func.isRequired,
showSaveItemErrorModal: PropTypes.func.isRequired,
data: PropTypes.array.isRequired,
isSignedIn: PropTypes.bool.isRequired,
};
export default LoadWithInfiniteScroll(EventList);
<file_sep>import React, { Component } from 'react';
import { Route, Switch, Redirect, withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Modal from 'react-modal';
import Immutable from 'immutable';
import Nav from '../components/navigation/nav';
import Main from '../components/main';
import SignIn from '../components/forms/signIn';
import Register from '../components/forms/register';
import RegistrationSuccessful from '../components/misc/registrationSuccessful';
import CustomerProfile from '../components/profile';
import CharacterList from '../components/list/characterList';
import ComicList from '../components/list/comicList';
import CreatorList from '../components/list/creatorList';
import EventList from '../components/list/eventList';
import SeriesList from '../components/list/seriesList';
import SelectedCharacter from '../components/details/selectedCharacter';
import SelectedComic from '../components/details/selectedComic';
import SelectedCreator from '../components/details/selectedCreator';
import SelectedEvent from '../components/details/selectedEvent';
import SelectedSeries from '../components/details/selectedSeries';
import SaveItemErrorModal from '../components/modals/saveItemError';
import ServerErrorModal from '../components/modals/serverError';
import Search from '../components/search';
import PaginationBar from '../components/navigation/paginationBar';
import * as DisplayActions from '../actions/display';
import * as ApiActions from '../actions/api';
class App extends Component {
componentDidMount() {
Modal.setAppElement('body');
}
componentWillReceiveProps(nextProps) {
const { location, clearApiErrors } = this.props;
if (location.pathname !== nextProps.location.pathname) {
clearApiErrors();
}
}
componentDidCatch(error, info) {
const { setApplicationError } = this.props;
setApplicationError({
error: error.message,
info: info.componentStack,
});
}
render() {
const {
getCharacters,
getComics,
getCreators,
getEvents,
getSeries,
getUser,
logout,
getSelectedCharacter,
getSelectedComic,
getSelectedCreator,
getSelectedEvent,
getSelectedSeries,
searchCharacters,
searchComics,
searchCreators,
searchEvents,
searchSeries,
searchCharactersByLetter,
searchComicsByLetter,
searchCreatorsByLetter,
searchEventsByLetter,
searchSeriesByLetter,
saveResource,
characters,
comics,
creators,
events,
series,
user,
display,
history,
signIn,
register,
hideFlashMessage,
hideSaveItemErrorModal,
hideServerErrorModal,
showSaveItemErrorModal,
clearApiData,
clearSearchTerm,
clearLetter,
} = this.props;
return (
<div>
<Nav
history={history}
user={user}
logout={logout}
/>
<Main
displayFlashMessage={display.get('displayFlashMessage')}
hideFlashMessage={hideFlashMessage}
currentPage={location.pathname}
>
<Switch>
<Route
path="/sign-in"
render={() => (
<SignIn
signIn={signIn}
display={display}
isLoading={display.get('loading')}
/>
)}
/>
<Route
path="/register"
render={() => (
<Register
register={register}
display={display}
isLoading={display.get('loading')}
history={history}
/>
)}
/>
<Route
path="/profile"
render={() => (
<CustomerProfile
data={user.get('user')}
getUser={getUser}
isLoading={display.get('loading')}
history={history}
/>
)}
/>
<Route
path="/registration-successful"
render={() => (
<RegistrationSuccessful
user={user}
/>
)}
/>
<Route
path="/characters"
exact
render={() => (
<div>
<Search
placeholder="Search characters"
searchFunc={searchCharacters}
display={display}
/>
<PaginationBar
setPaginationAndSearch={searchCharactersByLetter}
display={display}
/>
<CharacterList
data={characters.get('characters')}
apiCall={getCharacters}
getUser={getUser}
searchCharacters={searchCharacters}
isLoading={display.get('loading')}
history={history}
saveResource={saveResource}
showSaveItemErrorModal={showSaveItemErrorModal}
isSignedIn={user.get('signedIn')}
display={display}
clearApiData={clearApiData}
clearSearchTerm={clearSearchTerm}
clearLetter={clearLetter}
/>
</div>
)}
/>
<Route
path="/characters/:id"
render={props => (
<SelectedCharacter
data={characters.get('selectedCharacter')}
apiCall={getSelectedCharacter}
getUser={getUser}
match={props.match}
isLoading={display.get('loading')}
isSignedIn={user.get('signedIn')}
/>
)}
/>
<Route
path="/comics"
exact
render={() => (
<div>
<Search
placeholder="Search comics"
searchFunc={searchComics}
display={display}
/>
<PaginationBar
setPaginationAndSearch={searchComicsByLetter}
display={display}
/>
<ComicList
data={comics.get('comics')}
apiCall={getComics}
getUser={getUser}
isLoading={display.get('loading')}
history={history}
saveResource={saveResource}
showSaveItemErrorModal={showSaveItemErrorModal}
isSignedIn={user.get('signedIn')}
display={display}
clearApiData={clearApiData}
clearSearchTerm={clearSearchTerm}
clearLetter={clearLetter}
/>
</div>
)}
/>
<Route
path="/comics/:id"
render={props => (
<SelectedComic
data={comics.get('selectedComic')}
apiCall={getSelectedComic}
getUser={getUser}
match={props.match}
isLoading={display.get('loading')}
isSignedIn={user.get('signedIn')}
/>
)}
/>
<Route
path="/creators"
exact
render={() => (
<div>
<Search
placeholder="Search creators"
searchFunc={searchCreators}
display={display}
/>
<PaginationBar
setPaginationAndSearch={searchCreatorsByLetter}
display={display}
/>
<CreatorList
data={creators.get('creators')}
apiCall={getCreators}
getUser={getUser}
isLoading={display.get('loading')}
history={history}
saveResource={saveResource}
showSaveItemErrorModal={showSaveItemErrorModal}
isSignedIn={user.get('signedIn')}
display={display}
clearApiData={clearApiData}
clearSearchTerm={clearSearchTerm}
clearLetter={clearLetter}
/>
</div>
)}
/>
<Route
path="/creators/:id"
render={props => (
<SelectedCreator
data={creators.get('selectedCreator')}
apiCall={getSelectedCreator}
getUser={getUser}
match={props.match}
isLoading={display.get('loading')}
isSignedIn={user.get('signedIn')}
/>
)}
/>
<Route
path="/events"
exact
render={() => (
<div>
<Search
placeholder="Search events"
searchFunc={searchEvents}
display={display}
/>
<PaginationBar
setPaginationAndSearch={searchEventsByLetter}
display={display}
/>
<EventList
data={events.get('events')}
apiCall={getEvents}
getUser={getUser}
isLoading={display.get('loading')}
history={history}
saveResource={saveResource}
showSaveItemErrorModal={showSaveItemErrorModal}
isSignedIn={user.get('signedIn')}
display={display}
clearApiData={clearApiData}
clearSearchTerm={clearSearchTerm}
clearLetter={clearLetter}
/>
</div>
)}
/>
<Route
path="/events/:id"
render={props => (
<SelectedEvent
data={events.get('selectedEvent')}
apiCall={getSelectedEvent}
getUser={getUser}
match={props.match}
isLoading={display.get('loading')}
isSignedIn={user.get('signedIn')}
/>
)}
/>
<Route
path="/series"
exact
render={() => (
<div>
<Search
placeholder="Search series"
searchFunc={searchSeries}
display={display}
/>
<PaginationBar
setPaginationAndSearch={searchSeriesByLetter}
display={display}
/>
<SeriesList
data={series.get('series')}
apiCall={getSeries}
getUser={getUser}
isLoading={display.get('loading')}
history={history}
saveResource={saveResource}
showSaveItemErrorModal={showSaveItemErrorModal}
isSignedIn={user.get('signedIn')}
display={display}
clearApiData={clearApiData}
clearSearchTerm={clearSearchTerm}
clearLetter={clearLetter}
/>
</div>
)}
/>
<Route
path="/series/:id"
exact
render={props => (
<SelectedSeries
data={series.get('selectedSeries')}
apiCall={getSelectedSeries}
getUser={getUser}
match={props.match}
isLoading={display.get('loading')}
isSignedIn={user.get('signedIn')}
/>
)}
/>
<Redirect from="/" to="/characters" />
<Redirect to="/" />
</Switch>
</Main>
<SaveItemErrorModal
isOpen={display.get('showSaveItemErrorModal')}
hideSaveItemErrorModal={hideSaveItemErrorModal}
/>
<ServerErrorModal
isOpen={display.get('apiError')}
hideServerErrorModal={hideServerErrorModal}
/>
</div>
);
}
}
App.propTypes = {
getCharacters: PropTypes.func.isRequired,
getComics: PropTypes.func.isRequired,
getCreators: PropTypes.func.isRequired,
getEvents: PropTypes.func.isRequired,
getSeries: PropTypes.func.isRequired,
getUser: PropTypes.func.isRequired,
logout: PropTypes.func.isRequired,
getSelectedCharacter: PropTypes.func.isRequired,
getSelectedComic: PropTypes.func.isRequired,
getSelectedCreator: PropTypes.func.isRequired,
getSelectedEvent: PropTypes.func.isRequired,
getSelectedSeries: PropTypes.func.isRequired,
saveResource: PropTypes.func.isRequired,
searchCharacters: PropTypes.func.isRequired,
searchComics: PropTypes.func.isRequired,
searchCreators: PropTypes.func.isRequired,
searchEvents: PropTypes.func.isRequired,
searchSeries: PropTypes.func.isRequired,
characters: PropTypes.instanceOf(Immutable.Map).isRequired,
comics: PropTypes.instanceOf(Immutable.Map).isRequired,
creators: PropTypes.instanceOf(Immutable.Map).isRequired,
events: PropTypes.instanceOf(Immutable.Map).isRequired,
user: PropTypes.instanceOf(Immutable.Map).isRequired,
display: PropTypes.instanceOf(Immutable.Map).isRequired,
series: PropTypes.instanceOf(Immutable.Map).isRequired,
history: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
setApplicationError: PropTypes.func.isRequired,
signIn: PropTypes.func.isRequired,
register: PropTypes.func.isRequired,
clearApiErrors: PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
characters: state.characters,
comics: state.comics,
creators: state.creators,
events: state.events,
display: state.display,
user: state.user,
series: state.series,
});
const mapDispatchToProps = dispatch => ({
...bindActionCreators(ApiActions, dispatch),
...bindActionCreators(DisplayActions, dispatch),
});
export default withRouter(
connect(
mapStateToProps,
mapDispatchToProps,
)(App)
);
<file_sep>import { call, put, takeEvery, select } from 'redux-saga/effects';
import * as Api from '../utils/api';
import history from '../utils/history';
import { LOADING, FETCH_FAILED, SHOW_FLASH_MESSAGE } from '../constants/display';
import {
REGISTRATION_ATTEMPT,
GET_USER,
REGISTRATION_SUCCEEDED,
USER_FETCH_SUCCEEDED,
SAVE_RESOURCE,
SAVE_RESOURCE_SUCCEEDED,
} from '../constants/user';
function* registerUser() {
try {
yield put({ type: LOADING, payload: true });
const payload = yield select(state => ({
name: state.form.register.values.name,
email: state.form.register.values.email,
password: <PASSWORD>,
age: state.form.register.values.age,
gender: state.form.register.values.gender,
}));
const user = yield call(Api.register, payload);
yield put({ type: REGISTRATION_SUCCEEDED, user: user.data });
yield put({ type: LOADING, payload: false });
yield call(history.push, '/registration-successful');
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* getUser() {
try {
yield put({ type: LOADING, payload: true });
const user = yield call(Api.fetchUser);
yield put({ type: USER_FETCH_SUCCEEDED, user: user.data });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* saveResource({ payload }) {
try {
yield put({ type: LOADING, payload: true });
yield call(Api.saveResource, { ...payload });
yield put({ type: SAVE_RESOURCE_SUCCEEDED });
yield put({ type: SHOW_FLASH_MESSAGE });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* userActions() {
yield takeEvery(REGISTRATION_ATTEMPT, registerUser);
yield takeEvery(GET_USER, getUser);
yield takeEvery(SAVE_RESOURCE, saveResource);
}
export default userActions;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Modal from 'react-modal';
const ServerErrorModal = ({ isOpen, hideServerErrorModal }) => (
<Modal
isOpen={isOpen}
style={{
content: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
height: '25vh',
margin: '0 auto',
textAlign: 'center',
},
}}
>
<span className="close-thin" role="button" onClick={hideServerErrorModal} />
<h1 className="is-size-4 mar-t-2">Sorry!</h1>
<div>
<p>
There seems to be an issue connecting to the server. Please try again later.
</p>
</div>
</Modal>
);
ServerErrorModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
hideServerErrorModal: PropTypes.func.isRequired,
};
export default ServerErrorModal;
<file_sep>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { call, takeEvery } from 'redux-saga/effects';
import { runSaga } from 'redux-saga';
import {
fetchSeries,
fetchSelectedSeries,
searchSeries,
} from '../../__mocks__/series';
Enzyme.configure({ adapter: new Adapter() });
describe('Series Sagas', () => {
it('Should test fetch series saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, fetchSeries).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'SERIES_FETCH_SUCCEEDED',
series: [{
id: 5,
title: 'Wolverine',
}]
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
it('Should test fetch selected series saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, fetchSelectedSeries, 123).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'SELECTED_SERIES_FETCH_SUCCEEDED',
series: {
id: 5,
title: 'Wolverine',
}
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
it('Should test search series saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, searchSeries, 123).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'SERIES_SEARCH_SUCCEEDED',
series: [{
id: 5,
title: 'Wolverine',
}]
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
});
<file_sep>import createBrowserHistory from 'history/createBrowserHistory';
// NOTE: Discussed in issue 3972 on GitHub.
// Must export shared instance of browser history to use directly with Redux Saga.
export default createBrowserHistory();
<file_sep>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import * as ApiActions from '../../actions/api';
import * as CharacterConstants from '../../constants/characters';
import * as ComicConstants from '../../constants/comics';
import * as CreatorConstants from '../../constants/creators';
import * as EventConstants from '../../constants/events';
import * as SeriesConstants from '../../constants/series';
import * as UserConstants from '../../constants/user';
import * as AuthConstants from '../../constants/auth';
import * as DisplayConstants from '../../constants/display';
Enzyme.configure({ adapter: new Adapter() });
describe('API Actions', () => {
const id = 123;
const payload = {
id: 123,
name: 'spiderman',
resourceType: 'character',
};
const mockEvent = {
target: {
value: 'test',
},
};
it('Should create an action to get characters', () => {
const expectedAction = {
type: CharacterConstants.GET_CHARACTERS,
};
expect(ApiActions.getCharacters()).toEqual(expectedAction);
});
it('Should create an action to get comics', () => {
const expectedAction = {
type: ComicConstants.GET_COMICS,
};
expect(ApiActions.getComics()).toEqual(expectedAction);
});
it('Should create an action to get creators', () => {
const expectedAction = {
type: CreatorConstants.GET_CREATORS,
};
expect(ApiActions.getCreators()).toEqual(expectedAction);
});
it('Should create an action to get events', () => {
const expectedAction = {
type: EventConstants.GET_EVENTS,
};
expect(ApiActions.getEvents()).toEqual(expectedAction);
});
it('Should create an action to get series', () => {
const expectedAction = {
type: SeriesConstants.GET_SERIES,
};
expect(ApiActions.getSeries()).toEqual(expectedAction);
});
it('Should create an action to get user', () => {
const expectedAction = {
type: UserConstants.GET_USER,
};
expect(ApiActions.getUser()).toEqual(expectedAction);
});
it('Should create an action to selected character', () => {
const expectedAction = {
type: CharacterConstants.GET_SELECTED_CHARACTER,
id,
};
expect(ApiActions.getSelectedCharacter(id)).toEqual(expectedAction);
});
it('Should create an action to get selected comic', () => {
const expectedAction = {
type: ComicConstants.GET_SELECTED_COMIC,
id,
};
expect(ApiActions.getSelectedComic(id)).toEqual(expectedAction);
});
it('Should create an action to get selected creator', () => {
const expectedAction = {
type: CreatorConstants.GET_SELECTED_CREATOR,
id,
};
expect(ApiActions.getSelectedCreator(id)).toEqual(expectedAction);
});
it('Should create an action to get selected event', () => {
const expectedAction = {
type: EventConstants.GET_SELECTED_EVENT,
id,
};
expect(ApiActions.getSelectedEvent(id)).toEqual(expectedAction);
});
it('Should create an action to get selected series', () => {
const expectedAction = {
type: SeriesConstants.GET_SELECTED_SERIES,
id,
};
expect(ApiActions.getSelectedSeries(id)).toEqual(expectedAction);
});
it('Should create an action to save resource', () => {
const expectedAction = {
type: UserConstants.SAVE_RESOURCE,
payload,
};
expect(ApiActions.saveResource(payload)).toEqual(expectedAction);
});
it('Should create an action to sign in user', () => {
const expectedAction = {
type: AuthConstants.SIGN_IN_ATTEMPT,
};
expect(ApiActions.signIn()).toEqual(expectedAction);
});
it('Should create an action to register user', () => {
const expectedAction = {
type: UserConstants.REGISTRATION_ATTEMPT,
};
expect(ApiActions.register()).toEqual(expectedAction);
});
it('Should create an action to logout', () => {
const expectedAction = {
type: AuthConstants.LOGOUT,
};
expect(ApiActions.logout()).toEqual(expectedAction);
});
it('Should create an action to set application error', () => {
const expectedAction = {
type: DisplayConstants.SET_APPLICATION_ERROR,
error: {
err: 'sample error',
stack: 'sample stack',
},
};
expect(ApiActions.setApplicationError({
err: 'sample error',
stack: 'sample stack',
})).toEqual(expectedAction);
});
it('Should create an action to clear api errors', () => {
const expectedAction = {
type: DisplayConstants.CLEAR_API_ERRORS,
};
expect(ApiActions.clearApiErrors()).toEqual(expectedAction);
});
it('Should create an action to search characters', () => {
const expectedAction = {
type: CharacterConstants.SEARCH_CHARACTERS,
searchTerm: 'test',
};
expect(ApiActions.searchCharacters(mockEvent)).toEqual(expectedAction);
});
it('Should create an action to search comics', () => {
const expectedAction = {
type: ComicConstants.SEARCH_COMICS,
searchTerm: 'test',
};
expect(ApiActions.searchComics(mockEvent)).toEqual(expectedAction);
});
it('Should create an action to search creators', () => {
const expectedAction = {
type: CreatorConstants.SEARCH_CREATORS,
searchTerm: 'test',
};
expect(ApiActions.searchCreators(mockEvent)).toEqual(expectedAction);
});
it('Should create an action to search events', () => {
const expectedAction = {
type: EventConstants.SEARCH_EVENTS,
searchTerm: 'test',
};
expect(ApiActions.searchEvents(mockEvent)).toEqual(expectedAction);
});
it('Should create an action to search series', () => {
const expectedAction = {
type: SeriesConstants.SEARCH_SERIES,
searchTerm: 'test',
};
expect(ApiActions.searchSeries(mockEvent)).toEqual(expectedAction);
});
});
<file_sep>export const SIGN_IN_ATTEMPT = 'SIGN_IN_ATTEMPT';
export const SIGN_IN_SUCCEEDED = 'SIGN_IN_SUCCEEDED';
export const LOGOUT = 'LOGOUT';
export const LOGOUT_SUCCEEDED = 'LOGOUT_USER_SUCCEEDED';
<file_sep>import { Map } from 'immutable';
import { SIGN_IN_SUCCEEDED, LOGOUT_SUCCEEDED } from '../constants/auth';
import { REGISTRATION_SUCCEEDED, USER_FETCH_SUCCEEDED } from '../constants/user';
const initialState = new Map({
user: {},
signedIn: false,
});
export default (state = initialState, action) => {
switch (action.type) {
case SIGN_IN_SUCCEEDED:
return state
.set('user', action.user)
.set('signedIn', true);
case REGISTRATION_SUCCEEDED:
return state.set('user', action.user);
case USER_FETCH_SUCCEEDED:
return state
.set('user', action.user)
.set('signedIn', true);
case LOGOUT_SUCCEEDED:
return initialState;
default:
return state;
}
};
<file_sep>import React, { Component } from 'react';
import LoadingSpinner from '../components/misc/loadingSpinner';
const InfiniteScrollHOC = WrappedComponent => (
class InfiniteScroll extends Component {
state = { itemsLoaded: 0 }
componentDidMount() {
window.addEventListener('scroll', this.scrollToBottom, false);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.scrollToBottom, false);
}
componentWillReceiveProps(nextProps) {
if (this.props.display.get('total') !== nextProps.display.get('total')) {
this.setState({ itemsLoaded: 0 });
}
}
makeApiCall = (apiCall, display, itemsLoaded) => {
let searchTerm = '';
if (display.get('searchTerm')) {
searchTerm = display.get('searchTerm')
}
if (display.get('letter')) {
searchTerm = display.get('letter');
}
apiCall(itemsLoaded, searchTerm);
}
scrollToBottom = () => {
const { display, apiCall } = this.props;
if ((document.body.scrollHeight - window.innerHeight) === window.pageYOffset) {
const additionalResultsAvailable = display.get('count') < (display.get('total') - this.state.itemsLoaded)
if (additionalResultsAvailable && !display.get('loading')) {
this.setState({
itemsLoaded: this.state.itemsLoaded + display.get('count'),
});
this.makeApiCall(apiCall, display, this.state.itemsLoaded);
}
}
}
render() {
return (
<div>
<div>{ this.props.display.get('loading') && <LoadingSpinner /> }</div>
<WrappedComponent {...this.props} />
</div>
)
}
}
);
export default InfiniteScrollHOC;
<file_sep>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { call, takeEvery } from 'redux-saga/effects';
import { runSaga } from 'redux-saga';
import {
fetchComics,
fetchSelectedComic,
searchComics,
} from '../../__mocks__/comics';
Enzyme.configure({ adapter: new Adapter() });
describe('Comics Sagas', () => {
it('Should test fetch comics saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, fetchComics).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'COMICS_FETCH_SUCCEEDED',
comics: [{
title: 'Spiderman',
issueNumber: 5,
}]
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
it('Should test fetch selected character saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, fetchSelectedComic, 123).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'SELECTED_COMIC_FETCH_SUCCEEDED',
comic: {
title: 'Spiderman',
issueNumber: 5,
}
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
it('Should test search characters saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, searchComics, 123).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'COMICS_SEARCH_SUCCEEDED',
comics: [{
title: 'Spiderman',
issueNumber: 5,
}]
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
});
<file_sep>export const CREATORS_FETCH_SUCCEEDED = 'CREATORS_FETCH_SUCCEEDED';
export const SELECTED_CREATOR_FETCH_SUCCEEDED = 'SELECTED_CREATOR_FETCH_SUCCEEDED';
export const GET_CREATORS = 'GET_CREATORS';
export const GET_SELECTED_CREATOR = 'GET_SELECTED_CREATOR';
export const SEARCH_CREATORS = 'SEARCH_CREATORS';
export const SEARCH_CREATORS_BY_LETTER = 'SEARCH_CREATORS_BY_LETTER';
export const CREATORS_SEARCH_SUCCEEDED = 'CREATORS_SEARCH_SUCCEEDED';
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
const CreatorItem = ({ name, resourceURI }) => {
const creatorId = resourceURI.slice(resourceURI.lastIndexOf('/') + 1);
return (
<div className="level">
<div className="level-left">
<div className="level-item center-mobile">{ name }</div>
<small className="level-item">
<Link to={`/creators/${creatorId}`}>Details</Link>
</small>
</div>
</div>
);
};
CreatorItem.propTypes = {
name: PropTypes.string.isRequired,
resourceURI: PropTypes.string.isRequired,
};
export default CreatorItem;
<file_sep>import React from 'react';
import Modal from 'react-modal';
import PropTypes from 'prop-types';
import history from '../../utils/history';
const SaveItemErrorModal = ({ isOpen, hideSaveItemErrorModal }) => {
const redirectToRegistrationPage = () => {
history.push('/register');
hideSaveItemErrorModal();
};
return (
<Modal
isOpen={isOpen}
style={{
content: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
height: '25vh',
margin: '0 auto',
textAlign: 'center',
},
}}
>
<span className="close-thin" role="button" onClick={hideSaveItemErrorModal} />
<h1 className="is-size-4 mar-t-2">Sorry!</h1>
<div>
<p>
You must be logged in to use this feature. Don't have an account yet?
<a role="button" onClick={redirectToRegistrationPage}> Click here to register. </a>
</p>
</div>
</Modal>
);
};
SaveItemErrorModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
hideSaveItemErrorModal: PropTypes.func.isRequired,
};
export default SaveItemErrorModal;
<file_sep>import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import SeriesCard from '../../components/cards/seriesCard';
Enzyme.configure({ adapter: new Adapter() })
describe('Series Card', () => {
const props = {
id: 123,
title: 'Spiderman',
description: 'Spider-Man is a fictional superhero by Marvel Comics',
thumbnail: {
path: 'test',
extension: 'com',
},
history: {
location: { pathname: '/events/:id'},
push: jest.fn(),
},
saveResource: jest.fn(),
showSaveItemErrorModal: jest.fn(),
isSignedIn: true,
};
it('Should render correctly', () => {
const wrapper = shallow(
<SeriesCard
id={props.id}
title={props.title}
description='Spider-Man is a fictional superhero by Marvel Comics'
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
expect(wrapper).toMatchSnapshot();
});
it('Should call save button on click', () => {
const wrapper = shallow(
<SeriesCard
id={props.id}
title={props.title}
description='Spider-Man is a fictional superhero by Marvel Comics'
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
wrapper.find(".save-btn").simulate('click');
expect(props.saveResource.mock.calls.length).toBe(1);
expect(props.saveResource.mock.calls[0][0])
.toEqual({
id: 123,
name: 'Spiderman',
resourceType: 'events/:id'
});
});
it('Should call more details button on click', () => {
const wrapper = shallow(
<SeriesCard
id={props.id}
title={props.title}
description='Spider-Man is a fictional superhero by Marvel Comics'
thumbnail={props.thumbnail}
history={props.history}
saveResource={props.saveResource}
showSaveItemErrorModal={props.showSaveItemErrorModal}
isSignedIn={props.isSignedIn}
/>,
);
wrapper.find(".details-btn").simulate('click');
expect(props.saveResource.mock.calls.length).toBe(1);
});
});
<file_sep>import { Map } from 'immutable';
import { CLEAR_API_DATA } from '../constants/display';
import {
CHARACTERS_FETCH_SUCCEEDED,
SELECTED_CHARACTER_FETCH_SUCCEEDED,
CHARACTERS_SEARCH_SUCCEEDED,
} from '../constants/characters';
const initialState = new Map({
characters: [],
selectedCharacter: {},
});
export default (state = initialState, action) => {
switch (action.type) {
case CHARACTERS_FETCH_SUCCEEDED:
return state.set('characters', state.get('characters').concat(action.characters));
case CHARACTERS_SEARCH_SUCCEEDED:
return state.set('characters', action.characters);
case SELECTED_CHARACTER_FETCH_SUCCEEDED:
return state.set('selectedCharacter', action.character);
case CLEAR_API_DATA:
return state
.set('characters', initialState.get('characters'))
.set('selectedCharacter', initialState.get('selectedCharacter'));
default:
return state;
}
};
<file_sep>export const REGISTRATION_ATTEMPT = 'REGISTRATION_ATTEMPT';
export const REGISTRATION_SUCCEEDED = 'REGISTRATION_SUCCEEDED';
export const GET_USER = 'GET USER';
export const USER_FETCH_SUCCEEDED = 'USER_FETCH_SUCCEEDED';
export const SAVE_RESOURCE = 'SAVE_RESOURCE';
export const SAVE_RESOURCE_SUCCEEDED = 'SAVE_RESOURCE_SUCCEEDED';
<file_sep>import { call, put, takeEvery, takeLatest } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import * as Api from '../utils/api';
import {
LOADING,
FETCH_FAILED,
SET_SEARCH_TERM,
CLEAR_SEARCH_TERM,
SET_PAGINATION_DATA,
SET_LETTER,
CLEAR_LETTER,
} from '../constants/display';
import {
COMICS_FETCH_SUCCEEDED,
SELECTED_COMIC_FETCH_SUCCEEDED,
GET_COMICS,
GET_SELECTED_COMIC,
SEARCH_COMICS,
COMICS_SEARCH_SUCCEEDED,
SEARCH_COMICS_BY_LETTER,
} from '../constants/comics';
function* fetchComics({ offset, searchTerm }) {
try {
yield put({ type: LOADING, payload: true });
const comics = yield call(Api.fetchComics, offset, searchTerm);
const { data, total, count } = comics.data;
yield put({ type: COMICS_FETCH_SUCCEEDED, comics: data });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* fetchSelectedComic({ id }) {
try {
yield put({ type: LOADING, payload: true });
const comic = yield call(Api.fetchSelectedComic(id));
yield put({ type: SELECTED_COMIC_FETCH_SUCCEEDED, comic: comic.data.data[0] });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* searchComics({ searchTerm }) {
try {
yield put({ type: SET_SEARCH_TERM, payload: searchTerm });
yield put({ type: CLEAR_LETTER });
yield call(delay, 500);
yield put({ type: LOADING, payload: true });
const comics = yield call(Api.searchComics, searchTerm);
const { data, total, count } = comics.data;
yield put({ type: COMICS_SEARCH_SUCCEEDED, comics: data });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* searchComicsByLetter({ searchTerm }) {
try {
yield put({ type: SET_LETTER, letter: searchTerm });
yield put({ type: CLEAR_SEARCH_TERM });
yield put({ type: LOADING, payload: true });
const comics = yield call(Api.searchComics, searchTerm);
const { data, total, count } = comics.data;
yield put({ type: COMICS_SEARCH_SUCCEEDED, comics: data });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* getComics() {
yield takeEvery(GET_COMICS, fetchComics);
yield takeEvery(GET_SELECTED_COMIC, fetchSelectedComic);
yield takeLatest(SEARCH_COMICS, searchComics);
yield takeLatest(SEARCH_COMICS_BY_LETTER, searchComicsByLetter);
}
export default getComics;
<file_sep>import { createStore, applyMiddleware, compose } from 'redux';
import { createLogger } from 'redux-logger';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './rootReducer';
import rootSaga from './sagas';
const sagaMiddleware = createSagaMiddleware();
const middleWare = process.env.NODE_ENV === 'production' ? [sagaMiddleware] : [sagaMiddleware, createLogger()];
const store = createStore(
rootReducer,
compose(
applyMiddleware(...middleWare),
(typeof window.devToolsExtension === 'function') ? window.devToolsExtension() : f => f,
),
);
sagaMiddleware.run(rootSaga);
export default store;
<file_sep>import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import DetailListWrapper from '../../components/details/detailListWrapper';
Enzyme.configure({ adapter: new Adapter() })
describe('Detail List Wrapper', () => {
it('Should render correctly', () => {
const wrapper = shallow(
<DetailListWrapper heading="Spiderman">
<div>Hello world!</div>
</DetailListWrapper>,
);
expect(wrapper).toMatchSnapshot();
});
});
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
const DetailListWrapper = ({ heading, children }) => (
<article className="media">
<div className="media-content">
<div className="content">
<div>
<strong>{ heading }</strong>
<br />
{ children }
</div>
</div>
</div>
</article>
);
DetailListWrapper.propTypes = {
heading: PropTypes.string.isRequired,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.element),
PropTypes.element,
]).isRequired,
};
export default DetailListWrapper;
<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import LoadingHOC from '../../containers/loadingHOC';
const CustomerProfile = ({ data: { name, email, gender, age, savedData } }) => {
const savedCharacters = savedData.characters && savedData.characters.map(({ id, name }) => (
<div className="flex-center">
<div className="r-mar">{ name }</div>
<small style={{ display: 'block' }}>
<Link to={`/characters/${id}`}>Details</Link>
</small>
</div>
));
const savedComics = savedData.comics && savedData.comics.map(({ id, name }) => (
<div className="flex-center">
<div className="r-mar">{ name }</div>
<small style={{ display: 'block' }}>
<Link to={`/comics/${id}`}>Details</Link>
</small>
</div>
));
const savedCreators = savedData.creators && savedData.creators.map(({ id, name }) => (
<div className="flex-center">
<div className="r-mar">{ name }</div>
<small style={{ display: 'block' }}>
<Link to={`/creators/${id}`}>Details</Link>
</small>
</div>
));
const savedEvents = savedData.events && savedData.events.map(({ id, name }) => (
<div className="flex-center">
<div className="r-mar">{ name }</div>
<small style={{ display: 'block' }}>
<Link to={`/events/${id}`}>Details</Link>
</small>
</div>
));
const savedSeries = savedData.series && savedData.series.map(({ id, name }) => (
<div className="flex-center">
<div className="r-mar">{ name }</div>
<small style={{ display: 'block' }}>
<Link to={`/series/${id}`}>Details</Link>
</small>
</div>
));
return (
<div className="Profile">
<h1 className="has-text-centered is-size-3">My Profile</h1>
<div className="has-text-centered main-profile-content">
<i className="fa fa-user-circle fa-5x" aria-hidden="true" />
<div>
<span><em>Username:</em></span>
<span>{ name }</span>
</div>
<div>
<span><em>Email:</em></span>
<span>{ email }</span>
</div>
<div>
<span><em>Gender:</em></span>
<span>{ gender }</span>
</div>
<div>
<span><em>Age:</em></span>
<span>{ age }</span>
</div>
</div>
<article className="media">
<div className="media-content">
<div className="content">
<div>
<br />
{ savedCharacters && savedCharacters.length > 0 && (
<div className="saved-content">
<h5 className="has-text-centered"><em>Saved Characters</em></h5>
{ savedCharacters }
</div>
)}
{ savedComics && savedComics.length > 0 && (
<div className="saved-content">
<h5 className="has-text-centered"><em>Saved Comics</em></h5>
{ savedComics }
</div>
)}
{ savedCreators && savedCreators.length > 0 && (
<div className="saved-content">
<h5 className="has-text-centered"><em>Saved Creators</em></h5>
{ savedCreators }
</div>
)}
{ savedEvents && savedEvents.length > 0 && (
<div className="saved-content">
<h5 className="has-text-centered"><em>Saved Events</em></h5>
{ savedEvents }
</div>
)}
{ savedSeries && savedSeries.length > 0 && (
<div className="saved-content">
<h5 className="has-text-centered"><em>Saved Series</em></h5>
{ savedSeries }
</div>
)}
</div>
</div>
</div>
</article>
</div>
);
};
CustomerProfile.propTypes = {
data: PropTypes.shape({
name: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
gender: PropTypes.arrayOf(PropTypes.object).isRequired,
age: PropTypes.arrayOf(PropTypes.object).isRequired,
savedData: PropTypes.arrayOf(PropTypes.object),
}).isRequired,
};
export default LoadingHOC(CustomerProfile);
<file_sep>import { call, put, takeEvery, takeLatest } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import * as Api from '../utils/api';
import {
LOADING,
FETCH_FAILED,
SET_SEARCH_TERM,
CLEAR_SEARCH_TERM,
SET_PAGINATION_DATA,
SET_LETTER,
CLEAR_LETTER,
} from '../constants/display';
import {
CHARACTERS_FETCH_SUCCEEDED,
SELECTED_CHARACTER_FETCH_SUCCEEDED,
GET_CHARACTERS,
GET_SELECTED_CHARACTER,
SEARCH_CHARACTERS,
CHARACTERS_SEARCH_SUCCEEDED,
SEARCH_CHARACTERS_BY_LETTER,
} from '../constants/characters';
function* fetchCharacters({ offset, searchTerm }) {
try {
yield put({ type: LOADING, payload: true });
const characters = yield call(Api.fetchCharacters, offset, searchTerm);
const { data, total, count } = characters.data;
yield put({ type: CHARACTERS_FETCH_SUCCEEDED, characters: data });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* fetchSelectedCharacter({ id }) {
try {
yield put({ type: LOADING, payload: true });
const character = yield call(Api.fetchSelectedCharacter(id));
yield put({ type: SELECTED_CHARACTER_FETCH_SUCCEEDED, character: character.data.data[0] });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* searchCharacters({ searchTerm }) {
try {
yield put({ type: SET_SEARCH_TERM, payload: searchTerm });
yield put({ type: CLEAR_LETTER });
yield call(delay, 500);
yield put({ type: LOADING, payload: true });
const characters = yield call(Api.searchCharacters, searchTerm);
const { data, total, count } = characters.data;
yield put({ type: CHARACTERS_SEARCH_SUCCEEDED, characters: data });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* searchCharactersByLetter({ searchTerm }) {
try {
yield put({ type: SET_LETTER, letter: searchTerm });
yield put({ type: CLEAR_SEARCH_TERM });
yield put({ type: LOADING, payload: true });
const characters = yield call(Api.searchCharacters, searchTerm);
const { data, total, count } = characters.data;
yield put({ type: CHARACTERS_SEARCH_SUCCEEDED, characters: data });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* getCharacters() {
yield takeEvery(GET_CHARACTERS, fetchCharacters);
yield takeEvery(GET_SELECTED_CHARACTER, fetchSelectedCharacter);
yield takeLatest(SEARCH_CHARACTERS, searchCharacters);
yield takeLatest(SEARCH_CHARACTERS_BY_LETTER, searchCharactersByLetter);
}
export default getCharacters;
<file_sep>import { Map } from 'immutable';
import {
LOADING,
FETCH_FAILED,
SET_APPLICATION_ERROR,
CLEAR_API_ERRORS,
SHOW_FLASH_MESSAGE,
HIDE_FLASH_MESSAGE,
SHOW_SAVE_ITEM_ERROR_MODAL,
HIDE_SAVE_ITEM_ERROR_MODAL,
HIDE_SERVER_ERROR_MODAL,
SET_PAGINATION_DATA,
CLEAR_API_DATA,
SET_SEARCH_TERM,
CLEAR_SEARCH_TERM,
SET_LETTER,
CLEAR_LETTER,
} from '../constants/display';
const initialState = new Map({
loading: false,
apiError: false,
apiErrorPayload: {},
applicationError: {},
displayFlashMessage: false,
showSaveItemErrorModal: false,
searchTerm: '',
prevLetter: null,
letter: null,
count: 0,
total: 0,
});
export default (state = initialState, action) => {
switch (action.type) {
case LOADING:
return state.set('loading', action.payload);
case FETCH_FAILED:
return state
.set('apiError', true)
.set('apiErrorPayload', action.error);
case SET_APPLICATION_ERROR:
return state.set('applicationError', action.error);
case CLEAR_API_ERRORS:
return state.set('apiError', initialState.get('apiError'));
case SHOW_FLASH_MESSAGE:
return state.set('displayFlashMessage', true);
case HIDE_FLASH_MESSAGE:
return state.set('displayFlashMessage', false);
case SHOW_SAVE_ITEM_ERROR_MODAL:
return state.set('showSaveItemErrorModal', true);
case HIDE_SAVE_ITEM_ERROR_MODAL:
return state.set('showSaveItemErrorModal', false);
case HIDE_SERVER_ERROR_MODAL:
return state
.set('apiError', false)
.set('apiErrorPayload', initialState.get('apiErrorPayload'));
case SET_SEARCH_TERM:
return state.set('searchTerm', action.payload);
case CLEAR_SEARCH_TERM:
return state.set('searchTerm', initialState.get('searchTerm'));
case SET_PAGINATION_DATA:
return state
.set('count', action.count)
.set('total', action.total);
case CLEAR_API_DATA:
return state
.set('count', initialState.get('count'))
.set('total', initialState.get('total'));
case SET_LETTER:
return state
.set('letter', action.letter)
.set('prevLetter', state.get('letter'));
case CLEAR_LETTER:
return state.set('letter', initialState.get('letter'));
default:
return state;
}
};
<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
const SideBar = ({ currentPage }) => (
<aside className="menu column is-one-quarter">
<p className="menu-label">Browse</p>
<ul className="menu-list">
<li className={ currentPage === '/characters' ? 'has-text-weight-bold' : ''}>
<Link to="/">Characters</Link>
</li>
<li className={ currentPage === '/comics' ? 'has-text-weight-bold' : ''}>
<Link to="/comics">Comics</Link>
</li>
<li className={ currentPage === '/creators' ? 'has-text-weight-bold' : ''}>
<Link to="/creators">Creators</Link>
</li>
<li className={ currentPage === '/events' ? 'has-text-weight-bold' : ''}>
<Link to="/events">Events</Link>
</li>
<li className={ currentPage === '/series' ? 'has-text-weight-bold' : ''}>
<Link to="/series">Series</Link>
</li>
</ul>
</aside>
);
SideBar.propTypes = {
currentPage: PropTypes.string.isRequired,
};
export default SideBar;
<file_sep>import React from 'react';
export default () => <li><span className="pagination-ellipsis">…</span></li>;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
const ComicCard = ({
id,
title,
issueNumber,
series: { name },
prices,
thumbnail: { path, extension },
history,
saveResource,
showSaveItemErrorModal,
isSignedIn,
}) => {
const selectComic = () => history.push(`/comics/${id}`);
const saveResourceApiCall = () => saveResource({ id, name: title, resourceType: history.location.pathname.slice(1) });
const saveItemFunction = isSignedIn ? saveResourceApiCall : showSaveItemErrorModal;
return (
<div className="column is-half ComicCard">
<div className="box">
<article className="media">
<div className="media-left">
<figure className="image is-64x64">
<img src={`${path}.${extension}`} alt="http://bulma.io/images/placeholders/128x128.png" />
</figure>
</div>
<div className="media-content">
<div className="content">
<p>
<strong>{ title }</strong>
</p>
<p>Series: <em>{name}</em></p>
<p>Issue Number: <em>{issueNumber}</em></p>
<p>Print Price: <em>${prices[0].price}</em></p>
</div>
<nav className="level is-mobile">
<div className="level-left">
<a className="level-item icon-sm-screen">
<span className="icon is-small r-mar-5">
<i className="fa fa-bookmark" />
</span>
<span className="is-small save-btn" role="presentation" onClick={saveItemFunction}>Save</span>
</a>
<a className="level-item">
<span className="icon is-small r-mar-5">
<i className="fa fa-info-circle" />
</span>
<span className="is-small details-btn" role="presentation" onClick={selectComic}>Details</span>
</a>
</div>
</nav>
</div>
</article>
</div>
</div>
);
};
ComicCard.propTypes = {
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
issueNumber: PropTypes.number.isRequired,
series: PropTypes.shape({
name: PropTypes.string.isRequired,
}).isRequired,
prices: PropTypes.arrayOf(PropTypes.shape({
price: PropTypes.number.isRequired,
})).isRequired,
thumbnail: PropTypes.shape({
extension: PropTypes.string.isRequired,
path: PropTypes.string.isRequired,
}).isRequired,
history: PropTypes.object.isRequired,
saveResource: PropTypes.func.isRequired,
showSaveItemErrorModal: PropTypes.func.isRequired,
isSignedIn: PropTypes.bool.isRequired,
};
export default ComicCard;
<file_sep>import React from 'react';
import { compose, lifecycle, branch, renderComponent } from 'recompose';
import LoadingSpinner from '../components/misc/loadingSpinner';
import NoResultsFound from '../components/misc/noResultsFound';
export default compose(
lifecycle({
componentDidMount() {
const { getUser, apiCall, match, isSignedIn } = this.props;
const id = match && match.params && match.params.id;
if (isSignedIn) {
getUser();
}
if (apiCall) {
apiCall(id);
}
}
}),
branch(
props => props.isLoading,
renderComponent(LoadingSpinner),
),
branch(
props => !Object.keys(props.data).length,
renderComponent(NoResultsFound),
)
);
<file_sep>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { call, takeEvery } from 'redux-saga/effects';
import { runSaga } from 'redux-saga';
import {
fetchCharacters,
fetchSelectedCharacter,
searchCharacters,
} from '../../__mocks__/characters';
Enzyme.configure({ adapter: new Adapter() });
describe('Character Sagas', () => {
it('Should test fetch characters saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, fetchCharacters).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'CHARACTERS_FETCH_SUCCEEDED',
characters: [{
username: 'Pikachu',
email: '<EMAIL>',
}]
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
it('Should test fetch selected character saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, fetchSelectedCharacter, 123).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'SELECTED_CHARACTER_FETCH_SUCCEEDED',
character: {
username: 'Pikachu',
email: '<EMAIL>',
}
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
it('Should test search characters saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, searchCharacters, 123).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'CHARACTERS_SEARCH_SUCCEEDED',
characters: [{
username: 'Pikachu',
email: '<EMAIL>',
}]
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
});
<file_sep>import { call, put, takeEvery, takeLatest } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import * as Api from '../utils/api';
import {
LOADING,
FETCH_FAILED,
SET_SEARCH_TERM,
CLEAR_SEARCH_TERM,
SET_PAGINATION_DATA,
SET_LETTER,
CLEAR_LETTER,
} from '../constants/display';
import {
EVENTS_FETCH_SUCCEEDED,
SELECTED_EVENT_FETCH_SUCCEEDED,
GET_EVENTS,
GET_SELECTED_EVENT,
SEARCH_EVENTS,
EVENTS_SEARCH_SUCCEEDED,
SEARCH_EVENTS_BY_LETTER,
} from '../constants/events';
function* fetchEvents({ offset, searchTerm }) {
try {
yield put({ type: LOADING, payload: true });
const events = yield call(Api.fetchEvents, offset, searchTerm);
const { data, total, count } = events.data;
yield put({ type: EVENTS_FETCH_SUCCEEDED, events: data });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* fetchSelectedEvent({ id }) {
try {
yield put({ type: LOADING, payload: true });
const event = yield call(Api.fetchSelectedEvent(id));
yield put({ type: SELECTED_EVENT_FETCH_SUCCEEDED, event: event.data.data[0] });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* searchEvents({ searchTerm }) {
try {
yield put({ type: SET_SEARCH_TERM, payload: searchTerm });
yield put({ type: CLEAR_LETTER });
yield call(delay, 500);
yield put({ type: LOADING, payload: true });
const events = yield call(Api.searchEvents, searchTerm);
const { data, total, count } = events.data;
yield put({ type: EVENTS_SEARCH_SUCCEEDED, events: data });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* searchEventsByLetter({ searchTerm }) {
try {
yield put({ type: SET_LETTER, letter: searchTerm });
yield put({ type: CLEAR_SEARCH_TERM });
yield put({ type: LOADING, payload: true });
const events = yield call(Api.searchEvents, searchTerm);
const { data, total, count } = events.data;
yield put({ type: EVENTS_SEARCH_SUCCEEDED, events: data });
yield put({ type: SET_PAGINATION_DATA, total, count });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
}
function* getEvents() {
yield takeEvery(GET_EVENTS, fetchEvents);
yield takeEvery(GET_SELECTED_EVENT, fetchSelectedEvent);
yield takeLatest(SEARCH_EVENTS, searchEvents);
yield takeLatest(SEARCH_EVENTS_BY_LETTER, searchEventsByLetter);
}
export default getEvents;
<file_sep>import { call, put } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import * as Api from '../utils/api';
import { LOADING, FETCH_FAILED } from '../constants/display';
import {
CHARACTERS_FETCH_SUCCEEDED,
SELECTED_CHARACTER_FETCH_SUCCEEDED,
CHARACTERS_SEARCH_SUCCEEDED,
} from '../constants/characters';
const mockFetchCharactersApiResponse = jest.fn()
.mockReturnValue({
data: {
data: [{
username: 'Pikachu',
email: '<EMAIL>',
}],
},
});
export const fetchCharacters = function* fetchCharacters() {
try {
yield put({ type: LOADING, payload: true });
const characters = yield call(mockFetchCharactersApiResponse);
yield put({ type: CHARACTERS_FETCH_SUCCEEDED, characters: characters.data.data });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
export const fetchSelectedCharacter = function* fetchSelectedCharacter({ id }) {
try {
yield put({ type: LOADING, payload: true });
const character = yield call(mockFetchCharactersApiResponse, id);
yield put({ type: SELECTED_CHARACTER_FETCH_SUCCEEDED, character: character.data.data[0] });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
export const searchCharacters = function* searchCharacters({ searchTerm }) {
try {
yield call(delay, 500);
yield put({ type: LOADING, payload: true });
const characters = yield call(mockFetchCharactersApiResponse, searchTerm);
yield put({ type: CHARACTERS_SEARCH_SUCCEEDED, characters: characters.data.data });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
<file_sep>import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import characters from './reducers/characters';
import comics from './reducers/comics';
import creators from './reducers/creators';
import events from './reducers/events';
import series from './reducers/series';
import display from './reducers/display';
import user from './reducers/user';
export default combineReducers({
characters,
comics,
creators,
events,
series,
user,
display,
form: formReducer,
});
<file_sep>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { Map } from 'immutable';
import reducer from '../../reducers/display';
import {
LOADING,
FETCH_FAILED,
SET_APPLICATION_ERROR,
CLEAR_API_ERRORS,
SHOW_FLASH_MESSAGE,
HIDE_FLASH_MESSAGE,
SHOW_SAVE_ITEM_ERROR_MODAL,
HIDE_SAVE_ITEM_ERROR_MODAL,
} from '../../constants/display';
Enzyme.configure({ adapter: new Adapter() });
describe.only('Display Reducer', () => {
const initialState = new Map({
loading: false,
apiError: false,
apiErrorPayload: {},
applicationError: {},
displayFlashMessage: false,
showSaveItemErrorModal: false,
});
it('Should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(initialState);
});
it('Should handle LOADING', () => {
expect(
reducer(new Map(), {
type: LOADING,
payload: true,
}),
).toEqual(new Map({
loading: true,
}));
});
it('Should handle FETCH_FAILED', () => {
expect(
reducer(new Map(), {
type: FETCH_FAILED,
error: {
statusCode: 401,
error: 'Unauthorized',
message: 'Invalid password',
},
}),
).toEqual(new Map({
apiError: true,
apiErrorPayload: {
statusCode: 401,
error: 'Unauthorized',
message: 'Invalid password',
},
}));
});
it('Should handle SET_APPLICATION_ERROR', () => {
expect(
reducer(new Map(), {
type: SET_APPLICATION_ERROR,
error: {
err: 'test error',
stack: 'test stack',
},
}),
).toEqual(new Map({
applicationError: {
err: 'test error',
stack: 'test stack',
},
}));
});
it('Should handle CLEAR_API_ERRORS', () => {
expect(
reducer(new Map(), {
type: CLEAR_API_ERRORS,
}),
).toEqual(new Map({
apiError: false,
}));
});
it('Should handle SHOW_FLASH_MESSAGE', () => {
expect(
reducer(new Map(), {
type: SHOW_FLASH_MESSAGE,
}),
).toEqual(new Map({
displayFlashMessage: true,
}));
});
it('Should handle HIDE_FLASH_MESSAGE', () => {
expect(
reducer(new Map(), {
type: HIDE_FLASH_MESSAGE,
}),
).toEqual(new Map({
displayFlashMessage: false,
}));
});
it('Should handle SHOW_SAVE_ITEM_ERROR_MODAL', () => {
expect(
reducer(new Map(), {
type: SHOW_SAVE_ITEM_ERROR_MODAL,
}),
).toEqual(new Map({
showSaveItemErrorModal: true,
}));
});
it('Should handle HIDE_SAVE_ITEM_ERROR_MODAL', () => {
expect(
reducer(new Map(), {
type: HIDE_SAVE_ITEM_ERROR_MODAL,
}),
).toEqual(new Map({
showSaveItemErrorModal: false,
}));
});
});
<file_sep># Marvel Universe React
A UI application built in React to view information provided by the Marvel API in a user-friendly way. End users may register for an account and save their favorite characters, comics, etc. to their profile for easy access at a later time.
## Getting Started
The following instructions will get the React application running on your local machine.
### Installing
Clone the repo:
`git clone https://github.com/matt-taggart/marvel_universe_react.git`
Install node modules:
`yarn install`
Start up webpack dev server:
`yarn start`
Run production build:
`yarn run build`
## Running Tests
This project uses Jest and Enzyme for unit testing purposes. To run the entire test suite, you can use the command `yarn test`. If you prefer to use the "watch" functionality of Jest, you can do this by running `yarn watch`.
## Built With
* React - Javascript library for building UI's.
* Redux - State container for Javascript apps.
* Jest - Zero-configuration testing library.
* Enzyme - Javascript testing utililities for React.
* Recompose - React utility for higher order components.
* Redux-Saga - An alternative side effect model for Redux apps.
## Features
* Register for an account and authenticate users on login.
* If logged in, user can save characters, comics, creators, etc. to their profile for later use.
* Search functionality provided to easily fetch data from the Marvel API.
* Infinite scrolling to load additional results from server.
* Pagination by letter for more convenient browsing.
<file_sep>import { Map } from 'immutable';
import { CLEAR_API_DATA } from '../constants/display';
import {
EVENTS_FETCH_SUCCEEDED,
SELECTED_EVENT_FETCH_SUCCEEDED,
EVENTS_SEARCH_SUCCEEDED,
} from '../constants/events';
const initialState = new Map({
events: [],
selectedEvent: {},
});
export default (state = initialState, action) => {
switch (action.type) {
case EVENTS_FETCH_SUCCEEDED:
return state.set('events', state.get('events').concat(action.events));
case EVENTS_SEARCH_SUCCEEDED:
return state.set('events', action.events);
case SELECTED_EVENT_FETCH_SUCCEEDED:
return state.set('selectedEvent', action.event);
case CLEAR_API_DATA:
return state
.set('events', initialState.get('events'))
.set('selectedEvent', initialState.get('selectedEvent'));
default:
return state;
}
};
<file_sep>import { call, put, select } from 'redux-saga/effects';
import * as Api from '../utils/api';
import history from '../utils/history';
import { LOADING, FETCH_FAILED } from '../constants/display';
import {
SIGN_IN_SUCCEEDED,
LOGOUT_SUCCEEDED,
} from '../constants/auth';
const mockHistory = {
push: jest.fn(value => value),
};
const mockSignInApiResponse = jest.fn()
.mockReturnValueOnce({
data: {
username: 'Pikachu',
email: '<EMAIL>',
},
});
export const signIn = function* signIn() {
try {
yield put({ type: LOADING, payload: true });
const credentials = yield select(state => ({
email: state.form.signIn.values.email,
password: <PASSWORD>,
}));
const user = yield call(mockSignInApiResponse, credentials);
yield put({ type: SIGN_IN_SUCCEEDED, user: user.data });
yield put({ type: LOADING, payload: false });
yield call(mockHistory.push, '/profile');
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
export const logout = function* logout() {
try {
yield put({ type: LOADING, payload: true });
yield call(Api.logout);
yield put({ type: LOGOUT_SUCCEEDED });
yield put({ type: LOADING, payload: false });
yield call(history.push, '/');
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import Immutable from 'immutable';
const Nav = ({ user, logout }) => (
<nav className="navbar is-dark" aria-label="main navigation">
<div className="navbar-brand">
<div className="navbar-item">
<h1 className="title is-3"><Link to="/">Marvel Universe</Link></h1>
</div>
</div>
<div className="navbar-menu">
<div className="navbar-end">
{ user.get('signedIn') && Object.keys(user.get('user')).length
? (
<div className="navbar-item has-dropdown is-hoverable">
<Link className="navbar-link" to="/profile">
<span className="r-mar"><i className="fa fa-user" /></span>
<span>{ user.get('user').name }</span>
</Link>
<div className="navbar-dropdown is-boxed">
<Link className="navbar-item" to="/">
Home
</Link>
<Link className="navbar-item" to="/profile">
Profile
</Link>
<a className="navbar-item" onClick={logout} role="navigation">
Logout
</a>
</div>
</div>
)
: (
<div className="navbar-item">
<Link to="/sign-in" className="title is-6">Sign In</Link>
</div>
)
}
</div>
</div>
</nav>
);
Nav.propTypes = {
user: PropTypes.instanceOf(Immutable.Map).isRequired,
logout: PropTypes.func.isRequired,
};
export default Nav;
<file_sep>import { Map } from 'immutable';
import { CLEAR_API_DATA } from '../constants/display';
import {
SERIES_FETCH_SUCCEEDED,
SELECTED_SERIES_FETCH_SUCCEEDED,
SERIES_SEARCH_SUCCEEDED,
} from '../constants/series';
const initialState = new Map({
series: [],
selectedSeries: {},
});
export default (state = initialState, action) => {
switch (action.type) {
case SERIES_FETCH_SUCCEEDED:
return state.set('series', state.get('series').concat(action.series));
case SERIES_SEARCH_SUCCEEDED:
return state.set('series', action.series);
case SELECTED_SERIES_FETCH_SUCCEEDED:
return state.set('selectedSeries', action.series);
case CLEAR_API_DATA:
return state
.set('series', initialState.get('series'))
.set('selectedSeries', initialState.get('selectedSeries'));
default:
return state;
}
};
<file_sep>import { call, put } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import * as Api from '../utils/api';
import { LOADING, FETCH_FAILED } from '../constants/display';
import {
EVENTS_FETCH_SUCCEEDED,
SELECTED_EVENT_FETCH_SUCCEEDED,
EVENTS_SEARCH_SUCCEEDED,
} from '../constants/events';
const mockFetchEventsApiResponse = jest.fn()
.mockReturnValue({
data: {
data: [{
id: 5,
title: 'Wolverine',
}],
},
});
export const fetchEvents = function* fetchEvents() {
try {
yield put({ type: LOADING, payload: true });
const events = yield call(mockFetchEventsApiResponse);
yield put({ type: EVENTS_FETCH_SUCCEEDED, events: events.data.data });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
export const fetchSelectedEvent = function* fetchSelectedEvent({ id }) {
try {
yield put({ type: LOADING, payload: true });
const event = yield call(mockFetchEventsApiResponse, id);
yield put({ type: SELECTED_EVENT_FETCH_SUCCEEDED, event: event.data.data[0] });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
export const searchEvents = function* searchEvents({ searchTerm }) {
try {
yield call(delay, 500);
yield put({ type: LOADING, payload: true });
const events = yield call(mockFetchEventsApiResponse, searchTerm);
yield put({ type: EVENTS_SEARCH_SUCCEEDED, events: events.data.data });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Immutable from 'immutable';
import { Field, reduxForm, SubmissionError } from 'redux-form';
import { validateRegistration } from '../../utils/validators';
import renderField from '../forms/renderField';
import renderGroupField from '../forms/renderGroupField';
import renderDropdown from '../forms/renderDropdown';
const Register = ({ handleSubmit, display, register, isLoading }) => {
const submit = ({ name, email, password, age, gender }) => {
const errors = validateRegistration(name, email, password, age, gender);
if (Object.keys(errors).length) {
throw new SubmissionError(errors);
}
register();
};
const buttonClasses = isLoading
? 'button disabled is-dark is-medium is-loading'
: 'button is-dark is-medium';
return (
<div className="columns is-centered">
<div className="column is-two-thirds">
<form onSubmit={handleSubmit(submit)}>
<Field
name="name"
type="text"
placeholder="Name"
iconClasses="fa fa-user"
component={renderField}
/>
<Field
name="email"
type="text"
placeholder="Email"
iconClasses="fa fa-envelope"
component={renderField}
/>
<Field
name="password"
type="<PASSWORD>"
placeholder="<PASSWORD>"
iconClasses="fa fa-lock"
component={renderField}
/>
<div className="field is-horizontal">
<div className="field-body">
<Field
name="age"
type="text"
placeholder="Age"
component={renderGroupField}
/>
<Field
name="gender"
defaultValue="Gender"
options={['Male', 'Female']}
component={renderDropdown}
/>
</div>
</div>
{ display.get('apiError').message && (
<div className="field">
<div className="message is-danger">
<div className="message-body">
{ display.get('apiError').message }
</div>
</div>
</div>
)}
<div className="field">
<p className="control">
<button className={buttonClasses}>
Register
</button>
</p>
</div>
</form>
</div>
</div>
);
};
Register.propTypes = {
handleSubmit: PropTypes.func.isRequired,
display: PropTypes.instanceOf(Immutable.Map).isRequired,
register: PropTypes.func.isRequired,
isLoading: PropTypes.bool.isRequired,
};
export default reduxForm({
form: 'register',
})(Register);
<file_sep>import { call, put } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import * as Api from '../utils/api';
import { LOADING, FETCH_FAILED } from '../constants/display';
import {
COMICS_FETCH_SUCCEEDED,
SELECTED_COMIC_FETCH_SUCCEEDED,
COMICS_SEARCH_SUCCEEDED,
} from '../constants/comics';
const mockFetchComicsApiResponse = jest.fn()
.mockReturnValue({
data: {
data: [{
title: 'Spiderman',
issueNumber: 5,
}],
},
});
export const fetchComics = function* fetchComics() {
try {
yield put({ type: LOADING, payload: true });
const comics = yield call(mockFetchComicsApiResponse);
yield put({ type: COMICS_FETCH_SUCCEEDED, comics: comics.data.data });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
export const fetchSelectedComic = function* fetchSelectedComic({ id }) {
try {
yield put({ type: LOADING, payload: true });
const comic = yield call(mockFetchComicsApiResponse, id);
yield put({ type: SELECTED_COMIC_FETCH_SUCCEEDED, comic: comic.data.data[0] });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
export const searchComics = function* searchComics({ searchTerm }) {
try {
yield call(delay, 500);
yield put({ type: LOADING, payload: true });
const comics = yield call(mockFetchComicsApiResponse, searchTerm);
yield put({ type: COMICS_SEARCH_SUCCEEDED, comics: comics.data.data });
yield put({ type: LOADING, payload: false });
} catch (e) {
yield put({ type: LOADING, payload: false });
yield put({ type: FETCH_FAILED, error: e });
}
};
<file_sep>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { call, takeEvery } from 'redux-saga/effects';
import { runSaga } from 'redux-saga';
import {
fetchEvents,
fetchSelectedEvent,
searchEvents,
} from '../../__mocks__/events';
Enzyme.configure({ adapter: new Adapter() });
describe('Events Sagas', () => {
it('Should test fetch events saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, fetchEvents).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'EVENTS_FETCH_SUCCEEDED',
events: [{
id: 5,
title: 'Wolverine',
}]
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
it('Should test fetch selected event saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, fetchSelectedEvent, 123).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'SELECTED_EVENT_FETCH_SUCCEEDED',
event: {
id: 5,
title: 'Wolverine',
}
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
it('Should test search events saga', async () => {
const dispatched = [];
const result = await runSaga({
dispatch: action => dispatched.push(action),
}, searchEvents, 123).done;
expect(dispatched[0]).toEqual({ type: 'LOADING', payload: true });
expect(dispatched[1])
.toEqual({
type: 'EVENTS_SEARCH_SUCCEEDED',
events: [{
id: 5,
title: 'Wolverine',
}]
});
expect(dispatched[2]).toEqual({ type: 'LOADING', payload: false });
});
});
<file_sep>import { Map } from 'immutable';
import { CLEAR_API_DATA } from '../constants/display';
import {
CREATORS_FETCH_SUCCEEDED,
SELECTED_CREATOR_FETCH_SUCCEEDED,
CREATORS_SEARCH_SUCCEEDED,
} from '../constants/creators';
const initialState = new Map({
creators: [],
selectedCreator: {},
});
export default (state = initialState, action) => {
switch (action.type) {
case CREATORS_FETCH_SUCCEEDED:
return state.set('creators', state.get('creators').concat(action.creators));
case CREATORS_SEARCH_SUCCEEDED:
return state.set('creators', action.creators);
case SELECTED_CREATOR_FETCH_SUCCEEDED:
return state.set('selectedCreator', action.creator);
case CLEAR_API_DATA:
return state
.set('creators', initialState.get('creators'))
.set('selectedCreator', initialState.get('selectedCreator'));
default:
return state;
}
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
const PaginationLink = ({ setPaginationAndSearch, letter, activeLetter }) => {
const setLetterFunc = () => setPaginationAndSearch(letter);
const letterClasses = (letter === activeLetter)
? 'pagination-link active-letter'
: 'pagination-link';
return (
<li onClick={setLetterFunc}>
<a className={letterClasses} aria-label={`Go to letter ${letter}`}>{ letter }</a>
</li>
);
};
PaginationLink.propTypes = {
setPaginationAndSearch: PropTypes.func.isRequired,
letter: PropTypes.string.isRequired,
activeLetter: PropTypes.string,
};
export default PaginationLink;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Immutable from 'immutable';
import PaginationLink from './paginationLink';
import Ellipsis from '../misc/ellipsis';
import LETTERS from '../../constants/letters';
const PaginationBar = ({ setPaginationAndSearch, display }) => {
let componentToRender = null;
let currentIndex = -1;
let prevIndex = 0;
const renderStartOfList = () => (
<ul className="pagination-list">
{
LETTERS
.slice(0, 5)
.map(letter => (
<PaginationLink
setPaginationAndSearch={setPaginationAndSearch}
letter={letter}
activeLetter={display.get('letter')}
key={letter}
/>
))
}
<Ellipsis />
{
LETTERS
.slice(25)
.map(letter => (
<PaginationLink
setPaginationAndSearch={setPaginationAndSearch}
letter={letter}
activeLetter={display.get('letter')}
key={letter}
/>
))
}
</ul>
);
const renderMiddleOfList = index => (
<ul className="pagination-list">
{
LETTERS
.slice(0, 1)
.map(letter => (
<PaginationLink
setPaginationAndSearch={setPaginationAndSearch}
letter={letter}
activeLetter={display.get('letter')}
key={letter}
/>
))
}
<Ellipsis />
{
LETTERS
.slice(index - 2, index + 3)
.map(letter => (
<PaginationLink
setPaginationAndSearch={setPaginationAndSearch}
letter={letter}
activeLetter={display.get('letter')}
key={letter}
/>
))
}
<Ellipsis />
{
LETTERS
.slice(25)
.map(letter => (
<PaginationLink
setPaginationAndSearch={setPaginationAndSearch}
letter={letter}
activeLetter={display.get('letter')}
key={letter}
/>
))
}
</ul>
);
const renderEndOfList = () => (
<ul className="pagination-list">
{ LETTERS
.slice(0, 1)
.map(letter => (
<PaginationLink
setPaginationAndSearch={setPaginationAndSearch}
letter={letter}
activeLetter={display.get('letter')}
key={letter}
/>
)) }
<Ellipsis />
{ LETTERS
.slice(21, 26)
.map(letter => (
<PaginationLink
setPaginationAndSearch={setPaginationAndSearch}
letter={letter}
activeLetter={display.get('letter')}
key={letter}
/>
)) }
</ul>
);
if (display.get('letter')) {
currentIndex = LETTERS.findIndex(letter => (
letter === display.get('letter')
));
prevIndex = LETTERS.findIndex(letter => (
letter === display.get('prevLetter')
));
}
if (currentIndex < 4) {
componentToRender = renderStartOfList();
}
if (currentIndex >= 4 && currentIndex < 21) {
componentToRender = renderMiddleOfList(currentIndex);
}
if (currentIndex === 21 && prevIndex > currentIndex) {
componentToRender = renderMiddleOfList(currentIndex);
}
if (currentIndex === 21 && prevIndex < currentIndex) {
componentToRender = renderEndOfList();
}
if (currentIndex > 21) {
componentToRender = renderEndOfList();
}
const setPrevLetter = () => setPaginationAndSearch((LETTERS[currentIndex - 1] || 'A'));
const setNextLetter = () => setPaginationAndSearch((LETTERS[currentIndex + 1] || 'Z'));
return (
<nav className="pagination is-small" role="navigation" aria-label="pagination">
<button className="pagination-previous" disabled={!display.get('letter') || display.get('letter') === 'A'} onClick={setPrevLetter}>Previous</button>
<button className="pagination-next" disabled={display.get('letter') === 'Z'} onClick={setNextLetter}>Next page</button>
{ componentToRender }
</nav>
);
};
PaginationBar.propTypes = {
setPaginationAndSearch: PropTypes.func.isRequired,
display: PropTypes.instanceOf(Immutable.Map).isRequired,
};
export default PaginationBar;
<file_sep>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { Map } from 'immutable';
import reducer from '../../reducers/comics';
import {
COMICS_FETCH_SUCCEEDED,
SELECTED_COMIC_FETCH_SUCCEEDED,
COMICS_SEARCH_SUCCEEDED,
} from '../../constants/comics';
Enzyme.configure({ adapter: new Adapter() });
describe('Comics Reducer', () => {
const initialState = new Map({
comics: [],
selectedComic: {},
});
it('Should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(initialState);
});
it('Should handle COMICS_FETCH_SUCCEEDED', () => {
expect(
reducer(new Map(), {
type: COMICS_FETCH_SUCCEEDED,
comics: [
{ id: 1, name: 'spiderman' },
],
}),
).toEqual(new Map({
comics: [
{ id: 1, name: 'spiderman' },
],
}));
});
it('Should handle COMICS_SEARCH_SUCCEEDED', () => {
expect(
reducer(new Map(), {
type: COMICS_SEARCH_SUCCEEDED,
comics: [
{ id: 1, name: 'spiderman' },
],
}),
).toEqual(new Map({
comics: [
{ id: 1, name: 'spiderman' },
],
}));
});
it('Should handle SELECTED_COMIC_FETCH_SUCCEEDED', () => {
expect(
reducer(new Map(), {
type: SELECTED_COMIC_FETCH_SUCCEEDED,
comic: { id: 1, name: 'spiderman' },
}),
).toEqual(new Map({
selectedComic: { id: 1, name: 'spiderman' },
}));
});
});
<file_sep>const webpack = require('webpack');
const { join } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const merge = require('webpack-merge');
const parts = require('./webpack.parts');
const commonConfig = merge([
{
entry: {
src: ['babel-polyfill', join(__dirname, 'src', 'index.jsx')],
},
output: {
path: join(__dirname, 'dist'),
filename: '[name].js',
},
plugins: [
new HtmlWebpackPlugin({
title: 'Project',
minify: {
collapseWhitespace: true,
},
hash: true,
template: join(__dirname, 'src', './index.ejs'),
}),
new webpack.NamedModulesPlugin(),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
resolve: {
extensions: ['.js', '.jsx'],
},
},
parts.loadFonts({
options: {
name: '[name].[hash].[ext]',
},
}),
parts.loadJavascript({
include: join(__dirname, 'src'),
exclude: /node_modules/,
}),
]);
const productionConfig = merge([
{
output: {
chunkFilename: '[name].[chunkhash].js',
filename: '[name].[chunkhash].js',
},
plugins: [
new BundleAnalyzerPlugin(),
new CleanWebpackPlugin('dist'),
],
},
parts.extractBundles([
{
name: 'vendor',
minChunks: ({ resource }) => /node_modules/.test(resource),
},
{
name: 'manifest',
minChunks: Infinity,
},
]),
parts.extractCSS({
use: [
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')],
},
},
'sass-loader',
],
}),
parts.loadImages({
options: {
limit: 15000,
name: '[name].[hash].[ext]',
},
}),
parts.generateSourceMaps({ type: 'source-map' }),
parts.minifyJavascript(),
parts.minifyCSS({
options: {
discardComments: {
removeAll: true,
},
safe: true,
},
}),
parts.setVariable('process.env.NODE_ENV', 'production'),
parts.setVariable('process.env.API_URL', 'http://api.marveluniverse.info'),
]);
const developmentConfig = merge([
parts.devServer({
host: process.env.HOST,
port: process.env.PORT,
}),
parts.loadCSS(),
parts.loadImages(),
parts.generateSourceMaps({
type: 'cheap-module-eval-source-map',
}),
parts.setVariable('process.env.API_URL', 'http://192.168.99.100:3000'),
{
output: {
publicPath: '/',
devtoolModuleFilenameTemplate:
'webpack:///[absolute-resource-path]',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
},
]);
module.exports = env => {
if (env === 'production') {
return merge(commonConfig, productionConfig);
}
return merge(commonConfig, developmentConfig);
};
// TODO: Add SourceMapDevToolPlugin
| 05777bf56f2e88933d3d363cff2dc06ef45f9637 | [
"JavaScript",
"Markdown"
] | 68 | JavaScript | matt-taggart/marvel_universe_react | 4ed63b6af9a87bebfb1a0ea115383eb0fe043178 | ed67634ff838bf4ae236688177d498de435b0faf |
refs/heads/master | <file_sep>package testingg;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Test;
public class testgrid {
public RemoteWebDriver driver;
@Test
public void gridd() throws MalformedURLException{
DesiredCapabilities cp = DesiredCapabilities.firefox();
cp.setCapability(FirefoxDriver.BINARY, new File ("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe").getAbsolutePath());
// cp.setJavascriptEnabled(true);
driver = new RemoteWebDriver(new URL("http://10.32.5.119:5555/wd/hub"),cp);
driver.get("http://facebook.com");
}
}
| fd8624a9735845e5f15922e9119ee1e93f0db41b | [
"Java"
] | 1 | Java | nikhiljain86/test | 77ae88acc45a22ae48e5e56c4eb6bb110c6c7817 | 0147fa5f10364538ec5a5b1734cb79144d26b73a |
refs/heads/master | <file_sep>#$<NAME> 10/15/19
import turtle
groundLevel = turtle.window_height() / 2 * -1 + 100
def grass(x, y):
grass = turtle.Turtle()
grass.ht()
grass.width(10)
grass.up()
grass.goto(x,y)
grass.down()
grass.color('green')
grass.left(150)
for i in range(0,3):
grass.forward(50)
grass.left(180)
grass.forward(50)
grass.left(120)
def ground():
ground = turtle.Turtle()
ground.ht()
ground.up()
ground.goto(turtle.window_width() / 2 * -1, turtle.window_height() / 2 * -1 + 100)
ground.pencolor('green')
ground.fillcolor('green')
ground.down()
ground.begin_fill()
ground.forward(turtle.window_width())
ground.right(90)
ground.forward(100)
ground.right(90)
ground.forward(turtle.window_width())
ground.right(90)
ground.forward(100)
ground.end_fill()
def tree(x, y):
tree = turtle.Turtle()
tree.ht()
tree.up()
tree.color('brown')
tree.fillcolor('brown')
tree.goto(x, y)
tree.down()
tree.begin_fill()
for x in range(0,2):
tree.forward(75)
tree.left(90)
tree.forward(325)
tree.left(90)
tree.end_fill()
#leaves
tree.up()
tree.color('ForestGreen')
tree.fillcolor('ForestGreen')
height = groundLevel + 305
tree.goto(x - 40, height)
for x in range(0, 6):
tree.down()
tree.begin_fill()
height = groundLevel + 325
tree.circle(40)
tree.end_fill()
tree.up()
tree.forward(60)
tree.up()
tree.goto(x, height + 20)
for x in range(0, 4):
tree.down()
tree.begin_fill()
height = groundLevel + 345
tree.circle(40)
tree.end_fill()
tree.up()
tree.forward(60)
tree.up()
tree.goto(x + 25, height + 45)
for x in range(0, 3):
tree.down()
tree.begin_fill()
height = groundLevel + 345
tree.circle(40)
tree.end_fill()
tree.up()
tree.forward(60)
def sky():
sky = turtle.Turtle()
sky.ht()
sky.up()
sky.color("LightSkyBlue")
sky.fillcolor("LightSkyBlue")
sky.goto(turtle.window_width() / 2 * -1, turtle.window_height() / 2)
sky.down()
sky.begin_fill()
sky.forward(turtle.window_width())
sky.right(90)
sky.forward(turtle.window_height())
sky.right(90)
sky.forward(turtle.window_width())
sky.right(90)
sky.forward(turtle.window_height())
sky.end_fill()
sky()
ground()
grass(-110,groundLevel)
grass(240,groundLevel)
tree(65, groundLevel)
<file_sep>#<NAME> 10/15/19
import turtle
bob = turtle.Turtle()
bob.right(54)
for x in range(0,5):
bob.forward(50)
bob.left(54)
bob.forward(50)
bob.right(126)
<file_sep>#<NAME> 10/15/19
import turtle
import random
bob = turtle.Turtle()
for x in range(0,5):
color = hex(random.randint(0,16777215))
bob.color("#" + color[2:])
bob.begin_fill()
bob.circle(25)
bob.end_fill()
bob.up()
bob.forward(50)
bob.down()
| 40b62f6026588ace43bfa6a67c38bfb3b01bb99d | [
"Python"
] | 3 | Python | Worcester-Preparatory-School-Comp-Sci/turtle-graphics-2-SpencerPaquette | d242343d1877dde82ba02af8095b37ac9859a0b9 | 1d61c9f17b4ac69a64fd1b1d741fe7c6ec5f5c5e |
refs/heads/master | <file_sep>var fs = require('fs');
var input = fs.readFileSync('1.txt').toString().split("\n").map(num => parseInt(num));
const getModuleFuel = (mass) => {
return Math.floor(mass / 3) - 2;
}
const sum = (a, b) => {
return a + b;
}
const calculateTotalFuelPart2 = (moduleMass) => {
const moduleFuel = getModuleFuel(moduleMass);
return moduleFuel <= 0 ? 0 : moduleFuel + calculateTotalFuelPart2(moduleFuel);
}
const part1 = input.map(getModuleFuel).reduce(sum);
const part2 = input.map(calculateTotalFuelPart2).reduce(sum);
console.log(part1);
console.log(part2);<file_sep>var fs = require('fs');
var input1 = fs.readFileSync('3a.txt').toString().split(",");
var input2 = fs.readFileSync('3b.txt').toString().split(",");
const getPathPoints = (trail) => {
const path = [];
var x = 0, y = 0;
for( var i = 0; i< trail.length; i++){
const dir = trail[i].slice(0, 1);
const dist = parseInt(trail[i].slice(1));
if(dir == 'R') {
for(var j = 1; j <= dist; j++){
path.push([x + j, y]);
}
x += j-1;
}
else if (dir == 'L') {
for (var j = 1; j <= dist; j++) {
path.push([x - j, y]);
}
x -= j-1;
}
if (dir == 'U') {
for (var j = 1; j <= dist; j++) {
path.push([x, y + j]);
}
y += j-1;
}
if (dir == 'D') {
for (var j = 1; j <= dist; j++) {
path.push([x, y - j]);
}
y -= j-1;
}
}
return path;
}
const getIntersectionPoints = (path1, path2) => {
const res = [];
var hash = {};
for (var i = 0; i < path1.length; i += 1) {
hash[path1[i]] = i;
}
for(var i = 0; i<path2.length; i++){
if (hash.hasOwnProperty(path2[i])) {
res.push(path2[i])
}
}
return res;
}
const getMinDistanceFromCenter = (points) => {
let minDist = Number.MAX_SAFE_INTEGER;
for (var i = 0; i< points.length; i++){
if (Math.abs(points[i][0]) + Math.abs(points[i][1]) < minDist) minDist = Math.abs(points[i][0]) + Math.abs(points[i][1]);
}
return minDist;
}
const part2 = (intersectionPoints, pathPoints1, pathPoints2) => {
let min = Number.MAX_SAFE_INTEGER;
for(var i=0; i<intersectionPoints.length; i++){
min = Math.min(min, lengthTill(pathPoints1, intersectionPoints[i]) + lengthTill(pathPoints2, intersectionPoints[i]));
}
return min;
}
const lengthTill = (arr, point) => {
var sum = 0;
for (var i = 0; i < arr.length && JSON.stringify(arr[i]) != JSON.stringify(point); i++){
sum+=1;
}
return sum + 1;
}
console.time('part1');
getMinDistanceFromCenter(getIntersectionPoints(getPathPoints(input1), getPathPoints(input2)));
console.timeEnd('part1');
console.time('part2');
part2(getIntersectionPoints(getPathPoints(input1), getPathPoints(input2)), getPathPoints(input1), getPathPoints(input2) );
console.timeEnd('part2');
<file_sep>const getInput = () => {
return [1, 0, 0, 3, 1, 1, 2, 3, 1, 3, 4, 3, 1, 5, 0, 3, 2, 9, 1, 19, 1, 19, 5, 23, 1, 23, 6, 27, 2, 9, 27, 31, 1, 5, 31, 35, 1, 35, 10, 39, 1, 39, 10, 43, 2, 43, 9, 47, 1, 6, 47, 51, 2, 51, 6, 55, 1, 5, 55, 59, 2, 59, 10, 63, 1, 9, 63, 67, 1, 9, 67, 71, 2, 71, 6, 75, 1, 5, 75, 79, 1, 5, 79, 83, 1, 9, 83, 87, 2, 87, 10, 91, 2, 10, 91, 95, 1, 95, 9, 99, 2, 99, 9, 103, 2, 10, 103, 107, 2, 9, 107, 111, 1, 111, 5, 115, 1, 115, 2, 119, 1, 119, 6, 0, 99, 2, 0, 14, 0];
}
const prepInput = (rawInput) => {
rawInput[1] = 12;
rawInput[2] = 2;
return rawInput;
}
const part1 = (input) => {
for (var i = 0; i < input.length; i++) {
if (input[i] == 99) break;
if (input[i] == 1) {
input[input[i + 3]] = input[input[i + 1]] + input[input[i + 2]];
}
else if (input[i] == 2) {
input[input[i + 3]] = input[input[i + 1]] * input[input[i + 2]];
}
i += 3;
}
return input;
}
const part2 = (input) => {
for (var i = 0; i < 100; i++){
for (var j = 0; j < 100; j++){
input = getInput();
input[1] = i, input[2] = j;
if (part1(input)[0] == 19690720) {
console.log('halting----------', i, j);
break;
}
}
}
}
console.log((part2(getInput())));
console.log(part1(prepInput(getInput()))[0]);
<file_sep>
const isNotDecreasing = (num) => {
return JSON.stringify((num).toString().split('').sort()) == JSON.stringify((num).toString().split(''))
}
const hasAdjDuplicates = (num) => {
let hasDup = false;
const str = num.toString();
for(var i = 1; i< str.length; i++){
if(str[i] == str[i-1]) {
hasDup = true;
break;
}
}
return hasDup;
}
const hasAdjDuplicatesPart2 = (num) => {
let hasDup = false;
const str = num.toString();
for (var i = 1; i < str.length; i++) {
if (str[i] == str[i - 1]
&& ((i -2 >= 0) ? str[i - 1] != str[i - 2] : true)
&& ((i + 1 < str.length ? str[i] != str[i + 1] : true ))
) {
hasDup = true;
break;
}
}
return hasDup;
}
const solve = (range) => {
const l = range.split('-')[0], r = range.split('-')[1];
let part1 = 0, part2 = 0;
for(var i = l; i<= r; i++){
if (isNotDecreasing(i) && hasAdjDuplicates(i)) part1+=1;
if (isNotDecreasing(i) && hasAdjDuplicatesPart2(i)) part2+=1;
}
console.log(part1, part2);
return;
}
solve('171309-643603'); | 565ba0d367c83417c3365305905402e215359c6c | [
"JavaScript"
] | 4 | JavaScript | farahanjum/aoc2019 | fe3507893748acb4c7d9d8e92209a62783138926 | 10f11917ad871a83799dca000e469845c4350bc4 |
refs/heads/master | <file_sep><?php
include_once("config.php");
if(isset($_POST['update'])){
$id = mysqli_real_escape_string($mysqli, $_POST['id']);
$ime = mysqli_real_escape_string($mysqli, $_POST['ime']);
$priimek = mysqli_real_escape_string($mysqli, $_POST['priimek']);
$datum = mysqli_real_escape_string($mysqli, $_POST['datum']);
$dosje = mysqli_real_escape_string($mysqli, $_POST['dosje']);
$policist = mysqli_real_escape_string($mysqli, $_POST['policist']);
if(empty($ime) || empty($priimek) || empty($datum) || empty($dosje) || empty($policist)) {
if(empty($ime)) {
echo "<font color='red'>Potrebno vpisati IME.</font><br/>";
}
if(empty($priimek)) {
echo "<font color='red'>Potrebno vpisati PRIIMEK.</font><br/>";
}
if(empty($datum)) {
echo "<font color='red'>Potrebno vpisati DATUM.</font><br/>";
}
if(empty($dosje)) {
echo "<font color='red'>Potrebno vpisati DOSJE.</font><br/>";
}
if(empty($policist)) {
echo "<font color='red'>Potrebno vpisati POLICISTA.</font><br/>";
}
} else {
$result = mysqli_query($mysqli, "UPDATE vabilo SET ime='$ime', priimek='$priimek', datum='$datum', dosje='$dosje', policist='$policist' WHERE id='$id'");
header("Location: prikaz.php");
}
}
?>
<?php
$id = isset($_GET['id']) ? $_GET['id'] : '';
$sql = "SELECT * FROM vabilo WHERE id='$id'";
$result = mysqli_query($mysqli, $sql);
while($res = mysqli_fetch_array($result))
{
$ime = $res['ime'];
$priimek = $res['priimek'];
$datum = $res['datum'];
$dosje = $res['dosje'];
$policist = $res['policist'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ažuriranje vabljene osebe</title>
<style>
html, body {
max-width: 100%;
overflow-x: hidden;
}
main {
width: 80%;
height: 80%;
border: none;
position: absolute;
left: 10%;
top: 10%;
font-family: verdana;
font-size: 150px;
text-align: center;
}
#a {
top:5%;
left:80%;
position:absolute;
color:white;
font-size:25px;
}
#b {
top:30%;
left:42%;
position:absolute;
color:white;
font-size:18px;
}
</style>
</head>
<body background="img/background.jpg">
<main>
<div style="top:5%; left:30%; color:white; font-size:20px; ">
<h1>Ažuriranje vabljene osebe</h1>
</div>
<div id="a">
<a style="color:white;" href = "index.php">Nazaj</a>
</div>
</main>
<div id="b">
<form name="obrazec1" method="post" action="Azuriranje.php">
<table>
<tr>
<td>Ime</td>
<td><input type="text" name="ime" value="<?php echo $ime;?>"></td>
</tr>
<tr>
<td>Priimek</td>
<td><input type="text" name="priimek" value="<?php echo $priimek;?>"></td>
</tr>
<tr>
<td>Datum</td>
<td><input type="date" name="datum" value="<?php echo $datum;?>"></td>
</tr>
<tr>
<td>Dosje</td>
<td><input type="int" name="dosje" value="<?php echo $dosje;?>"></td>
</tr>
<tr>
<td>Policist</td>
<td><input type="text" name="policist" value="<?php echo $policist;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value="<?php echo $_GET['id'];?>"></td>
<td><input type="submit" name="update" value="Ažuriraj"></td>
</tr>
</table>
</form>
</div>
</body>
</html><file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.1
-- https://www.phpmyadmin.net/
--
-- Gostitelj: 127.0.0.1
-- Čas nastanka: 17. avg 2018 ob 22.53
-- Različica strežnika: 10.1.33-MariaDB
-- Različica PHP: 7.2.6
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Zbirka podatkov: `test`
--
-- --------------------------------------------------------
--
-- Struktura tabele `vabilo`
--
CREATE TABLE `vabilo` (
`id` int(11) NOT NULL,
`ime` varchar(30) COLLATE utf8_slovenian_ci NOT NULL,
`priimek` varchar(30) COLLATE utf8_slovenian_ci NOT NULL,
`datum` date NOT NULL,
`dosje` int(7) NOT NULL,
`policist` varchar(30) COLLATE utf8_slovenian_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_slovenian_ci;
--
-- Odloži podatke za tabelo `vabilo`
--
INSERT INTO `vabilo` (`id`, `ime`, `priimek`, `datum`, `dosje`, `policist`) VALUES
(1, 'Katarina', 'Lupšina', '2018-09-15', 1, 'Žolger'),
(2, 'Katja', 'PoliÄnik', '2018-10-15', 2, 'MikoliÄ'),
(3, 'Samo', 'Možnar', '2018-09-18', 3, 'Pernek'),
(4, 'Uroš', 'Klavžar', '2018-09-09', 4, 'Vajda'),
(5, 'Matija', 'Planko', '2018-09-28', 5, 'Furst'),
(6, 'Klemen', 'Krizar', '2018-09-14', 7, 'Markovec'),
(7, 'Miha', 'Jordan', '2018-09-11', 6, 'Vajda'),
(8, 'Peter', 'Berdnik', '2018-09-08', 7, 'Markovec'),
(9, 'Janko', 'Moder', '2018-08-23', 8, 'Pernek'),
(10, 'Nino', 'Vranes', '2018-09-20', 9, 'Furst'),
(11, 'Davor', 'Ulcar', '2018-08-26', 10, 'Pernek'),
(12, 'Klemen', 'Kranjc', '2018-08-28', 11, 'Furst'),
(17, 'Davor', 'Plahuta', '2018-08-25', 12, 'Vajda'),
(18, 'Slavko', 'Slavc', '2018-09-22', 12, 'Furst'),
(19, 'Boris', 'Stajnko', '2018-09-08', 13, 'Furst'),
(20, 'Jože', 'Gržina', '2018-08-29', 13, 'Mikek');
--
-- Indeksi zavrženih tabel
--
--
-- Indeksi tabele `vabilo`
--
ALTER TABLE `vabilo`
ADD PRIMARY KEY (`id`);
ALTER TABLE `vabilo` ADD FULLTEXT KEY `ime` (`ime`);
ALTER TABLE `vabilo` ADD FULLTEXT KEY `priimek` (`priimek`);
ALTER TABLE `vabilo` ADD FULLTEXT KEY `policist` (`policist`);
--
-- AUTO_INCREMENT zavrženih tabel
--
--
-- AUTO_INCREMENT tabele `vabilo`
--
ALTER TABLE `vabilo`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
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><?php
include_once("config.php");
$result = mysqli_query($mysqli, "SELECT * FROM vabilo ORDER BY datum DESC");
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Prikaz vabljenih oseb</title>
<style>
html, body {
max-width: 100%;
overflow-x: hidden;
}
main {
width: 80%;
height: 80%;
border: none;
position: absolute;
left: 10%;
top: 10%;
font-family: verdana;
font-size: 150px;
text-align: center;
}
#a {
top:5%;
left:80%;
position:absolute;
color:white;
font-size:25px;
}
#b {
top:30%;
left:42%;
position:absolute;
color:white;
font-size:18px;
}
</style>
</head>
<body background="img/background.jpg">
<main>
<div style="top:5%; left:30%; color:white; font-size:20px; ">
<h1>Prikaz vabljenih oseb</h1>
</div>
<div id="a">
<a style="color:white;" href = "index.php">Nazaj</a>
</div>
<table style="color:white;" width='80%' border=0>
<tr bgcolor='#07adf4'>
<td>Ime</td>
<td>Priimek</td>
<td>Datum</td>
<td>Dosje</td>
<td>Policist</td>
<td>Ažuriraj</td>
</tr>
<?php
while($res = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>".$res['ime']."</td>";
echo "<td>".$res['priimek']."</td>";
echo "<td>".$res['datum']."</td>";
echo "<td>".$res['dosje']."</td>";
echo "<td>".$res['policist']."</td>";
echo "<td><a style=\"color:white;\" href=\"Azuriranje.php?id=$res[id]\">Ažuriraj</a> | <a style=\"color:white;\" href=\"izbris.php?id=$res[id]\" onClick=\"return confirm('Ste prepričani, da želite izbrisati?')\">Izbriši</a></td>";
}
?>
</table>
</main>
</body>
</html>
<file_sep><?php
include("config.php");
?>
<?php
$sql = "SELECT * FROM vabilo";
if( isset($_GET['search']) ){
$priimek = mysqli_real_escape_string($mysqli, htmlspecialchars($_GET['search']));
$policist = mysqli_real_escape_string($mysqli, htmlspecialchars($_GET['search']));
$sql = "SELECT * FROM vabilo WHERE priimek LIKE '$priimek' OR policist LIKE '$policist'" ;
}
$result = $mysqli->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Iskanje vabljene osebe</title>
<style>
html, body {
max-width: 100%;
overflow-x: hidden;
}
main {
width: 80%;
height: 80%;
border: none;
position: absolute;
left: 10%;
top: 10%;
font-family: verdana;
font-size: 150px;
text-align: center;
}
#a {
top:5%;
left:80%;
position:absolute;
color:white;
font-size:25px;
}
#b {
top:40%;
left:10%;
width: 80%;
position:absolute;
color:white;
font-size:18px;
}
</style>
</head>
<body background="img/background.jpg">
<main>
<div style="top:5%; left:30%; color:white; font-size:20px; ">
<h1>Iskanje vabljene osebe</h1>
</div>
<div id="a">
<a style="color:white;" href = "index.php">Nazaj</a>
</div>
<form action="" method="GET">
<input type="text" placeholder="Vpiši priimek osebe" name="search">
<input type="submit" value="Išči" name="btn">
</form>
</main>
<div id="b">
<table width='80%' border=0>
<tr bgcolor='#07adf4'>
<td>Ime</td>
<td>Priimek</td>
<td>Datum</td>
<td>Dosje</td>
<td>Policist</td>
</tr>
<?php
while($row = $result->fetch_assoc()){
echo "<tr>";
echo "<td>".$row['ime']."</td>";
echo "<td>".$row['priimek']."</td>";
echo "<td>".$row['datum']."</td>";
echo "<td>".$row['dosje']."</td>";
echo "<td>".$row['policist']."</td>";
}
?>
</table>
</div>
</body>
</html><file_sep><?php
session_start();
session_destroy();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Evidenca vabljenih oseb 2018</title>
<style>
html, body {
max-width: 100%;
overflow-x: hidden;
}
main {
width: 80%;
height: 80%;
border: none;
position: absolute;
left: 10%;
top: 10%;
font-family: verdana;
font-size: 150px;
text-align: center;
}
#povezava1 {
position:absolute;
top:5%;
right:40%;
width:40%;
font-size:30px;
cursor: pointer;
}
#povezava2 {
position:absolute;
top:15%;
right:40%;
width:40%;
font-size:30px;
cursor: pointer;
}
#povezava3 {
position:absolute;
top:25%;
right:40%;
width:40%;
font-size:30px;
cursor: pointer;
}
#povezava4 {
position:absolute;
top:35%;
right:40%;
width:40%;
font-size:30px;
cursor: pointer;
}
</style>
</head>
<body background="img/background.jpg">
<main>
<div id="povezava1">
<a style="color:white" href = "VnosO.php">Vnos vabljene osebe</a>
</div>
<div id="povezava2">
<a style="color:white" href = "Iskanje.php">Iskanje vabljene osebe</a>
</div>
<div id="povezava3">
<a style="color:white" href = "prikaz.php">Prikaz vseh vabljenih oseb</a>
</div>
</main>
</body>
</html>
<file_sep><html>
<head>
<title>Vnos vabljene osebe</title>
</head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<body>
<?php
include_once("config.php");
if(isset($_POST['Submit'])) {
$ime = mysqli_real_escape_string($mysqli, $_POST['ime']);
$priimek = mysqli_real_escape_string($mysqli, $_POST['priimek']);
$datum = mysqli_real_escape_string($mysqli, $_POST['datum']);
$dosje = mysqli_real_escape_string($mysqli, $_POST['dosje']);
$policist = mysqli_real_escape_string($mysqli, $_POST['policist']);
if(empty($ime) || empty($priimek) || empty($datum) || empty($dosje) || empty($policist)) {
if(empty($ime)) {
echo "<font color='red'>Potrebno vpisati IME.</font><br/>";
}
if(empty($priimek)) {
echo "<font color='red'>Potrebno vpisati PRIIMEK.</font><br/>";
}
if(empty($datum)) {
echo "<font color='red'>Potrebno vpisati DATUM.</font><br/>";
}
if(empty($dosje)) {
echo "<font color='red'>Potrebno vpisati DOSJE.</font><br/>";
}
if(empty($policist)) {
echo "<font color='red'>Potrebno vpisati POLICISTA.</font><br/>";
}
echo "<br/><a href='javascript:self.history.back();'>Nazaj</a>";
} else {
$result = mysqli_query($mysqli, "INSERT INTO vabilo (ime, priimek, datum, dosje, policist) VALUES ('$ime', '$priimek', '$datum', '$dosje', '$policist')");
echo "<font color='blue'>Vnos vabljene osebe je uspel.";
echo "<br/><a href='prikaz.php'>Prikaži vse vabljene osebe</a>";
echo "<br/><a href='VnosO.php'>Vnesi novo vabljeno osebo</a>";
}
}
?>
</body>
</html>
<file_sep><?php
session_start();
session_destroy();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Vnos vabljene osebe</title>
<style>
html, body {
max-width: 100%;
overflow-x: hidden;
}
main {
width: 80%;
height: 80%;
border: none;
position: absolute;
left: 10%;
top: 10%;
font-family: verdana;
font-size: 150px;
text-align: center;
}
#a {
top:5%;
left:80%;
position:absolute;
color:white;
font-size:25px;
}
#b {
top:30%;
left:42%;
position:absolute;
color:white;
font-size:18px;
}
</style>
</head>
<body background="img/background.jpg">
<main>
<div style="top:5%; left:30%; color:white; font-size:20px; ">
<h1>Vnos vabljene osebe</h1>
</div>
<div id="a">
<a style="color:white;" href = "index.php">Nazaj</a>
</div>
</main>
<div id="b">
<form action="dodaj.php" method="post" name="obrazec1">
<table>
<tr>
<td>Ime</td>
<td><input type="text" name="ime"></td>
</tr>
<tr>
<td>Priimek</td>
<td><input type="text" name="priimek"></td>
</tr>
<tr>
<td>Datum</td>
<td><input type="date" name="datum"></td>
</tr>
<tr>
<td>Dosje</td>
<td><input type="int" name="dosje"></td>
</tr>
<tr>
<td>Policist</td>
<td><input type="text" name="policist"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Dodaj"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
| d9385978922490befa525377e1c5f0c6b5e574eb | [
"SQL",
"PHP"
] | 7 | PHP | furchy/Vabljenje2018 | 28115ad1debf246325eac37ea1bfa6f7a11e6256 | 0a8497ea6e8f53101ad425dff27e3bc18ec4ff04 |
refs/heads/master | <repo_name>colombia9503/Posgrados<file_sep>/public/javascripts/app.js
(function(angular){
'use strict';
angular.module('tesisApp',['ngRoute'])
.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider){
$routeProvider
.when('/agregar', {
templateUrl: 'Plantillas/agregar.html'
})
.when('/enviar', {
templateUrl: 'Plantillas/enviarInvitacion.html'
})
.when('/gestionar', {
templateUrl: 'Plantillas/gestionarEvaluadores.html'
})
.when ('/presentar',{
templateUrl: 'Plantillas/presentarPropuesta.html'
})
.when ('/radicar',{
templateUrl: 'Plantillas/radicar.html',
controller: 'radicarController'
})
.otherwise({
redirectTo:'/'
});
$locationProvider.html5Mode(true);
}])
//mucho el imbecil yo pas
//esta es la version del angular 1.3, ojo se confunden de como+
//crear los controladores de las vistas
//pero reciben los mismo parametros
//esos son los scopes para hacer los requests a las cosas
.controller('radicarController', ["$scope", '$http', function($scope, $http){
//post de propuestas
console.log("controlador de propuestas");
$scope.addPropuesta = function(){
$http.post('/propuestas', $scope.propuesta).success(function(response){
console.log(response);
//limpiar campos
$scope.propuesta = "";
});
}
}])
.controller('MainCtrl',["$scope",function($scope){
$scope.botones={
prueba:[{
nombre: "Agregar Usuario",
url:"/agregar"
},{
nombre: "Radicar Propuesta",
url:"/radicar"
}, {
nombre: "Confirmar Invitaciones",
url:"/confirmar"
},{
nombre: "Enviar Invitaciones",
url:"/enviar"
},{
nombre: "Gestionar Evaluadores",
url:"/gestionar"
},{
nombre: "Presentar Propuesta",
url:"/presentar"
}],
estudiante:[{
nombre: "<NAME>",
url:"/presentar"
},{
nombre: "<NAME>",
url:"/radicar"
},{
nombre: "<NAME>",
url:"/radicar"
}],
calificador:[]
};
}])
})(window.angular);
| 5f13486117b4c229459d806391a61181b0389b31 | [
"JavaScript"
] | 1 | JavaScript | colombia9503/Posgrados | 3a1bc46e488fe3f0dbdcc42ec5364eac06967c0f | abaf432a0904c1ba16eba113e43011f8cdbeb698 |
refs/heads/master | <file_sep>package com.example.recyclerviewitemfocus
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val topics = listOf("Education","Finance","Government","Entertainment","Technology","Math","Biology","Physics","Chemistry","Space","Sports","Music","Animal","Countries","Weather","Politics","Traffic","Poverty","Social Media","Internet","Housing")
val linearLayoutManager = LinearLayoutManager(this)
val listAdapter = ItemListAdapter(topics)
recycler_view.setHasFixedSize(true)
recycler_view.layoutManager = linearLayoutManager
recycler_view.adapter = listAdapter
}
}
<file_sep>package com.example.recyclerviewitemfocus
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
class ItemListAdapter(private val itemList: List<String>) : RecyclerView.Adapter<ItemListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutView = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
return ViewHolder(layoutView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.tvTopic.text = itemList[position]
}
override fun getItemCount() = itemList.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
var tvTopic: TextView
init {
itemView.setOnClickListener(this)
tvTopic = itemView.findViewById<View>(R.id.topic) as TextView
}
override fun onClick(view: View) {
Toast.makeText(view.context, "Clicked Position = " + adapterPosition, Toast.LENGTH_SHORT).show()
}
}
}<file_sep># Android recyclerview item focus selection with selector drawable
https://www.codexpedia.com/android/android-recyclerview-item-focus-selection-on-dpad-navigation/
<img src="https://github.com/codexpedia/android_recyclerview_item_focus_selection/blob/master/captures/focus-selection.gif" width="250" height="420" />
| 7018147eaae1449f7f8fbfa58db34caa14cb3e04 | [
"Markdown",
"Kotlin"
] | 3 | Kotlin | codexpedia/android_recyclerview_item_focus_selection | 9b61779b17c007c76ac8125c79778942fcaf7834 | 77d55c29ba0b3f5a551b65172f6097f70fdb71f0 |
refs/heads/master | <file_sep>var slack = require("../../../slack_notify.js");
module.exports = {};
var report = module.exports.report = function(message) {
console.log("SOCKET.IO", message);
slack.notify(message, 'UEDJRTBEZ');
}
var blankStrings = ["null", "undefined", ""];
var isBlank = module.exports.isBlank = function(obj) {
if (Array.isArray(obj)) {
var hasBlank = false;
for (var item in obj) {
if (isBlank(obj[item])) hasBlank = true;
}
return hasBlank;
} else {
return (typeof obj === "undefined") || (obj === null) || (blankStrings.indexOf(obj) >= 0);
}
}
var toString = module.exports.toString = function(obj) {
if (Array.isArray(obj)) {
return JSON.stringify(obj);
} else if (isBlank(obj)) {
if (typeof obj === "undefined") {
return "undefined";
} else if (obj === null) {
return "null";
} else {
return '"' + obj + '"';
}
} else {
return JSON.stringify(obj);
}
}
module.exports.reportIfBlank = function(obj, message) {
if (isBlank(obj)) {
report(message + ", value is: " + toString(obj));
}
}
<file_sep>rm -rf ~/bigmarker.webrtc/node_modules/socket.io
cd ~/bigmarker.webrtc && npm install<file_sep>DIR=$(dirname $(realpath $0))
rm -rf ~/bigmarker.webrtc/node_modules/socket.io
cp -r $DIR ~/bigmarker.webrtc/node_modules/socket.io
cd ~/bigmarker.webrtc/node_modules/socket.io && npm install | 26122649492613d163b7160665fedb0ac86e2a72 | [
"JavaScript",
"Shell"
] | 3 | JavaScript | samuelokrent/socket-io-debug | 073596294f6a41609bd77e51e8e84d1c9c6dc2c5 | 3914b0824e07b5b2b174f14ebda3074886826ee7 |
refs/heads/master | <file_sep>Shindo.tests('Fog::Compute[:ibm] | image', ['ibm']) do
@image_id = '20010001'
@image = Fog::Compute[:ibm].images.get(@image_id)
tests('success') do
end
end
| 7636fb1cbb6aa05b76a066aea0fe64e84d4fc479 | [
"Ruby"
] | 1 | Ruby | dillards/fog | 4e2619a3e8d68b8faeeb41eb5f30175d930af5b1 | 320d7b05c36fae03067482d840423522c8693510 |
refs/heads/master | <file_sep>module GemsHelper
def has_dependencies?(gem)
gem['dependencies']['development'].empty?
end
end
<file_sep>class StaticPagesController < ApplicationController
def root
end
def favorites
end
def search
respond_to do |format|
begin
@gem = Gems.info params[:search]
rescue JSON::ParserError
format.js { render action: 'gemnotfound' }
end
format.html { redirect_to :back }
format.js
end
end
end
<file_sep>$(function() {
// Load favorite gems on page load if any
let gems = JSON.parse(localStorage.getItem("gems")) || []
// Save or remove gem on click
$('#search_area').on('click', '.favorite', function() {
// Retrieve the name of gem clicked
const thisGem = $(this).attr('id');
const removeGem = gem => {
let index = gems.indexOf(gem);
if (index > -1) {
gems.splice(index, 1)
}
}
const addGem = gem => {
gems.push(gem);
}
const starred = gem => {
if (gems.includes(gem)) {
return '/assets/star-gray';
} else {
return '/assets/star-blue';
}
}
// Check if gem is saved or not, render correct star-image
$(this).attr('src', starred(thisGem));
// Decide if gem should be deleted or added
gems.includes(thisGem) ? removeGem(thisGem) : addGem(thisGem)
// Save gem to browser
localStorage.setItem("gems", JSON.stringify(gems));
});
const displayFavorites = () => {
// Display saved gems to favorites page
// If no gems, display message
if(gems.length === 0) {
$('.favorite-gems').append('<p class="text-capitalize text-muted">none</p>');
} else {
// Create and populate table data to page
let html = '<tr>';
for(let i = 0; i < gems.length; i++) {
if(i > 0 && i % 3 == 0) {
html += '</tr>';
}
html += `<td><img src=/assets/star-blue class=favorite id=${gems[i]}> <a href=https://rubygems.org/gems/${gems[i]}>${gems[i]}</a></td>`;
}
html += '</tr>';
$('.table').append(html);
}
}
displayFavorites();
})
| b7de205188b3f6cb3175055f6d45b11fb362b5a7 | [
"JavaScript",
"Ruby"
] | 3 | Ruby | edwincarbajal/growth-team-developer-test | 5c7e760095c00e7485f06a9047f2b235ddf79fa3 | 8bb203041eb5499654cdd42cbaef379f5ab4821a |
refs/heads/master | <repo_name>wonkeunchoi/Left4Dead<file_sep>/src/Dead/Battle.java
package Dead;
import java.util.Scanner;
import 글.스토리1;
public class Battle {
public Battle(Zombie enemy, 사람 self) {
Scanner scanner = new Scanner(System.in);
System.out.println("|| 1.싸운다 | 2.남성좀비의 정보를 확인한다 | 3.SafeZone 이동 | 4. 인벤토리 | || ");
int 배틀 = scanner.nextInt();
if(배틀 == 1) {
System.out.println("싸운다를 선택하셨습니다.");
System.out.println();
enemy.일반공격(self,enemy);
self.상태();
self.공격(enemy);
enemy.상태();
if(enemy.HP == 0) {
System.out.println("⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎");
System.out.println();
System.out.println("전투에서 승리하셨습니다!!");
System.out.println();
System.out.println("⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎⚔︎");
}
}
}
}
<file_sep>/src/Dead/Map.java
package Dead;
public class Map {
int 컨티션상승;
int 컨디션감소;
//오류
void 좀비등장(Zombie zombie) {
System.out.println("☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎");
System.out.println();
System.out.println(zombie.name+"가 등장하였습니다!!");
System.out.println();
System.out.println("☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎☣︎");
}
void 보스등장(Boss boss) {
System.out.println("☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎!!!위험!!!☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎");
System.out.println();
System.out.println(" 💀보스"+boss.name+"가 출현하였습니다!💀");
System.out.println();
boss.보스정보();
System.out.println();
System.out.println("☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎☠︎");
}
}
<file_sep>/src/Dead/Zombie.java
package Dead;
public class Zombie extends 유닛{
String 스킬;
int 스킬데미지;
public Zombie(String name,int HP,int Attack,int Speed,int 크리티컬,String 특징,String 스킬,int 스킬데미지){
super();
this.name = name;
this.HP = HP;
this.Attack = Attack;
this.Speed = Speed;
this.크리티컬 = 크리티컬;
this.특징 = 특징;
this.스킬 = 스킬;
this.스킬데미지 = 스킬데미지;
}
void 일반공격(사람 self, Zombie enemy){
System.out.println();
System.out.println(enemy.name+"가 생존자를 공격하였습니다!");
self.HP -= Attack;
if(self.HP < 0 || self.HP == 0) {
self.HP = 0;
System.out.println(self.name+"가 사망하였습니다.");
System.out.println("The End....");
}
}
}
<file_sep>/src/Dead/Boss.java
package Dead;
import java.util.Random;
public class Boss extends Zombie{
int 방어력;
String 스킬2;
int 스킬데미지2;
public Boss(String name, int HP, int Attack, int Speed, int 크리티컬, String 특징, String 스킬, int 스킬데미지,String 스킬2,int 스킬데미지2) {
super(name, HP, Attack, Speed, 크리티컬, 특징, 스킬, 스킬데미지);
this.스킬2 = 스킬2;
this.스킬데미지2 = 스킬데미지2;
}
void 보스정보() {
System.out.println();
System.out.println("=============="+name+"의 정보=============");
System.out.println();
System.out.println(name+"의 생명력 : "+ HP );
System.out.println(name+"의 일반공격 : " + Attack);
System.out.println(name+"의 속도 : "+ Speed);
System.out.println(name+"의 특징 : "+ 특징);
System.out.println();
System.out.println(name+"의 스킬1 :"+ 스킬);
System.out.println(name+"의 스킬데미지 :"+ 스킬데미지);
System.out.println(name+"의 스킬2 :"+ 스킬2);
System.out.println(name+"의 스킬데미지2 :"+ 스킬데미지2);
System.out.println();
System.out.println("=====================================");
}
void 보스공격 (사람 enemy) {
System.out.println();
System.out.println(name+"가 생존자를 공격하였습니다!");
enemy.HP -= Attack;
}
void 보스스킬1 (사람 enemy) {
System.out.println();
System.out.println(name+" 이(가)"+스킬+"을(를) 사용하였습니다!");
System.out.println(name+"가 생존자를 공격하였습니다!");
enemy.HP -= Attack;
}
void 연타(사람 enemy) {
enemy.HP -= 10;
System.out.println("위치의 연타공격");
System.out.println(enemy.HP);
}
/*void 랜덤값() {
Random random = new Random();
System.out.println(random.nextInt(10));
Boss. = random.nextInt(10);
} */
void 연타공격(사람 enemy) { // 위치스킬
while(enemy.HP > 30) {
if(Math.random() < 0.8) {
enemy.HP -= 8;
System.out.println("데미지 -8");
System.out.println(enemy.name+"의 HP : "+enemy.HP);
if(Math.random() < 0.7) {
enemy.HP -= 10;
System.out.println("데미지 -10");
System.out.println(enemy.name+"의 HP : "+enemy.HP);
}
}
else {
System.out.println("위치의 공격에서 벗어나셨습니다!");
break;
}
}
}
}
<file_sep>/src/글/스토리1.java
package 글;
import java.util.Scanner;
public class 스토리1 {
public 스토리1() {
Scanner scanner = new Scanner(System.in);
System.out.println();
System.out.println("=============================");
System.out.println(" 프로그램을 시작합니다.");
System.out.println();
System.out.println("Enter 입력시 다음내용이 출력됩니다. ");
System.out.println("=============================");
scanner.nextLine();
System.out.println("⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑🇰🇷🇰🇷🇰🇷⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑");
System.out.println("⚑");
System.out.println("⚑ 스토리 🔈 ");
System.out.println("⚑ ");
System.out.println("⚑ 현재시간 2040년 4월24일. 내 이름은 유진.. 박사이다.");
System.out.println("⚑ 2038년 7월에 발생했던 '박테리오파지 N-41' 바이러스가 퍼진 이후로 부터 현재 세계 사람들은 그것으로 변화되었다.");
System.out.println("⚑ 우리는 그것을 좀비라 부른다..");
System.out.println("⚑ 2040년 4월24일인 오늘 마침내 나는 백신제조에 성공하였다. ");
System.out.println("⚑ 하지만 재료가 부족하여 백신의 양은 극소수.. 이것으로는 턱이 없다.");
System.out.println("⚑ 우리는 말레이시아 🇲🇾 에 위치해 있는 한 의료센터에서 백신을 대량으로 생산할 수 있는 장비가 있다는 것을 확인하였다");
System.out.println("⚑ 문제는 말레이시아 🇲🇾가 경계위험도 A급 지역이라는 것이다.. ");
System.out.println("⚑ 방도는 없다, 이 백신을 만들 수 있는 것은 나 하나뿐 생존자도 몇 남지 않았다.");
System.out.println("⚑ 내가 직접 그 길을 나설 수 밖에는..");
System.out.println("⚑");
System.out.println("⚑");
System.out.println("⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑⚑");
System.out.println();
System.out.println("박사가 헬리콥터에 탑승하는 중... 쓰레드 구현");
System.out.println("Please Press the Enter Key");
// 쓰레드 구현 : 박사가 헬리콥터에 탑승하는 중......
scanner.nextLine();
System.out.println("👤 헬리콥터 조종사 : 박사님 ! A급 지역에 도착하였습니다!");
System.out.println("👤 헬리콥터 조종사 : 목표 지점까지 20분 남았습니다.");
System.out.println();
System.out.println("👨🏻⚕️ 유진 박사 : 그렇구만 끝까지 수고 해주시게!");
System.out.println(" 밑을 바라본다...");
System.out.println();
System.out.println("👨🏻⚕️ 유진 박사 : 엄청난 수의 감염자들이구만.. 지옥을 보는 것만 같아..");
System.out.println();
System.out.println("어디선가 헬리콥터를 향해 돌덩어리가 날라온다..");
System.out.println("맞았다 추락한다..");
System.out.println("👤 헬리콥터 조종사 : 비상!! 비상!! 알 수 없는 무언가에 맞아 헬리콥터가 손상을 입어 추락합니다!!");
System.out.println("👤 헬리콥터 조종사 : 낙하산을 피셔야 합니다!!");
}
}
<file_sep>/src/Dead/좀비킬러.java
package Dead;
public class 좀비킬러 {
}
| c82ef692f1a2e0aeb799903a502b0e4714a40564 | [
"Java"
] | 6 | Java | wonkeunchoi/Left4Dead | 64c068dc446ab1d8f031939d62dadcd354af9e07 | 15e7c312f3a3e9fd9c82fa126ace5783e73f47f3 |
refs/heads/master | <file_sep><?php
$result = '';
if(isset($_POST['submit'])){
if(isset($_POST["birthday"])){
$birthday = new DateTime($_POST['birthday']);
$now = new DateTime();
$interval = $now->diff($birthday);
$result = 'You Birth date is: '.$_POST['birthday']. '<br>'. $interval->y. ' years, ' . $interval->m . ' Month(s), '. $interval->d .' days ';
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Age Calculator</title>
<style>
body{
background: #f5f5f5;
}
.form{
text-align: center;
margin-top: 200px;
}
.result{
margin-top: 20px;
font-size: 35px;
text-align: center;
color: green;
}
</style>
</head>
<body>
<div class="form">
<form action="" method="post">
<input type="date" name="birthday">
<button type="submit" name="submit">Submit</button>
</form>
</div>
<div class="result">
<?php echo $result; ?>
</div>
</body>
</html><file_sep><?php
/**
* Created by PhpStorm.
* User: primez
* Date: 2/3/17
* Time: 10:22 AM
*/ | 3b2922dabe4096ebcff26cd4560d2023397f1e34 | [
"PHP"
] | 2 | PHP | abdurrahmanriyad/Basic-PHP | f8ba7ab2a1f2c3dcf2e6d560608849f369f66d48 | 13afcfe6e49275f500971bbeabfac89ec99e2b36 |
refs/heads/master | <repo_name>linzhibo/superpoint_visual_odom<file_sep>/superPointNet.py
import glob
import numpy as np
import os
import time
import cv2
import torch
myjet = np.array([[0. , 0. , 0.5 ],
[0. , 0. , 0.99910873],
[0. , 0.37843137, 1. ],
[0. , 0.83333333, 1. ],
[0.30044276, 1. , 0.66729918],
[0.66729918, 1. , 0.30044276],
[1. , 0.90123457, 0. ],
[1. , 0.48002905, 0. ],
[0.99910873, 0.07334786, 0. ],
[0.5 , 0. , 0. ]])
class SuperPointNet(torch.nn.Module):
"""docstring for SuperPointNet"""
def __init__(self, arg):
super(SuperPointNet, self).__init__()
self.relu = torch.nn.ReLU(inplace = True)
self.pool = torch.nn.MaxPool2d(kernel_size=2, stride=2)
c1, c2, c3, c4, c5, d1 = 64, 64, 128, 128, 256, 256
# Shared Encoder.
self.conv1a = torch.nn.Conv2d(1, c1, kernel_size=3, stride=1, padding=1)
self.conv1b = torch.nn.Conv2d(c1, c1, kernel_size=3, stride=1, padding=1)
self.conv2a = torch.nn.Conv2d(c1, c2, kernel_size=3, stride=1, padding=1)
self.conv2b = torch.nn.Conv2d(c2, c2, kernel_size=3, stride=1, padding=1)
self.conv3a = torch.nn.Conv2d(c2, c3, kernel_size=3, stride=1, padding=1)
self.conv3b = torch.nn.Conv2d(c3, c3, kernel_size=3, stride=1, padding=1)
self.conv4a = torch.nn.Conv2d(c3, c4, kernel_size=3, stride=1, padding=1)
self.conv4b = torch.nn.Conv2d(c4, c4, kernel_size=3, stride=1, padding=1)
# Detector Head.
self.convPa = torch.nn.Conv2d(c4, c5, kernel_size=3, stride=1, padding=1)
self.convPb = torch.nn.Conv2d(c5, 65, kernel_size=1, stride=1, padding=0)
# Descriptor Head.
self.convDa = torch.nn.Conv2d(c4, c5, kernel_size=3, stride=1, padding=1)
self.convDb = torch.nn.Conv2d(c5, d1, kernel_size=1, stride=1, padding=0)
def forward(self, x):
# Shared Encoder.
x = self.relu(self.conv1a(x))
x = self.relu(self.conv1b(x))
x = self.pool(x)
x = self.relu(self.conv2a(x))
x = self.relu(self.conv2b(x))
x = self.pool(x)
x = self.relu(self.conv3a(x))
x = self.relu(self.conv3b(x))
x = self.pool(x)
x = self.relu(self.conv4a(x))
x = self.relu(self.conv4b(x))
cPa = self.relu(self.convPa(x))
detec = self.convPb(cPa)
cDa = self.relu(self.convDa(x))
desc = self.convDb(cDa)
dn = torch.norm(desc, p=2, dim=1)
desc = desc.div(torch.unsqueeze(dn, 1))
return detec, desc
class SuperPointFrontend(object):
def __init__(self, weights_path, nms_dist, conf_thresh, nn_thresh, cuda=True):
self.name = 'SuperPoint'
self.cuda = cuda
self.nms_dist = nms_dist
self.conf_thresh = conf_thresh
self.nn_thresh = nn_thresh
self.cell = 8
self.border_remove = 4
self.net = SuperPointNet()
self.net.load_state_dict(torch.load(weights_path))
self.net = self.net.cuda()
self.net.eval()
def nms_fast(self, in_corners, H, W, dist_thresh):
grid = np.zeros((H,W)).astype(int)
inds = np.zeros((H,W)).astype(int)
inds1 = np.argsort(-in_corners[2,:])
corners = in_corners[:, inds1]
rcorners = corners[:2,:].round().astype(int)
if rcorners.shape[1] == 0:
return np.zeros((3,0)).astype(int), np.zeros(0).astype(int)
if rcorners.shape[1] == 1:
return out, np.zeros((1)).astype(int)
for i, rc in enumerate(rcorners.T):
grid[rcorners[1,i], rcorners[0,i]] = 1
inds[rcorners[1,i], rcorners[0,i]] = i
pad = dist_thresh
grid = np.pad(grid, ((pad, pad), (pad, pad)), mode = 'constant')
count = 0
for i, rc in enumerate(rcorners.T):
pt = (rc[0] + pad, rc[1] + pad)
if grid[pt[1], pt[0]] == 1:
grid[pt[1]-pad:pt[1]+pad+1, pt[0]-pad:pt[0]+pad+1] = 0
grid[pt[1], pt[0]] = -1
count +=1
keepy, keepx = np.where(grid==-1)
keepy, keepx = keepy - pad, keepx - pad
inds_keep = inds[keepy, keepx]
out = corners[:,inds_keep]
values = out[-1, :]
inds2 = np.argsort(-values)
out = out[:, inds2]
out_inds = inds1[inds_keep[inds2]]
return out, out_inds
def run(self):
assert img.ndim == 2, 'Image must be grayscale.'
assert img.dtype == np.float32, 'Image must be float32.'
H, W = img.shape[0], img.shape[1]
inp = img.copy()
inp = (inp.reshape(1, H, W))
inp = torch.from_numpy(inp)
inp = torch.autograd.Variable(inp).view(1, 1, H, W)
if self.cuda:
inp = inp.cuda()
# Forward pass of network.
outs = self.net.forward(inp)
semi, coarse_desc = outs[0], outs[1]
# Convert pytorch -> numpy.
semi = semi.data.cpu().numpy().squeeze()
# --- Process points.
dense = np.exp(semi) # Softmax.
dense = dense / (np.sum(dense, axis=0)+.00001) # Should sum to 1.
# Remove dustbin.
nodust = dense[:-1, :, :]
# Reshape to get full resolution heatmap.
Hc = int(H / self.cell)
Wc = int(W / self.cell)
nodust = nodust.transpose(1, 2, 0)
heatmap = np.reshape(nodust, [Hc, Wc, self.cell, self.cell])
heatmap = np.transpose(heatmap, [0, 2, 1, 3])
heatmap = np.reshape(heatmap, [Hc*self.cell, Wc*self.cell])
xs, ys = np.where(heatmap >= self.conf_thresh) # Confidence threshold.
if len(xs) == 0:
return np.zeros((3, 0)), None, None
pts = np.zeros((3, len(xs))) # Populate point data sized 3xN.
pts[0, :] = ys
pts[1, :] = xs
pts[2, :] = heatmap[xs, ys]
pts, _ = self.nms_fast(pts, H, W, dist_thresh=self.nms_dist) # Apply NMS.
inds = np.argsort(pts[2,:])
pts = pts[:,inds[::-1]] # Sort by confidence.
# Remove points along border.
bord = self.border_remove
toremoveW = np.logical_or(pts[0, :] < bord, pts[0, :] >= (W-bord))
toremoveH = np.logical_or(pts[1, :] < bord, pts[1, :] >= (H-bord))
toremove = np.logical_or(toremoveW, toremoveH)
pts = pts[:, ~toremove]
# --- Process descriptor.
D = coarse_desc.shape[1]
if pts.shape[1] == 0:
desc = np.zeros((D, 0))
else:
# Interpolate into descriptor map using 2D point locations.
samp_pts = torch.from_numpy(pts[:2, :].copy())
samp_pts[0, :] = (samp_pts[0, :] / (float(W)/2.)) - 1.
samp_pts[1, :] = (samp_pts[1, :] / (float(H)/2.)) - 1.
samp_pts = samp_pts.transpose(0, 1).contiguous()
samp_pts = samp_pts.view(1, 1, -1, 2)
samp_pts = samp_pts.float()
if self.cuda:
samp_pts = samp_pts.cuda()
desc = torch.nn.functional.grid_sample(coarse_desc, samp_pts)
desc = desc.data.cpu().numpy().reshape(D, -1)
desc /= np.linalg.norm(desc, axis=0)[np.newaxis, :]
return pts, desc, heatmap
class PointTracker(object):
def __init__(self, max_length, nn_thresh):
if max_length < 2:
raise ValueError('max_length must be greater than or equal to 2')
self.maxl = max_length
self.nn_thresh = nn_thresh
self.all_pts = []
for n in range(self.maxl):
self.all_pts.append(np.zeros((2,0)))
self.last_desc = None
self.tracks = np.zeros((0, self.maxl+2))
self.track_count = 0
self.max_score = 9999
def nn_match_two_way(self, desc1, desc2, nn_thresh):
assert desc1.shape[0] == desc2.shape[0]
if desc1.shape[1]==0 or desc2.shape[1]==0:
return nn.zeros((3, 0))
if nn_thresh < 0.0:
raise ValueError('\'nn_thresh\' should be non-negative')
dmat = np.dot(desc1.T, desc2)
dmat = np.sqrt(2-2*np.clip(dmat, -1, 1))
idx = np.argmin(dmat, axis=1)
scores = dmat[np.arange(dmat.shape[0]), idx]
keep = scores < nn_thresh
idx2 = np.argmin(dmat, axis=0)
keep_bi = np.arange(len(idx)) == idx2[idx]
keep = np.logical_and(keep, keep_bi)
idx = idx[keep]
scores = scores[keep]
m_idx1 = np.arange(desc1.shape[1])[keep]
m_idx2 = idx
matches = np.zeros((3, int(keep.sum())))
matches[0, :] = m_idx1
matches[1, :] = m_idx2
matches[2, :] = scores
return matches
def get_offsets(self):
offsets = []
offsets.append(0)
for i in range(len(self.all_pts) - 1):
offsets.append(self.all_pts[i].shape[1])
offsets = np.array(offsets)
offsets = np.cumsum(offsets)
return offsets
<file_sep>/main.py
import numpy as np
import cv2
from sp_vo import VisualOdometry as sp_VisualOdometry
from sp_vo import PinholeCamera
cam = PinholeCamera(640, 480, 611.164, 609.028, 316.961, 247.770)
sp_vo = sp_VisualOdometry(cam)
traj = np.zeros((1000,1000,3), dtype = np.uint8)
log_fopen = open("results/result.txt", mode='a')
sp_errors=[]
norm_errors = []
sp_feature_nums = []
norm_feature_num = []
cv2.namedWindow('Trajectory',1)
for img_id in range(263,3606):
img_name = '/media/zhibo/storage/home/dataset/orbbec/camera/data/' + str(img_id) + '.png'
img_id = img_id - 262
img = cv2.imread(img_name, 0)
img = cv2.resize(img, (320, 240))
sp_vo.update(img, img_id)
sp_cur_t = sp_vo.cur_t
if(img_id > 2):
sp_x, sp_y, sp_z = sp_cur_t[0], sp_cur_t[1], sp_cur_t[2]
else:
sp_x, sp_y, sp_z = 0., 0., 0.
sp_img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
for(u, v) in sp_vo.px_ref:
cv2.circle(sp_img, (u,v), 3, (0, 255, 0))
# sp_est_point = np.array([sp_x, sp_y]).reshape(2)
sp_draw_x, sp_draw_y = int(sp_x) + 500, int(sp_z) + 200
cv2.circle(traj, (sp_draw_x, sp_draw_y), 1, (255, 0, 0), 1)
# cv2.rectangle(traj, (10,20), (600,60), (0,0,0), -1)
cv2.imshow('Feature detection', sp_img)
cv2.imshow('Trajectory', traj)
raw_key = cv2.waitKey(1)
if (raw_key == 27):
break
if (raw_key == 32):
continue
# live cam
# cap = cv2.VideoCapture(2)
# img_id = 0
# pauseTime = 0
# while(cap.isOpened()):
# ret, img_name = cap.read()
# # if ret is True:
# sp_img = cv2.resize(img_name, (320, 240))
# sp_vo.update(sp_img, img_id)
# sp_cur_t = sp_vo.cur_t
# if(img_id > 2):
# sp_x, sp_y, sp_z = sp_cur_t[0], sp_cur_t[1], sp_cur_t[2]
# else:
# sp_x, sp_y, sp_z = 0., 0., 0.
# # sp_img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
# for(u, v) in sp_vo.px_ref:
# cv2.circle(sp_img, (u,v), 3, (0, 255, 0))
# # sp_est_point = np.array([sp_x, sp_y]).reshape(2)
# sp_draw_x, sp_draw_y = int(sp_x) + 500, int(sp_z) + 200
# cv2.circle(traj, (sp_draw_x, sp_draw_y), 1, (255, 0, 0), 1)
# # cv2.rectangle(traj, (10,20), (600,60), (0,0,0), -1)
# print (sp_vo.cur_R)
# cv2.imshow('Feature detection', sp_img)
# cv2.imshow('Trajectory', traj)
# raw_key = cv2.waitKey(pauseTime)
# if (raw_key == 27):
# break
# if (raw_key == 32):
# pauseTime = 1
# if (pauseTime == 1):
# img_id= img_id +1
cv2.imwrite('map.png', traj)
<file_sep>/sp_vo.py
import numpy as np
import cv2
from iterative_closest_point import ICP_matching, SVD_motion_estimation
from spn import SuperPointFrontend, PointTracker
FIRST_FRAME = 0
SECOND_FRAME = 1
DEFAULT_FRAME = 2
class PinholeCamera(object):
"""docstring for PinholeCamera"""
def __init__(self, width, height, fx, fy, cx, cy,
k1 = 0.0, k2=0.0, p1=0.0,p2=0.0,k3=0.0):
self.width = width
self.height = height
self.fx = fx
self.fy = fy
self.cx = cx
self.cy = cy
self.distortion = (abs(k1) > 0.0000001)
self.d = [k1, k2, p1, p2, k3]
class VisualOdometry():
def __init__(self, cam):
self.frame_stage = 0
self.cam = cam
self.new_frame = None
self.last_frame = None
self.cur_R = None
self.cur_t = None
self.px_ref = None
self.px_cur = None
self.focal = cam.fx
self.pp = (cam.cx, cam.cy)
self.trueX, self.trueY, self.trueZ = 0, 0, 0
self.detector = SuperPointFrontend(weights_path = "superpoint_v1.pth",
nms_dist = 4,
conf_thresh = 0.015,
nn_thresh = 0.7,
cuda = True)
self.tracker = PointTracker(max_length = 2,
nn_thresh = self.detector.nn_thresh)
# with open(annotations) as f:
# self.annotations = f.readlines()
def featureTracking(self):
pts, desc, heatmap = self.detector.run(self.new_frame)
self.tracker.update(pts, desc)
tracks = self.tracker.get_tracks(min_length = 1)
tracks[:, 1] /= float(self.detector.nn_thresh)
kp1, kp2 = self.tracker.draw_tracks(tracks)
return kp1, kp2
# def getAbsoluteScale(self, frame_id):
def processFirstFrame(self):
self.px_ref, self.px_cur = self.featureTracking()
self.frame_stage = SECOND_FRAME
def processSecondFrame(self):
self.px_ref, self.px_cur = self.featureTracking()
E, mask = cv2.findEssentialMat(self.px_cur, self.px_ref,
focal = self.focal,
pp = self.pp,
method = cv2.RANSAC,
prob = 0.999,
threshold = 1.0)
_, self.cur_R ,self.cur_t, mask = cv2.recoverPose(E, self.px_cur, self.px_ref,
focal = self.focal,
pp = self.pp)
self.frame_stage = DEFAULT_FRAME
self.px_ref = self.px_cur
def processFrame(self, frame_id):
self.px_ref, self.px_cur = self.featureTracking()
E, mask = cv2.findEssentialMat(self.px_cur, self.px_ref,
focal = self.focal,
pp = self.pp,
method = cv2.RANSAC,
prob = 0.999,
threshold = 1)
_, R, t, mask = cv2.recoverPose(E, self.px_cur, self.px_ref,
focal = self.focal,
pp = self.pp)
# t_tmp = t + self.cur_t
# distance = ((float(t_tmp[0]) - float(self.cur_t[0]))*(float(t_tmp[0]) - float(self.cur_t[0])) +
# (float(t_tmp[1]) - float(self.cur_t[1]))*(float(t_tmp[1]) - float(self.cur_t[1])) +
# (float(t_tmp[2]) - float(self.cur_t[2]))*(float(t_tmp[2]) - float(self.cur_t[2])) )
# print (distance)
# absolute_scale = pow(((t_tmp[0] - self.cur_t[0])*(t_tmp[0] - self.cur_t[0]) +
# (t_tmp[1] - self.cur_t[1])*(t_tmp[1] - self.cur_t[1]) +
# (t_tmp[2] - self.cur_t[2])*(t_tmp[2] - self.cur_t[2])),0.5)
# distance = float(t[0])*float(t[0]) + float(t[1])*float(t[1]) + float(t[2])*float(t[2])
# print(t)
# absolute_scale = pow(distance, 0.5)
absolute_scale = 1
# R, t = ICP_matching(self.px_ref,self.px_cur)
# R, t = SVD_motion_estimation(self.px_cur,self.px_ref)
self.cur_t = self.cur_t + absolute_scale* self.cur_R.dot(t)
self.cur_R = R.dot(self.cur_R)
self.px_ref = self.px_cur
def update(self, img, frame_id):
# assert(img.ndim == 2 and img.shape[0] == self.cam.height and img.shape[1] ==
# self.cam.width), "Frame: provided image has not the same size as the camera model or image is not grayscale"
self.new_frame = img
if(self.frame_stage == DEFAULT_FRAME):
self.processFrame(frame_id)
elif(self.frame_stage == SECOND_FRAME):
self.processSecondFrame()
elif(self.frame_stage == FIRST_FRAME):
self.processFirstFrame()
self.last_frame = self.new_frame
| 809b087c092fdbf601db88744a68323a8afca06c | [
"Python"
] | 3 | Python | linzhibo/superpoint_visual_odom | 1e92d48c4a9f9423381c7a4a803fd0b9da224535 | 084d3ee3b2ed0875123cd50ea676ffbdbb9d746e |
refs/heads/master | <file_sep>'use strict';
var bodyParser = require('body-parser'),
normalize = require('path').normalize,
spawn = require('child_process').spawn,
crypto = require('crypto'),
express = require('express');
module.exports = GitHooked;
/**
* Create a express app with github webhook parsing and actions
*
* @param {String} This is the git reference being listened to
* @param {String|Function} This is the action which will be invoked when the reference is called. Can be either a function that will be executed or a string which will be called from a shell
* @api public
*/
function GitHooked(ref, action, options) {
// default ref to hook and action to reference if only single args sent
// This means that all webhooks will invoke the action
if (arguments.length === 1) {
action = ref;
ref = 'hook';
}
// Defaults options to empty object
options = options || {};
// Check if options is an associative array
if ( options.toString() !== '[object Object]' ) {
throw new Error('GitHooked: Options argument supplied, but type is not an Object');
}
// create express instance
var githooked = express();
// Setup optional middleware
setupMiddleware(githooked, options);
// default bodyparser.json limit to 1mb
options.json = options.json || { limit: '1mb' };
githooked.use(bodyParser.urlencoded({ extended: false, limit: options.json.limit || '1mb' }));
// Setup secret signature validation
if ( options.secret ) {
// Throw error if secret is not a string
if ( typeof options.secret !== 'string' ) {
throw new Error('GitHooked: secret provided but it is not a string');
}
options.json.verify = function(req, res, buf) {
signatureValidation(githooked, options, req, res, buf);
};
}
// json parsing middleware limit is increased to 1mb, otherwise large PRs/pushes will
// fail due to maiximum content-length exceeded
githooked.use(bodyParser.json(options.json));
// Bind Ref, Action, and Options to Express Server
githooked.ghRef = ref;
githooked.ghAction = action;
githooked.ghOptions = options;
// main POST handler
githooked.post('/', function (req, res ) {
var payload = req.body;
// Check if ping event, send 200 if so
if (req.headers['x-github-event'] === 'ping') {
res.sendStatus(200);
return;
}
// Check if Payload was sent
if (!payload) {
githooked.emit('error', 'no payload');
return res.sendStatus(400);
}
// Check if payload has a ref, this is required in order to run contexted scripts
if (!payload.ref || typeof payload.ref !== 'string') {
githooked.emit('error', 'invalid ref');
return res.sendStatus(400);
}
// Created hook event
if (payload.created) {
githooked.emit('create', payload);
}
// Deleted hook event
else if (payload.deleted) {
githooked.emit('delete', payload);
}
// Else, default to a push hook event
else {
githooked.emit('push', payload);
}
// Always emit a global 'hook' event so people can watch all requests
githooked.emit('hook', payload);
// Emit a ref type specfic event
githooked.emit(payload.ref, payload);
res.status(202);
res.send('Accepted\n');
});
if (typeof action === 'string') {
var shell = process.env.SHELL,
args = ['-c', action],
opts = { stdio: 'inherit' };
// Windows specfic env checks
if (shell && isCygwin()) {
shell = cygpath(shell);
} else if (isWin()) {
shell = process.env.ComSpec;
args = ['/s', '/c', '"' + action + '"'];
opts.windowsVerbatimArguments = true;
}
githooked.on(ref, function() {
// Send emit spawn event w/ instance
githooked.emit('spawn', spawn(shell, args, opts));
});
}
else if (typeof action === 'function') {
githooked.on(ref, action);
}
// Development Error middleware
if ( process.env.NODE_ENV === 'development' ) {
githooked.use(function(err, req, res, next) {
console.log(err.stack);
next(err);
});
}
// Default Error middlware
githooked.use(function(err, req, res, next) { // jshint ignore:line
githooked.emit('error', err);
if ( !res.headersSent ) {
res.status(500);
res.end(err.message);
}
});
return githooked;
}
function signatureValidation(githooked, options, req, res, buf) {
// Use crypto.timingSafeEqual when available to avoid timing attacks
// See https://codahale.com/a-lesson-in-timing-attacks/
var compareStrings = function(a, b) { return a === b };
var compareSecure = function(a, b) {
return a.length === b.length && crypto.timingSafeEqual(new Buffer(a), new Buffer(b));
}
var validateSecret = crypto.timingSafeEqual ? compareSecure : compareStrings;
var providedSignature = req.headers['x-hub-signature'];
// Throw an error if secret was provided but no X-Hub-Signature header present
if ( !providedSignature ) {
res.sendStatus(401);
githooked.emit('error', 'no provider signature');
throw new Error('no provider signature');
}
var ourSignature = 'sha1=' + crypto.createHmac('sha1', options.secret).update(buf.toString()).digest('hex');
// Validate Signatures
if ( ! validateSecret(providedSignature, ourSignature) ) {
res.sendStatus(401);
githooked.emit('error', 'signature validation failed');
throw new Error('signature validation failed');
}
}
/**
* Setup middleware if options configured properly
*
* @return {Undefined}
* @api private
*/
function setupMiddleware(githooked, options) {
// Optional middleware pass
if ( options.middleware ) {
// If middleware = function, convert to array
if ( typeof options.middleware === 'function' ) {
options.middleware = [options.middleware];
}
// Add middleware
options.middleware.forEach(function(fn) {
githooked.use(fn);
});
}
}
/**
* Returns `true` if node is currently running on Windows, `false` otherwise.
*
* @return {Boolean}
* @api private
*/
function isWin () {
return 'win32' === process.platform;
}
/**
* Returns `true` if node is currently running from within a "cygwin" environment.
* Returns `false` otherwise.
*
* @return {Boolean}
* @api private
*/
function isCygwin () {
// TODO: implement a more reliable check here...
return isWin() && /cygwin/i.test(process.env.HOME);
}
/**
* Convert a Unix-style Cygwin path (i.e. "/bin/bash") to a Windows-style path
* (i.e. "C:\cygwin\bin\bash").
*
* @param {String} path
* @return {String}
* @api private
*/
function cygpath (path) {
path = normalize(path);
if (path[0] === '\\') {
// TODO: implement better cygwin root detection...
path = 'C:\\cygwin' + path;
}
return path;
}
<file_sep>1.1.2 / 2017-11-30
==================
* Validate secret using a constant-time comparison to avoid timing attacks.
1.1.1 / 2015-02-06
==================
* Added secret option for payload validation
1.0.4 / 2015-01-22
==================
* Added the ability for ping events to be properly responded to
1.0.3 / 2015-01-22
==================
* Create basic BDD test coverage
* Added Body Parser JSON limit to be 1mb
0.1.0 / 2014-09-16
==================
* Bump dependency versions.
* Correctly handle both json and x-www-form-urlencoded payloads.
0.0.2 / 2013-05-16
==================
* Implement initial Windows and Cygwin support
0.0.1 / 2013-04-22
==================
* Initial Release
<file_sep>'use strict';
var assert = require('assert'),
cp = require('child_process'),
path = require('path'),
getport = require('getport'),
request = require('superagent'),
cli = path.resolve(__dirname + '/../bin/githooked');
describe('githooked cli', function() {
it('should return help if no action is provided with exit code 1', function(done){
cp.exec(cli + ' -p 3965', function(err) {
assert.equal(err.code, 1);
done();
});
});
// 1.0.0 backwords compat to calling actions
// Wow, need to find a better way to test CLIs that start a server
it('should it should start a server and accept requests', function(done) {
var gh;
getport(function(err, port) {
if ( err ) { done(err); }
// The pain difference in the following test is how actions (-a) are passed to githooked cli
gh = cp.spawn(cli, ['-p', port, '-r', 'test', '-a', 'echo "THIS IS A TEST"']);
var buf = '',
started = false;
gh.stdout.on('data', function(chunk) {
buf += chunk;
if ( !started && buf.match('githooked server started') ) {
started = true;
webhookCaller(port, done);
}
});
gh.on('error', function(chunk) {
done(new Error(chunk));
});
});
// Cleanup
after(function() {
gh.kill();
});
});
it('should support the action being undefined commander args', function(done) {
var gh;
getport(function(err, port) {
if ( err ) { done(err); }
gh = cp.spawn(cli, ['-p', port, '-r', 'test', 'echo "THIS IS A TEST"']);
var buf = '',
started = false;
gh.stdout.on('data', function(chunk) {
buf += chunk;
if ( !started && buf.match('githooked server started') ) {
started = true;
webhookCaller(port, done);
}
});
gh.on('error', function(chunk) {
done(new Error(chunk));
});
});
// Cleanup
after(function() {
gh.kill();
});
});
});
function webhookCaller(port, cb) {
request
.post('localhost:' + port + '/')
.set('Content-Type', 'application/json')
.send({ ref: 'test' })
.end(function(err, res) {
if ( res.status === 202 ) {
cb();
}
});
}
<file_sep>#!/usr/bin/env node
'use strict';
var fs = require('fs'),
path = require('path'),
program = require('commander');
program
.version(JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf-8')).version)
.usage('-p 3000 -r \'refs/heads/master\' -a \'git pull && npm run build\'')
.option('-a, --hookaction <n>', 'Shell command which will be executed on webhook event (required)')
.option('-p, --port <n>', 'Port number to listen to (defaults to 3000)', parseInt)
.option('-r, --ref <n>', 'Ref to look for (defaults to all refs)')
.option('-s, --secret <n>', 'Secret used to verify payload signature')
.parse(process.argv);
var githooked = require('../lib');
if (!program.hookaction && program.args.length === 0) {
console.log('\n No action provided!');
program.outputHelp();
process.exit(1);
}
var action = program.hookaction || program.args.join(' '),
options = program.secret ? { secret: program.secret } : {};
githooked(program.ref || 'hook', action, options).listen(program.port || 3000, function() {
console.log('githooked server started on', this.address().port);
});
<file_sep># githooked
A GitHub webhooks worker!
[](http://travis-ci.org/ScottONeal/githooked)
**githooked** is a tiny library and companion CLI tool for handling [GitHub webhooks hooks](https://help.github.com/articles/about-webhooks/). This repo is a fork of https://github.com/coreh/hookshot and was created since the author of hookshot was innactive.
When setting up webhooks in your githooked dashboard, the types of events that should be sent to githooked should be set to: 'Just the push event'
## Examples
### Library
```javascript
var githooked = require('githooked');
githooked('refs/heads/master', 'git pull && make').listen(3000)
```
### CLI Tool
```bash
githooked -r refs/heads/master 'git pull && make'
```
## Usage
The library exposes a single function, `githooked()`. When called, this functions returns an express instance configured to handle webhooks pushes from GitHub. You can react to pushes to specific branches by listening to specific events on the returned instance, or by providing optional arguments to the `githooked()` function.
```javascript
githooked()
.on('refs/heads/master', 'git pull && make')
.listen(3000)
```
```javascript
githooked('refs/heads/master', 'git pull && make').listen(3000)
```
## Arguments
GitHooked supports up to three arguments: reference, action, and options. The first argument is the branch reference from the GitHooked webhook (i.e: `refs/heads/master`). If only one argument is supplied, it should be the action that needs to be ran. In this instance githooked will bind to every webhook event sent from GitHub.
```js
githooked('branch/references', 'action', { /* options */});
```
### Reference
References are specific webhook references or actions fired when editing tags or branches changes happen. This argument is provided so you can bind to specific branch or the following event hooks:
- **hook**: This will bind to all webhooks
- **create**: fired on [create events](https://developer.github.com/v3/activity/events/types/#createevent)
- **delete**: fired on [delete events](https://developer.github.com/v3/activity/events/types/#deleteevent)
- **push**: fired on [push events](https://developer.github.com/v3/activity/events/types/#pushevent)
### Action
Actions can either be shell commands or JavaScript functions.
```javascript
githooked('refs/heads/master', 'git pull && make').listen(3000)
```
```javascript
githooked('refs/heads/master', function(info) {
// do something with push info ...
}).listen(3000)
```
### Options
Lastly, the third option is an object of configuration parameters. Usage:
```js
githooked('push', 'git pull && make', {
json: {
limit: '100mb',
strict: true
},
middleware: [
require('connect-timeout'),
function(req, res, next) {
// Do something
next();
}
]
}})
```
The following configuration options are:
#### json (Object)
These are arguments passed to express's [body-parsers json() middleware](https://github.com/expressjs/body-parser#bodyparserjsonoptions)
#### middleware (Function|Array[Function])
This is an array or function of valid [express middleware](http://expressjs.com/en/guide/using-middleware.html). This middleware will be applied before any other express middleware. If an array is provided, the middleware will be applied in the order they are declared in the array.
#### secret (String)
GitHub webhooks can pass a secret which is used as an validation mechanism between your GitHub repo and your githooked server. Read more about it [here](https://developer.github.com/v3/repos/hooks/#create-a-hook). Validation of the payload will be the first operation performed on incoming requests. If using githooked for any serious purposes this option should be necessary. If validation failed an error event will be called with value of 'signature validation failed' or 'no provider signature':
```js
githooked.on('error', function(msg) {
if ( msg === 'signature validation failed' ) {
// do something
}
})
```
#### logFile (String|stream) TODO
If your action is a shell call, then this option will log all STDOUT and STDERR into the provided stream or file descriptor
### Mounting to existing express servers
**githooked** can be mounted to a custom route on your existing express server:
```javascript
// ...
app.use('/my-github-hook', githooked('refs/heads/master', 'git pull && make'));
// ...
```
### Special Events
Special events are fired when branches/tags are created, deleted:
```javascript
githooked()
.on('create', function(info) {
console.log('ref ' + info.ref + ' was created.')
})
.on('delete', function(info) {
console.log('ref ' + info.ref + ' was deleted.')
})
```
The `push` event is fired when a push is made to any ref:
```javascript
githooked()
.on('push', function(info) {
console.log('ref ' + info.ref + ' was pushed.')
})
```
Finally, the `hook` event is fired for every post-receive hook that is send by GitHub.
```javascript
githooked()
.on('push', function(info) {
console.log('ref ' + info.ref + ' was pushed.')
})
```
### Spawn Event
If githooked was created with a shell command as the action, it will throw a spawn event with the child_process spawn instance.
```javascript
var server = githooked('refs/head/master', 'git pull && make').listen(3000);
server.on('spawn', function(spawn) {
// Bind on close to get exit code
spawn.on('close', function(code) {
if ( code !== 0 ) {
console.log('something went wrong');
}
});
});
```
### CLI Tool
A companion CLI tool is provided for convenience. To use it, install **githooked** via npm using the `-g` flag:
```bash
npm install -g githooked
```
The CLI tool takes as argument a command to execute upon GitHub post-receive hook:
```bash
githooked 'echo "PUSHED!"'
```
You can optionally specify an HTTP port via the `-p` flag (defaults to 3000) and a ref via the `-r` flag (defaults to all refs):
```bash
githooked -r refs/heads/master -p 9001 'echo "pushed to master!"'
```
<file_sep>'use strict';
var assert = require('assert'),
supertest = require('supertest'),
githooked = require('../lib'),
crypto = require('crypto');
process.env.NODE_ENV = 'test';
describe('githooked initialization', function() {
var server, request;
beforeEach(function() {
server = githooked('test', 'exit 1');
request = supertest(server);
});
it('should have property githookedServer.ghRef', function() {
assert.equal(server.ghRef, 'test');
});
it('should have property githookedServer.ghAction', function() {
assert.equal(server.ghAction, 'exit 1');
});
it('should have property githookedServer.ghOptions', function() {
var options = { json: '10mb', logFile: './goothoked.log' };
var scopedServer = githooked('test', 'exit 1', options);
assert.equal(scopedServer.ghOptions, options);
});
it('defaults action to first argument if only one argument sent', function() {
var scopedServer = githooked('exit 1');
assert(scopedServer);
});
it('should throw an error when if option argument is not an object', function() {
assert.throws(function() {
githooked('test', 'exit 1', []);
}, Error);
});
it('should accept bodyParser.json middleware options', function(done) {
var scopedServer = githooked('test', 'exit 1', { json: { limit: '1kb'}});
var buf = new Buffer(1024);
buf.fill('.');
supertest(scopedServer)
.post('/')
.set('Content-Type', 'application/json')
.send(JSON.stringify({ str: buf.toString() }))
.expect(413, done);
});
it('should accept a default payload size limit of 1mb', function(done) {
var buf = new Buffer(999990);
buf.fill('.');
request
.post('/')
.set('Content-Type', 'application/json')
.send(JSON.stringify({ ref: 'test', str: buf.toString() }))
.expect(202, done);
});
it('should add a middleware function if options.middlware = function', function(done) {
var middlewarePassed = false;
var scopedServer = githooked('test', 'exit 1', { middleware:
function(req, res, next) {
middlewarePassed = true;
next();
}
});
supertest(scopedServer)
.post('/')
.set('Content-Type', 'application/json')
.send(JSON.stringify({ ref: 'test' }))
.end(function(err) {
assert.equal(middlewarePassed, true);
done(err);
});
});
it('should accept an array of middleware functions, if optons.middleware = [function]', function(done) {
var middleware1Passed = false,
middleware2Passed = false;
var scopedServer = githooked('test', 'exit 1', { middleware: [
function(req, res, next) {
middleware1Passed = true;
next();
},
function(req, res, next) {
middleware2Passed = true;
next();
},
]});
supertest(scopedServer)
.post('/')
.set('Content-Type', 'application/json')
.send(JSON.stringify({ ref: 'test' }))
.end(function(err) {
assert.equal(middleware1Passed, true);
assert.equal(middleware2Passed, true);
done(err);
});
});
});
describe('githooked secret validation', function() {
it('should throw an error if secret is not a string', function() {
assert.throws(function() {
githooked('test', 'exit 1', { secret: [] });
}, Error);
});
it('should emit an error if secret not sent from provider', function(done) {
var scopedServer = githooked('test', 'exit 1', { secret: 'test-secret' });
supertest(scopedServer)
.post('/')
.set('Content-Type', 'application/json')
.send({ ref: 'test' })
.expect(401)
.end(function(err) {
if ( err ) { done(err); }
});
scopedServer.on('error', function(msg) {
assert.equal(msg, 'no provider signature');
done();
});
});
it('should send a 401 if signatures do not match', function(done) {
var secret = 'test-secret',
body = { ref: 'test'},
scopedServer = githooked('test', 'exit 1', { secret: secret });
supertest(scopedServer)
.post('/')
.set('Content-Type', 'application/json')
.set('X-Hub-Signature', 'thisisabadsignature')
.send(body)
.expect(401)
.end(function(err) {
if ( err ) { done(err); }
});
scopedServer.on('error', function(msg) {
assert.equal(msg, 'signature validation failed');
done();
});
});
it('should send a 202 if signature validations match', function(done) {
var secret = 'test-secret',
body = { ref: 'test'},
scopedServer = githooked('test', 'exit 1', { secret: secret });
supertest(scopedServer)
.post('/')
.set('Content-Type', 'application/json')
.set('X-Hub-Signature', createSignature(secret, JSON.stringify(body)))
.send(body)
.expect(202, done);
});
});
describe('githooked server', function() {
var server, request;
beforeEach(function() {
server = githooked('test', 'exit 1');
request = supertest(server);
});
it('should send a 200 back for a PING event', function(done) {
request
.post('/')
.set('X-GitHub-Event', 'ping')
.set('Content-Type', 'application/json')
.send({zen: 'thisisatest', hook_id: 'thisisatest', hook: 'thisisatest'})
.expect(200, done);
});
it('should throw an error on invalid payload', function(done) {
request
.post('/')
.set('Content-Type', 'application/json')
.send('asdf')
.expect(400, done);
});
it('should emit an error on invalid payload', function(done) {
server.on('error', function(msg) {
assert.equal(msg, 'invalid ref');
done();
});
request
.post('/')
.set('Content-Type', 'application/json')
.send({})
.expect(400)
.end(function(err) {
assert(err instanceof Error);
});
});
it('should get a create event', function(done) {
server.on('create', function(payload) {
assert(payload);
done();
});
request
.post('/')
.set('Content-Type', 'application/json')
.send({ ref: 'test', created: true })
.expect(202)
.end(function(err) {
assert(!err);
});
});
it('should get a delete event', function(done) {
server.on('delete', function(payload) {
assert(payload);
done();
});
request
.post('/')
.set('Content-Type', 'application/json')
.send({ ref: 'test', deleted: true })
.expect(202)
.end(function(err) {
assert(!err);
});
});
it('should get a push event if created and deleted are falsy', function(done) {
server.on('push', function(payload) {
assert(payload);
done();
});
request
.post('/')
.set('Content-Type', 'application/json')
.send({ ref: 'test' })
.expect(202)
.end(function(err) {
assert(!err);
});
});
it('should get reference event with payload on hook', function(done) {
server.on('test', function() {
done();
});
request
.post('/')
.set('Content-Type', 'application/json')
.send({ ref: 'test' })
.expect(202)
.end(function(err) {
assert(!err);
});
});
it('should run command `exit 1` when running receiving a hook for reference "test"', function(done) {
server.on('spawn', function(instance) {
instance.on('close', function(code) {
assert.equal(code, 1);
done();
});
});
request
.post('/')
.set('Content-Type', 'application/json')
.send({ ref: 'test' })
.expect(202)
.end(function(err) {
assert(!err);
});
});
});
function createSignature(secret, body) {
return 'sha1=' + crypto.createHmac('sha1', secret).update(body).digest('hex');
}
| 47d394ef5e06f47dcebb8daed096afe235c6663f | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | ScottONeal/githooked | 5dec4f96bac9c88b97c1ceff1bb90343df71f54a | d9cf26e51693796b6d778d2dc11587fa58ab4d7c |
refs/heads/main | <file_sep>
class HashTable {
constructor(size) {
this.values = {};
this.size = size;
}
add(key, value) {
const hash = this.genHash(key)
// Initialize this portion of table
// if it has not yet been defined
if (!this.values.hasOwnProperty(hash))
this.values[hash] = {};
this.values[hash][key] = value;
}
remove(key) {
const hash = this.genHash(key);
// If this.values has property at hash with a key
if (this.values.hasOwnProperty(hash) &&
this.values[hash].hasOwnProperty(key)) {
delete this.values[hash][key]; // Delete the value
}
}
genHash(key) {
var keyStr = key.toString();
var sum = 0;
// Sum ASCII values of all chars in keyStr
for (let i = 0; i < keyStr.length; i++)
sum += keyStr.charCodeAt(i);
// Ensures index is in range of array
return sum % this.size
}
getValue(key) {
const hash = this.genHash(key);
// If this key value pair exists in table
if (this.values.hasOwnProperty(hash)
&& this.values[hash].hasOwnProperty(key))
return this.values[hash][key]; // Return the key's value
else
return undefined;
}
}
<file_sep>'use strict';
const { get } = require('mongoose');
class WriterModel {
constructor() {
this.username = username;
this.password = <PASSWORD>;
this.notAUser = notAUser;
this.fields = ['phone', 'address', 'city'];
}
get(username) {
if (username) {
return this.password.find(record => record.username === username);
} else {
return this.notAUser;
}
}
create(obj) {
let record = {
username: ++this.username,
data: {}
};
this.fields.forEach(field => record.data[field] = obj[field]);
this.db.push(record);
return record();
}
}
module.exports = WriterModel;
<file_sep>'use strict';
const Stack = require('../stacks/stacks.js');
describe('stack', () => {
it('throws when popping from an empty stack', () => {
const stack = new Stack();
expect(() => {
stack.pop();
}).toThrow(new Error('Stack underflow'));
});
it('it pops the most recently pushed item - 11', () => {
const stack = new Stack();
stack.push(11);
expect(stack.pop()).toEqual(11);
});
it('it pops the most recently pushed items - 13, 11', () => {
const stack = new Stack();
stack.push(11);
stack.push(13);
expect(stack.pop()).toEqual(13);
expect(stack.pop()).toEqual(11);
});
it('it pops the most recently pushed items - 13, 11', () => {
const stack = new Stack();
stack.push(11);
expect(stack.pop()).toEqual(11);
stack.push(13);
expect(stack.pop()).toEqual(13);
});
});
describe('peek', () => {
it('throws when the stack is empty', () => {
const stack = new Stack();
expect(() => {
stack.peek();
}).toThrow(new Error('Stack underflow'));
});
it('returns the only element in the stack', () => {
const stack = new Stack();
stack.push(11);
expect(stack.peek()).toEqual(11);
});
it('returns the most recently added element', () => {
const stack = new Stack();
stack.push(11);
stack.push(13);
expect(stack.peek()).toEqual(13);
});
});
describe('size', () => {
it('returns 0 for empty stack', () => {
const stack = new Stack();
expect(stack.size()).toEqual(0);
});
it('returns 1 for stack with 1 element', () => {
const stack = new Stack();
stack.push(19);
expect(stack.size()).toEqual(1);
});
it('returns 2 for stack with 2 elements', () => {
const stack = new Stack();
stack.push(19);
stack.push(23);
expect(stack.size()).toEqual(2);
});
it('returns 3 for stack with 3 elements', () => {
const stack = new Stack();
stack.push(19);
stack.push(23);
stack.push(29);
expect(stack.size()).toEqual(3);
});
});
describe('isEmpty', () => {
it('returns true for empty stack', () => {
const stack = new Stack();
expect(stack.isEmpty()).toEqual(true);
});
it('returns true for empty stack', () => {
const stack = new Stack();
stack.push(7);
expect(stack.isEmpty()).toEqual(false);
});
});
<file_sep>'use strict';
app.post('../sign-up', async (req, res) => {
try {
req.body.password = await bcrypt.hash(req.body.password, 10);
const user = new Users(req.body);
const record = await user.save(req.body);
res.status(200).json(record);
} catch (e) { res.status(403).send('Error creating user'); }
});<file_sep># Graph Implementation
# Authors
<NAME> & <NAME>
## Challenge
Implement a graph and represent it as an adjacency list, and should include the following methods:
- add node
- add edge
- get nodes
- get neighbors
- size
## UML

<file_sep># Code Challenge-11
# Challenge Summary
Implement a queue using two stacks
## Challenge Description
Create a brand new PseudoQueue class. Do not use an existing Queue. Instead, this PseudoQueue class will implement our standard queue interface, but will internally only utilize 2 Stack objects.
## Approach & Efficiency
## Solution
[Whiteboard](assets/queue-with-stacks.png)
<file_sep>'use Strict';
const LinkedList = require('../../lib/linkedlist.js');
describe('#insertAtHead', () => {
it('it adds the element to the beginning of the list', () => {
const ll = new LinkedList();
ll.insertAtHead(10);
const oldHead = ll.head;
ll.insertAtHead(20);
expect(ll.head.value).toBe(20);
expect(ll.head.next).toBe(oldHead);
});
it('should return a string of all values that exist in the linked list', () => {
const ll = new LinkedList();
ll.insertAtHead(0);
ll.insertAtHead(1);
ll.insertAtHead(2);
ll.insertAtHead(3);
const testString = ll.toString();
expect(testString).toEqual('{3} -> {2} -> {1} -> {0} -> {null}');
});
// it('Can successfully instantiate an empty linked list')
// it('Can properly insert into the linked list')
// it('Can head property will properly point to the first node in the linked list')
// it('Can properly insert multiple nodes into the linked list')
// it('Will return true when finding a value within the linked list that exists')
// it('Will return false when searching for a value in the linked list that does not exist')
// it('Can properly return a collection of all the values that exist in the linked list')
});
<file_sep># Challenge Summary
This is code challenge #31 - find the first repeated word in a book
## Authors:
<NAME> & <NAME>
## Whiteboard Process
[whiteboard](asset/repeatedWord.png)
## Approach & Efficiency
<!-- What approach did you take? Why? What is the Big O space/time for this approach? -->
## Solution
[code was referenced from here:](https://stackoverflow.com/questions/25644056/how-to-find-the-most-repeat-word-in-string/63988392)
<file_sep>
"use strict";
class BinaryTree {
constructor() {
this.root = null;
}
insertNode(val) {
const node = {
value: val,
left: null,
right: null,
};
let currentNode;
if (!this.root) {
this.root = node;
} else {
currentNode = this.root;
while (currentNode) {
if (val < currentNode.value) {
if (!currentNode.left) {
currentNode.left = node;
break;
} else {
currentNode = currentNode.left;
}
} else if (val > currentNode.value) {
if (!currentNode.right) {
currentNode.right = node;
break;
} else {
currentNode = currentNode.right;
}
} else {
break;
}
}
}
}
// depth first search algorythm - branch by branch.
//in-order. Process left node -> root node -> right node
//breath first search - level by level
//use a queue
InOrder() {
let result = [];
const traverse = (node) => {
// if left child exists, go left
if (node.left) traverse(node.left);
result.push(node.value);
//if righ child exists, go right
if (node.right) traverse(node.right);
};
traverse(this.root);
return result;
}
//pre-order. Process root node -> left node -> right node
PreOrder() {
let result = [];
const traverse = (node) => {
result.push(node.value);
if (node.left) traverse(node.left);
if (node.right) traverse(node.right);
};
traverse(this.root);
return result;
}
//post-order. Process left node -> right node -> root node
PostOrder() {
let result = [];
const traverse = (node) => {
if (node.left) traverse(node.left);
if (node.right) traverse(node.right);
result.push(node.value);
};
traverse(this.root);
return result;
}
//contains gets a value and check whether its in the tree
contains(value) {
let currentNode = this.root;
while (currentNode) {
if (value === currentNode.value);
return true;
}
if (value < currentNode.value) {
currentNode = currentNode.left;
} else {
currentNode = currentNode.right;
}
return false;
}
}
module.exports = BinaryTree;
<file_sep>'use strict';
const reverse = require('../array-reverse.js');
describe('Array Reverse', () => {
it('The test works', () => {
let myArray = [1, 2, 3, 4, 5]
let expected = [5, 4, 3, 2, 1]
reverse (myArray);
expect(myArray).toEqual(expected);
});
});
<file_sep>var assert = require("assert");
var salesman = require("./salesman.js");
var tests = [
{ q: [[0, 0]], r: [0] },
{
q: [
[0, 0],
[1, 1],
],
r: [0, 1],
},
];
for (let test of tests) {
var points = test.q.map(([x, y]) => new salesman.Point(x, y));
var res = salesman.solve(points);
assert.deepEqual(test.r, res);
}
<file_sep># RESPONSIVE WEB DESIGN and FLOATS
Responsive web design is the practice of building a website suitable to work on every device and every screen size, no matter how large or small, mobile or desktop. Responsive web design is focused around providing an intuitive and gratifying experience for everyone. Desktop computer and cell phone users alike all benefit from responsive websites.
## Responsive vs Adaptive vs Mobile Designs: What's the Difference?
### Responsive & Adaptive Web Designs
Responsive and adaptive web design are closely related, and often transposed as one in the same.
- Responsive generally means to react quickly and positively to any change.
- Adaptive means to be easily modified for a new purpose or situation, such as change.
With responsive design websites continually and fluidly change based on different factors, such as viewport width, while adaptive websites are built to a group of preset factors. A combination of the two is ideal, providing the perfect formula for functional websites. Which term is used specifically doesn’t make a huge difference.
- Mobile generally means to build a separate website commonly on a new domain solely for mobile users.

### Flexible Layouts
Responsive web design is broken down into three main components, including flexible layouts, media queries, and flexible media.
- Flexible layouts, is the practice of building the layout of a website with a flexible grid, capable of dynamically resizing to any width.
- Media queries were built as an extension to media types commonly found when targeting and including styles. Media queries provide the ability to specify different styles for individual browser and device circumstances, the width of the viewport or device orientation for example.
_It is best not to use fixed measurement units such as pixels or inches because the viewport height and width are onstantly changing from device to device. The formula for aleviating this constraint is the following:_
_target ÷ context = result_
_This is taking the target width of the element, divide it by the width of its parent element. The result is the relative width of the target element._
### Flexible Media
As viewports begin to change size media doesn’t always follow suit. Images, videos, and other media types need to be scalable, changing their size as the size of the viewport changes.
## Floats: What are they and what are they used for?
Float is a CSS positioning property. In web design, page elements with the CSS float property applied to them are just like the print images in a magazine where the text flows around them. Settinf the float property of a css happens like this:
.image {
float: right;
}
This sets the image to the right side of the page with the content wrapped around it to the left side.
### Four values for floating:
1. Float: right; // floats elements to the right.
1. Float: left; // floats elements to the left
1. Float: none; // ensures the element willnot float. This is a default.
1. Float: inherent // assumes the float value from the elements parent element.
Floats can be used to create webpage layouts.
Here's a example of a webpage with and w/o float properties:

<file_sep>'use strict';
const express = require('express');
const UsersModel = require('../models/user-model.js');
const users = new UsersModel();
const usersRouter = express.Router;
usersRouter.get('/users:username', getOneUsers);
function getOneUsers (req, res) {
let userName = parseInt(req.params.username);
let items = users.get(userName);
res.status(200).json(items);
}
module.exports = UsersModel;
<file_sep>// see this as a similar thing as a "node" in BT, LL, etc
class Vertex {
constructor(value) {
this.value = value;
}
}
// this is the line between vertexes
class Edge {
constructor(vertex, weight) {
this.vertex = vertex;
this.weight = weight;
}
}
// the only thing we need to hold on our graph is a the list of all edges and their related verticies
// we can do that, by holding them in a key/val pair set, using new Map()
class Graph {
constructor() {
this.adjacencyList = new Map(); // this is going to be used to keep track of our edges (key = some vertex // value = some edge)
}
// addNode(node){
// addVertex(vertex) {
// this.adjacencyList.set(vertex, []); // this will be used to store edges
// }
addNode(node) {
this.adjacencyList.set(node, []); // this will be used to store edges
}
// addEdge // adds this edge to a set of connected verticies
addEdge(startVertex, endVertex, weight = 0) {
let adjancencies = this.adjacencyList.get(startVertex);
console.log('list type:', adjancencies);
adjancencies.push(new Edge(endVertex, weight));
}
// create a copy of our list and return the copy -> this contains all related vertixes on this list
getNeighbors(vertex) {
return [...this.adjacencyList.get(vertex)];
}
}
<file_sep>'use strict';
app.post('../sign-in', async (req, res) => {
})<file_sep>'use strict';
const Node = require('./node.js');
class AnimalShelter {
constructor() {
this.front = null;
this.back = null;
}
enqueue(animal) {
let node = new Node(animal);
if (this.front === null) {
this.back = node;
this.back.next = node;
this.front = node;
} else {
this.back.next = node;
this.back = node;
}
return this.back.value;
}
dequeueAnimal(pref) {
let current = this.front;
let previous;
if (pref) {
if (current.value === pref) {
this.front = current.next;
}
while (current.value !== pref) {
previous = current;
current = current.next;
}
previous.next = current.next || null;
return `${current.value}`;
} else {
return null;
}
}
}
//enqueue test
let queue = new AnimalShelter;
queue.enqueue('cat');
queue.enqueue('dog');
queue.enqueue('cat');
queue.enqueue('dog');
// console.log(queue);
//dequeue() test
console.log(queue.dequeueAnimal());
console.log(queue);
module.exports = AnimalShelter;
<file_sep># 401 Code Challenge - 02
## Project: Array Binary Search
Write a function which takes in 2 parameters: a sorted array and the search key. Without utilizing any of the built-in methods available to your language, return the index of the array’s element that is equal to the search key, or -1 if the element does not exist.
### Challenge
To search a sorted array and find a search key
### Approach and Efficiency
To divide the array and search for the key until it is found
### Collaborators: <NAME> & <NAME>
### Links and Resources
- [Array Binary Search in JS](https://youtu.be/92e5Ih4Chbk) (YouTube Video)
#### Whiteboard Solution

### Pull Requests
- [PR 1 - Completed Lab-02](https://github.com/ClementBuchanan/basic-express-server/pull/1)
- [PR 2 - Updated Package.json](https://github.com/ClementBuchanan/basic-express-server/pull/2)
- [PR 3 - Completed readme.md](https://github.com/ClementBuchanan/basic-express-server/pull/3)
- [PR 4 - Updated and completed readme.md](https://github.com/ClementBuchanan/basic-express-server/pull/4)
- [PR 5 - Updated readme.md with setup](https://github.com/ClementBuchanan/basic-express-server/pull/5)
<file_sep>'use strict';
/* ========== STACK ========== */
class Stack {
constructor() {
this.storage = {};
this.size = 0;
}
push(element) {
this.size++;
this.storage[this.size] = element;
}
pop() {
let removed = this.storage[this.size];
delete this.storage[this.size];
this.size--;
return removed;
}
peek() {
return this.storage[this.size];
}
}
const stack = new Stack();
stack.push('5');
stack.push('1');
stack.push('2');
stack.pop();
stack.peek();
module.Stack = Stack;
<file_sep>'use strict';
const Stack = require('.stacks.js');
class Queue {
constructor() {
this.stack1 = new Stack();
this.stack2 = new Stack();
this.head = null;
this.tail = null;
}
enqueue(number) {
this.stack1[this.tail] = number;
this.head++;
}
dequeue() {
let removed = this.stack2[this.head];
delete this.stack2[this.head];
this.head++;
return removed;
}
}
<file_sep>
# Reverse an Array
Write a function that reverses an array in place
## Challenge
Be careful of empty arrays or arrays with only one number or odd number count or even number count
## Approach & Efficiency
- Identify the start and end of the array (0 and length -1)
- Swop the arr[start] with the arr[end]
- Move arr[start] forward by --> 1
- Move arr[end] backward by <-- 1
- Repeat while arr[start] <= arr[end]
## Solution

New word
<file_sep># Trees
Creating a Binary Tree and a Binary Search Tree implementation
## Challenge
- Create a Node class that has properties for the value stored in the node, the left child node, and the right child node.
- Create a BinaryTree class
- Create a BinarySearch Tree class
## Approach & Efficiency
<!-- What approach did you take? Why? What is the Big O space/time for this approach? -->
## API
<!-- Description of each method publicly available in each of your trees -->
## Tests
- Can successfully instantiate an empty tree
- Can successfully instantiate a tree with a single root node
- Can successfully add a left child and right child to a single root node
- Can successfully return a collection from a preorder traversal
- Can successfully return a collection from an inorder traversal
- Can successfully return a collection from a postorder traversal
## UML
<file_sep>'use strict';
const base64 = require('base-64');
const bcrypt = require('bcrypt');
<file_sep>'use strict';
function insertShiftArray(arr, val) {
let midIndex = Math.ceil(arr.length/2);
let temp = arr[midIndex];
arr[midIndex] = val;
let tempTwo = arr[midIndex+1];
for (let i=midIndex+1; i<arr.length; i++) {
tempTwo = arr[i];
arr[i]=temp;
temp=tempTwo;
}
arr[arr.length] = temp
return arr
}
console.log(insertShiftArray([1,2,3,4,5], 99))
console.log(insertShiftArray([1,2,3,4], 99))
module.exports = insertShiftArray;
<file_sep>"use strict";
const { BinaryTree } = require("../tree.js");
const { BinarySearchTree } = require("../binarySearch.js");
const { BinaryTreeMaxValue } = require("../treeMax.js");
const { BreadthFirst } = require("../breadthFirst.js");
const Node = require("../node.js");
describe("Tree", () => {
const tree = new BinaryTree();
beforeAll(() => {
// Binary Search Tree...
// tree.add(9); tree.add(4);
// Binary tree, so this all by hand
const nine = new Node(9);
const four = new Node(4);
const three = new Node(3);
const six = new Node(6);
const twelve = new Node(12);
const eleven = new Node(11);
const twentytwo = new Node(22);
tree.root = nine;
nine.left = four;
nine.right = twelve;
four.left = three;
four.right = six;
twelve.left = eleven;
twelve.right = twentytwo;
});
it("binary search tree can add a root", () => {
const testTree = new BinarySearchTree();
testTree.add(9);
expect(tree.root.value).toEqual(9);
testTree.add(4);
expect(tree.root.left.value).toEqual(4);
});
it("contains", () => {
// is tree an "instanceOf" BinarySearchTree
const tree = new BinarySearchTree();
tree.add(5);
expect(tree.contains(5)).toBeFalsy();
});
it("has a valid root", () => {
expect(tree.root.value).toEqual(9);
});
it("pre-order works right", () => {
console.log(tree.preOrder());
});
it("in-order is a sorted array", () => {
const tree = new BinarySearchTree();
tree.add(5);
tree.add(4);
tree.add(9);
tree.add(8);
const list = tree.inOrder();
expect(list).toEqual([4, 5, 8, 9]);
console.log(tree.inOrder());
console.log(tree.inOrderWithoutHelper(tree.root));
});
it("post-order is in the right order", () => {
console.log(tree.postOrder());
});
it("breadth first strips the tree", () => {
console.log(tree.breadthFirst());
});
it("should find max value", () => {
const tree = new BinaryTreeMaxValue();
tree.add(5);
tree.add(4);
tree.add(9);
tree.add(8);
expect(tree.findMax()).toEqual(9);
console.log(tree.findMax());
});
it("should find min value", () => {
const tree = new BinaryTreeMaxValue();
tree.add(5);
tree.add(4);
tree.add(9);
tree.add(8);
expect(tree.findMin()).toEqual(4);
console.log(tree.findMin());
});
it("should return breadthfirst", () => {
const tree = new BreadthFirst();
tree.add(5);
tree.add(4);
tree.add(9);
tree.add(8);
expect(tree.breadth()).toEqual([5, 4, 9, 8]);
console.log(tree.breadth());
});
});
<file_sep>'use strict';
let Queue = require('../fifo-animal-shelter.js');
describe('enqueue', () => {
it('Add node to the back-end of the queue', () => {
let queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
});
describe('dequeueAnimal(cat)', () => {
it('Remove first cat', () => {
let queue = new Queue();
queue.enqueue('dog');
queue.enqueue('cat');
queue.enqueue('dog');
queue.enqueue('cat');
console.log(queue.dequeueAnimal('cat'));
expect(queue.dequeueAnimal('cat')).toEqual('cat');
});
});
describe('dequeueAnimal(cat)', () => {
it('Remove sec cat', () => {
let queue = new Queue();
queue.enqueue('dog');
queue.enqueue('cat');
queue.enqueue('dog');
queue.enqueue('cat');
expect(queue.dequeueAnimal('cat')).toEqual('cat');
});
});
describe('dequeueAnimal(dog)', () => {
it('Remove first dog', () => {
let queue = new Queue();
queue.enqueue('cat');
queue.enqueue('dog');
queue.enqueue('dog');
queue.enqueue('cat');
expect(queue.dequeueAnimal('dog')).toEqual('dog');
});
});
describe('dequeueAnimal(dog)', () => {
it('Remove sec dog', () => {
let queue = new Queue();
queue.enqueue('cat');
queue.enqueue('dog');
queue.enqueue('cat');
queue.enqueue('dog');
expect(queue.dequeueAnimal('dog')).toEqual('dog');
});
});
});
<file_sep>'use strict';
const LL = require('../../lib/ll.js');
describe('LINKED LIST', () => {
it('Should create and empty list on instantiation', () => {
let list = new LL();
expect(list.head).toEqual(null);
});
it('Should add items to the list', () => {
let list = new LL();
let first = 'first';
let second = 'second';
list.append(first); //adds an item to the list
expect(list.head.value).toEqual(first); //checks the the item was added with the value
list.append(second); //checks the property of the next test
list.append(3);
list.append(4);
console.group(list);
});
it('can point the head property to the first node', () => {
let list = new LL();
list.head = new LL();
console.log('this is head', list.head);
expect(list.head).toBeTruthy();
});
it('should return a string of all values that exist in the linked list', () => {
let list = new LL();
let string1 = 'baldy';
let string2 = 'baldy2';
list.append(string1);
list.append(string2);
expect(list.toString()).toEqual('{baldy} -> {baldy2} -> {null}');
});
it('should return true if search value is in the list', () => {
let list = new LL();
expect(list.includes('first')).toBeFalsy();
list.append('first');
list.append('second');
expect(list.includes('first')).toBeTruthy();
expect(list.includes('second')).toBeTruthy();
});
});
<file_sep>## Singly Linked List
Create a Node class that has properties for the value stored in the Node, and a pointer to the next Node.
## Challenge
- Define a method called insert which takes any value as an argument and adds a new node with that value to the head of the list with an O(1) Time performance.
- Define a method called includes which takes any value as an argument and returns a boolean result depending on whether that value exists as a Node’s value somewhere within the list.
- Define a method called toString (or __str__ in Python) which takes in no arguments and returns a string representing all the values in the Linked List, formatted as:
"{ a } -> { b } -> { c } -> NULL"
## Approach & Efficiency
I first created a test for each of the features then check for assurance that they pass. I then coded based on the success of the tests. This was the most effe\icient way to do it.
## Tests
Write tests to prove the following functionality:
- It can successfully instantiate an empty linked list
- It can properly insert into the linked list
- The head property will properly point to the first node in the linked list
- It can properly insert multiple nodes into the linked list
- It will return true when finding a value within the linked list that exists
- It will return false when searching for a value in the linked list that does not exist
- It can properly return a collection of all the values that exist in the linked list<file_sep>
# Code Challenge 12
## Authors:
<NAME>, <NAME> and <NAME>
## Challenge Summary
Create a class called AnimalShelter which holds only dogs and cats. The shelter operates using a first-in, first-out approach.
## Challenge Description
Implement the following methods:
- enqueue(animal): adds animal to the shelter.
- animal can be either a dog or a cat object.
- dequeue(pref): returns either a dog or a cat.
- If pref is not "dog" or "cat" then return null.
## Approach & Efficiency
We used a simple queue and dequeue process vs using an array
## Solution
<file_sep>'use strict';
const linkedList = require('./lib/linkedlist.js');
let insert = new linkedList();
insert.insertAtHead(10);
console.log(insert);
insert.insertAtHead(20);
// insert.append('three');
// insert.append('four');
console.log(insert);
<file_sep># LAB-07
# Author: <NAME>
- Test Report
- Front End
## Setup
- .env requirements
- PORT - 8080
# Running the app
- node index.js
- Endpoint: /signup
- Returns Object

## UML
(created with Miro)

Maintain a head and a tail pointer on the merged linked list.
- I choose the head of the merged linked list by comparing the first node of both linked lists.
- I choose the smaller current node and link it to the tail of the merged list, and moving the current pointer of that list one step forward.
- I kept doing this while there are some remaining elements in both the lists. If there are still some elements in only one of the lists, I link this remaining list to the tail of the merged list.
- Initially, the merged linked list is NULL
- I made node with the smaller value the head node of the merged linked list. In this case, it is 1 from head 1.
- Since it’s the first and only node in the merged list, it will also be the tail.
- Then I moved head1 one step forward.
## Tests
write test for
- basic authorization middleware test
- bearer authorization midddleware test
<file_sep># Challenge Summary
Inserting a number in the middle of and array with even items, odd items or no items in the array.
## Challenge Description
Write a function called insertShiftArray which takes in an array and the value to be added. Without utilizing any of the built-in methods available to your language, return an array with the new value added at the middle index.
## Approach & Efficiency
<!-- What approach did you take? Why? What is the Big O space/time for this approach? -->
- First we determined the middle index then saved the
## Solution

## Link To The Code
[Click here to be taken to the array-shift.js file to see the code](array-shift.js)
## Partner Contributors
- <NAME>
- <NAME><file_sep>'use strict';
app.post('/signin', basicAuth, (req, res) => {
});<file_sep>const edges = {
AB: 10,
AC: 15,
AD: 20,
BA: 10,
BC: 12,
BD: 11,
CA: 13,
CB: 22,
CD: 24,
DA: 33,
DB: 25,
DD: 43,
};
let totalCities = 4;
let recordDistance;
let bestEver;
function setup() {
for (let i = 0; i < totalCities; i++) {
let vertices = ["A", "B", "C", "D"];
cities[i] = vertices;
}
let dist = calcDistance(cities);
recordDistance = dist;
bestEver = cities.slice();
}
function draw() {
let A = floor(random(cities.length));
let B = floor(random(cities.length));
let C = floor(random(cities.length));
let D = floor(random(cities.length));
swap(cities, A, B, C, D);
let dist = calcDistance(cities);
if (dist < recordDistance) {
recordDistance = dist;
bestCity = cities.slice();
}
}
//shuffling the array
function swap(arr, A, B, C, D) {
let temp = arr[A];
arr[A] = arr[B];
arr[C] = arr[D];
arr[D] = temp;
}
function totalCost(points) {
let cost = 0;
for (let i = 0; i < edges.length - 1; i++) {
let price = cost(points[i].edges, points[i + 1].edges);
cost += price;
}
}
return totalCost;
<file_sep>'use strict';
/* ========== STACK ========== */
class Stack {
constructor() {
this.storage = {};
this.size = 0;
}
push(element) {
this.size++;
this.storage[this.size] = element;
}
pop() {
let removed = this.storage[this.size];
delete this.storage[this.size];
this.size--;
return removed;
}
peek() {
return this.storage[this.size];
}
}
const stack = new Stack();
stack.push('dog');
stack.push('cat');
stack.push('bear');
stack.pop();
stack.peek();
module.Stack = Stack;
// class Stack {
// constructor() {
// this._size = 0;
// }
// pop() {
// if (!this._size()) {
// throw new Error('Stack underflow');
// }
// const result = this.toBePopped.item;
// this.toBePopped = this.toBePopped.nextToBePopped;
// this._size = this._size - 1;
// return result;
// }
// peek() {
// if (!this._size()) {
// throw new Error('Stack underflow');
// }
// return this.toBePopped.item;
// }
// push(item) {
// this.toBePopped = {
// item,
// nextToBePopped: this.toBePopped
// };
// this._size = this._size + 1;
// }
// size() {
// return this._size;
// }
// isEmpty() {
// return this._size() === 0;
// }
// }
// module.exports = Stack;
<file_sep>## Challenge Summary
Find the common values in two binary trees
## Authors: <NAME> & <NAME>
## Whiteboard Process

## Approach & Efficiency
We know that if we store the inorder traversal of a BST in an array, that array will be sorted in ascending order. So I simply took the inorder traversal of both the trees and store them in two seperate arrays and then find intersection between two arrays.
Time Complexity: O(n+m).
Here ‘m’ and ‘n’ are number of nodes in first and second tree respectively, as we need to traverse both the trees.
## Solution
[Link to code](www.link.com)<file_sep># Data Structures and Algorithms
See [setup instructions](https://codefellows.github.io/setup-guide/code-301/3-code-challenges), in the Code 301 Setup Guide.
## Repository Quick Tour and Usage
### 301 Code Challenges
Under the `data-structures-and-algorithms` repository, at the top level is a folder called `code-challenges`
Each day, you'll add one new file to this folder to do your work for the day's assigned code challenge
## Table of Contents for 301 Challenges
1. [Code Challenge-01](code-challenges/challenges-01.test.js)
2. [Code Challenge-02](code-challenges/challenges-02.test.js)
3. [Code Challenge-03](code-challenges/challenges-03.test.js)
4. [Code Challenge-04](code-challenges/challenges-04.test.js)
5. [Code Challenge-05](code-challenges/challenges-05.test.js)
6. [Code Challenge-06](code-challenges/challenges-06.test.js)
7. [Code Challenge-07](code-challenges/challenges-07.test.js)
8. [Code Challenge-08](code-challenges/challenges-08.test.js)
9. [Code Challenge-09](code-challenges/challenges-09.test.js)
10. [Code Challenge-10](code-challenges/challenges-10.test.js)
11. [Code Challenge-11](code-challenges/challenges-11.test.js)
12. [Code Challenge-12](code-challenges/challenges-12.test.js)
13. [Code challenge-12](code-challenges/challenges-12.test.js)
14. [Code Challenge-13](code-challenges/challenges-13.test.js)
### 401 Data Structures, Code Challenges
- Please follow the instructions specific to your 401 language, which can be found in the directory below, matching your course.
<file_sep>'use strict';
function multiBracketValidation(input) {
let temp = 0;
for (x of input) {
if (x === '(') temp++;
else (x === ')' && --tmp < 0) return false;
}
return tmp === 0;
}
const goodBrackets = '((((()))))';
const badBrakets = '((({[}][)]))';
const veryBadBrackets = '([]{(}]{([])})';
console.log(validate(goodBrackets));
console.log(validate(badBrakets));
console.log(validate(veryBadBrackets));
<file_sep>'use strict';
const linkedList = require('./lib/linked-list.js');
let ll = new linkedList();
ll.append('first');
ll.append(2);
ll.append('three');
ll.append('four');
console.log(ll);
<file_sep># Challenge Summary
Write methods for a linked list class
## Challenge Description
Write these methods
- .append(value) which adds a new node with the given value to the end of the list
- .insertBefore(value, newVal) which add a new node with the given newValue immediately before the first value node
- .insertAfter(value, newVal) which add a new node with the given newValue immediately after the first value node
## Approach & Efficiency
<!-- What approach did you take? Why? What is the Big O space/time for this approach? -->
## Solution

## Singly Linked List
Create a Node class that has properties for the value stored in the Node, and a pointer to the next Node.
## Challenge
- Define a method called insert which takes any value as an argument and adds a new node with that value to the head of the list with an O(1) Time performance.
- Define a method called includes which takes any value as an argument and returns a boolean result depending on whether that value exists as a Node’s value somewhere within the list.
- Define a method called toString (or __str__ in Python) which takes in no arguments and returns a string representing all the values in the Linked List, formatted as:
"{ a } -> { b } -> { c } -> NULL"
## Approach & Efficiency
I first created a test for each of the features then check for assurance that they pass. I then coded based on the success of the tests. This was the most effe\icient way to do it.
## Tests
Write tests to prove the following functionality:
- It can successfully instantiate an empty linked list
- It can properly insert into the linked list
- The head property will properly point to the first node in the linked list
- It can properly insert multiple nodes into the linked list
- It will return true when finding a value within the linked list that exists
- It will return false when searching for a value in the linked list that does not exist
- It can properly return a collection of all the values that exist in the linked list
<file_sep>'use strict';
const Node = require('../../lib/node.js');
// JEST - RUNNER / ASSERTION LIBRARY -> describe, it, expect
// describe -> test suite -> usually a module
describe('NODE CLASS', () => {
// it -> an individual test -> you can also use test()
it('can create a new node', () => {
let val = 'test value';
let node = new Node(val);
// expect are assertions
// 1. to check the node value we just created
expect(node.value).toEqual(val);
// 2. ensure our next is null, because there is only one node
expect(node.next).toBeNull();
});
});
<file_sep># 401 Code Challenge - 03
## Challenge Summary
Write a function which takes in 2 parameters: a sorted array and the search key. Without utilizing any of the built-in methods available to your language, return the index of the array’s element that is equal to the search key, or -1 if the element does not exist.
## Description
To search a sorted array and find a search key
### Approach and Efficiency
To divide the array and search for the key until it is found
### Links and Resources
- [Link to code for array-binary-search.js](array-binary-search.js)
- [Array Binary Search in JS](https://youtu.be/92e5Ih4Chbk) (YouTube Video)
### Whiteboard Solution

<file_sep>'use strict';
let arr = [2, 4, 5, 12, 13, 31, 32, 66];
let value = 13;
function binarySearch (arr, value) {
let high = arr.length - 1;
let low = 0;
let mid = 0;
while (low <= high) {
mid = Math.ceil((low + high) / 2); // if middle == value we're done
if(arr[mid] == value){
//return value
return mid;
}else if (value > arr[mid]) {
// move low up by 1
low = mid + 1;
}else {
// move high down by 1
high = mid - 1
}
}
return -1;
}
let wasItFound = binarySearch(arr, value)
console.log(wasItFound);
module.exports = binarySearch;<file_sep>'use strict';
// const { interface } = require('node:readLine');
//pull in the Node Class --> giving the ability to instantiate (add) a new node to the list
const Node = require('./node.js');
class LinkedList {
constructor() {
this.head = null;
}
// the ability to add an item to the tail
append(value) {
let node = new Node(value);
if (!this.head) { // same as this.head === null
this.head = node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
return this;
}
insertAtHead(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
} else {
let oldHead = this.head;
this.head = newNode;
this.head.next = oldHead;
}
return this;
}
includes(value) {
// check in linkedlist is empty
if (!this.head) {
return false;
} else {
let current = this.head;
while (current) {
if (value === current.value) {
return true;
} else {
current = current.next;
}
}
return false;
}
}
toString() {
let current = this.head;
let string = '';
while (current) {
string += `{${current.value}} -> `;
current = current.next;
}
string += '{null}';
return string;
}
}
module.exports = LinkedList;
<file_sep>"use strict";
const Vertex = require("./vertex");
const Edge = require("./edge");
class Graph {
constructor() {
this.vertices = [];
this.edges = [];
this.numberOfEdges = 0;
}
addVertex(vertex) {
this.vertices.push(vertex);
this.edges[vertex] = [];
}
removeVertex(vertex) {
//indexOf returns a value of -1
const index = this.vertices.indexOf(vertex);
if (index >= 0) {
//deletes the element at the index
this.vertices.splice(index, 1);
}
//whole there are edges for this vertex
while (this.edges[vertex].length) {
const adjacentVertex = this.edges[vertex].pop(); //pop takes the last element in the array and pops it
this.removeEdge(adjacentVertex, vertex);
}
}
//adding edge between two vertices with the addEgde function
addEdge(vertex1, vertex2) {
this.edges[vertex1].push(vertex2);
this.edges[vertex2].push(vertex1);
this.numberOfEdges++;
}
//removing edge between two vertices with the removeEdge function
removeEdge(vertex1, vertex2) {
//finding the index of vertex1 within the edges of vertex2 and if found returns -1
const index1 = this.edges[vertex1]
? this.edges[vertex1].indexOf[vertex2]
: 1;
const index2 = this.edges[vertex2]
? this.edges[vertex2].indexOf[vertex1]
: 1;
if (index1 >= 0) {
this.edges[vertex1].splice(index1, 1);
//placed inside the if statement because potentially the vertex could be empty.
this.numberOfEdges--;
}
if (index2 >= 0) {
this.edges[vertex2].splice(index2, 1);
this.numberOfEdges--;
}
}
//size of the vertices
size() {
return this.vertices.length;
}
//size of the edges
relations() {
return this.numberOfEdges;
}
findAdjacent(nodeName) {
let adjacentNodes = [];
this.edges.forEach(function (edge) {
if (edge[0] === nodeName) {
let node = this.vertices.find(function (vertex) {
return vertex.name === edge[1];
});
if (node) {
let adjacentIndex = this.vertices.indexOf(node);
let adjacent = this.vertices.splice(adjacentIndex, 1);
if (adjacent[0].distance === null) {
adjacentNodes.push(adjacent[0]);
}
}
} else if (edge[1] === nodeName) {
let node = this.vertices.find(function (vertex) {
return vertex.name === edge[0];
});
if (node) {
let adjacentIndex = this.vertices.indexOf(node);
let adjacent = this.vertices.splice(adjacentIndex, 1);
if (adjacent[0].distance === null) {
adjacentNodes.push(adjacent[0]);
}
}
}
});
return adjacentNodes;
}
markDistanceAndPredecessor(rootNode, adjacentNodes) {
if (rootNode.predecessor === null) {
adjacentNodes.forEach(function (node) {
node.predecessor = rootNode;
node.distance = 1;
});
} else {
adjacentNodes.forEach(function (node) {
node.predecessor = rootNode;
node.distance = rootNode.distance + 1;
});
}
return adjacentNodes;
}
breathFirstSearch(rootNode) {
let queue = [];
let visited = [];
let explored = [];
let rootIndex = this.vertices.indexOf(rootNode);
this.vertices.splice(rootIndex, 1);
queue.push(rootNode);
visited.push(rootNode);
while (queue.length !== 0) {
let currentNode = queue.shift();
let adjacentNodesArray = this.findAdjacent(currentNode.name);
adjacentNodesArray.forEach(function (node) {
queue.push(node);
visited.push(node);
});
this.markDistanceAndPredecessor(currentNode, adjacentNodesArray);
explored.push(currentNode);
}
return visited;
}
markDiscovered(node) {
return (node.discovered = true);
}
print() {
console.log(
this.vertices
.map((vertex) => {
return `${vertex} => ${this.edges[vertex].join(", ").trim()}`;
}, this)
.join(" | ")
);
}
}
module.exports = Graph;
<file_sep>"use strict";
const Node = require("./node.js");
const { BinarySearchTree } = require("./binarysearch.js");
class BreadthFirst extends BinarySearchTree {
breadth() {
if (!this.root) {
return "Empty";
}
let queue = [];
let path = [];
queue.push(this.root);
while (queue.length > 0) {
let currentNode = queue.shift();
path.push(currentNode.value);
if (currentNode.left !== null) {
queue.push(currentNode.left);
}
if (currentNode.right !== null) {
queue.push(currentNode.right);
}
}
return path;
}
}
module.exports = { BreadthFirst };
<file_sep>'use strict';
const express = require('express');
const WriterModel = require('../models/writer-model.js');
const writers = new WriterModel();
const writersRouter = express.Router();
writersRouter.get('/writers:username', readArticle);
writersRouter.get('/writers', createArticle);
function readArticle (req, res) {
let all = writers.get();
res.status(200).json(all);
}
function createArticle(req, res) {
let obj = req.body;
let newArticle = writers.create(obj);
console.log(newArticle);
res.status(201).json(newArticle);
}
module.exports = writersRouter;
<file_sep>
## Stacks and Queues
- Create a Node class that has properties for the value stored in the Node, and a pointer to the next node.
- Create a Stack class that has a top property. It creates an empty Stack when instantiated.
- Create a Queue class that has a front property. It creates an empty Queue when instantiated.
## Description
- Define a method called **PUSH**
- Define a method called **POP**
- Define a method called **PEEK**
- Define a method called **isEMPTY**
## Approach & Efficiency
I referenced a Youtube video for this challenge. The video was titled [Implementing stack data structure with TDD (Kata 2)](https://www.youtube.com/watch?v=hTx3bmMsISc) with sample codes and tests that I refactured. The code only sample for Stacks and Stacks testing. I got assistance from a classmate on Queues and Queues testing.
## Testing
- Can successfully push onto a stack
- Can successfully push multiple values onto a stack
- Can successfully pop off the stack
- Can successfully empty a stack after multiple pops
- Can successfully peek the next item on the stack
- Can successfully instantiate an empty stack
- Calling pop or peek on empty stack raises exception
- Can successfully enqueue into a queue
- Can successfully enqueue multiple values into a queue
- Can successfully dequeue out of a queue the expected value
- Can successfully peek into a queue, seeing the expected value
- Can successfully empty a queue after multiple dequeues
- Can successfully instantiate an empty queue
- Calling dequeue or peek on empty queue raises exception<file_sep>'use strict';
const findDuplicateWords = require('../repeated_words.js');
describe('find duplicate words', () => {
it('should test a', () => {
const a = 'Once upon a time, there was a brave princess who...';
expect(findDuplicateWords(a)).toEqual('a');
console.log(findDuplicateWords(a));
});
it('should test was', () => {
const a = 'It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way – in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only...';
expect(findDuplicateWords(a)).toEqual('was');
console.log(findDuplicateWords(a));
});
});
<file_sep>'use strict';
const Queue = require('../queues/queues.js');
describe('queue test', () => {
it('should enqueue into a queue', () => {
const setup = new Queue;
setup.enqueue(25);
expect(setup.storage.length).toEqual(1);
});
it('should enqueue multiple items into a queue', () => {
const setup = new Queue;
setup.enqueue(25);
setup.enqueue(32);
expect(setup.storage.length).toEqual(2);
});
it('should enqueue multiple items into a queue', () => {
const setup = new Queue;
setup.enqueue(25);
setup.enqueue(32);
expect(setup.storage.length).toEqual(2);
});
});
<file_sep>
"use strict";
const Node = require("./node.js");
class BST {
constructor() {
this.root = null;
// keeping track on # of nodes in the tree
this.count = 0;
}
size() {
return this.count;
}
insert(value) {
this.count++;
let newNode = new Node(value);
if (!this.root) {
this.root = newNode;
return this.root;
}
const searchTree = (node) => {
//value < node.value go left
if (value < node.value) {
//if no left child then append new node here
if (!node.left) {
node.left = newNode;
}
// if there is a left child. look left again
else {
searchTree(node.left);
}
}
//if value > node.value go right
else if (value > node.value) {
// if no right child. Append new node
if (!node.right) {
node.right = newNode;
}
// if there is a left child. look left again
else {
searchTree(node.right);
}
}
//if there is a right child node. Call searchTree and look right again.
};
searchTree(this.root);
//while inside the insert method call searchTree in the root node
}
//contains gets a value and check whether its in the tree
contains(value) {
// let currentNode = this.root;
const traverse = node => {
if (!node) return false;
if (node.value === value) return true;
const left = traverse(node.left);
const right = traverse(node.right);
if (left || right) return true;
};
const tree = traverse(this.root);
if (tree) return true;
return false;
}
}
module.exports = BST;
<file_sep>"use strict";
const Node = require("./node.js");
const { BinaryTree } = require("./tree.js");
class BinarySearchTree extends BinaryTree {
addNode(node, newNode) {
if (newNode.value < node.value) {
if (node.left === null) node.left = newNode;
else this.addNode(node.left, newNode);
} else {
if (node.right === null) node.right = newNode;
else this.addNode(node.right, newNode);
}
}
add(value) {
var newNode = new Node(value);
if (this.root === null) this.root = newNode;
else this.addNode(this.root, newNode);
}
remove(value) {
this.root = this.removeNode(this.root, value);
}
removeNode(node, key) {
if (node === null) return null;
else if (key < node.value) {
node.left = this.removeNode(node.left, key);
return node;
} else if (key > node.value) {
node.right = this.removeNode(node.right, key);
return node;
} else {
if (node.left === null && node.right === null) {
node = null;
return node;
}
if (node.left === null) {
node = node.right;
return node;
} else if (node.right === null) {
node = node.left;
return node;
}
var aux = this.findMinNode(node.right);
node.value = aux.value;
node.right = this.removeNode(node.right, aux.value);
return node;
}
}
breadth(tree, rootNode, searchValue) {
let queue = [];
let path = [];
queue.push(rootNode);
while (queue.length > 0) {
let currentNode = queue[0];
path.push(currentNode.value);
if (currentNode.value === searchValue) {
return path;
}
if (currentNode.left !== null) {
queue.push(tree[currentNode.left]);
}
if (currentNode.right !== null) {
queue.push(tree[currentNode.right]);
}
queue.shift();
}
}
fizzBuzz() {
if (!this.root) {
return "Empty";
}
let queue = [];
let path = [];
queue.push(this.root);
while (queue.length > 0) {
let currentNode = queue.shift();
path.push(currentNode.value);
if (currentNode.value % 15 === 0) {
console.log("FizzBuzz");
} else if (currentNode.value % 3 === 0) {
console.log("Fizz");
} else if (currentNode.value % 5 === 0) {
console.log("Buzz");
} else if (currentNode.value) {
console.log(currentNode.value);
console.log(path);
}
if (currentNode.left !== null) {
queue.push(currentNode.left);
}
if (currentNode.right !== null) {
queue.push(currentNode.right);
}
}
return path;
}
}
module.exports = { BinarySearchTree };
| 58a658b9509a2e69782c9666ecd96ebd3ac8bdff | [
"JavaScript",
"Markdown"
] | 51 | JavaScript | ClementBuchanan/data-structures-and-algorithms | 773ae626c806fad1a2375681e71abeb0950adffa | 631fd223f1d07f5d4d41d02685e39fec87e556e5 |
refs/heads/main | <repo_name>YashMarmat/TODO-APP-in-React<file_sep>/README.md
# TODO-APP-in-React
See the App in action <a href = "https://9diqy.csb.app/">here</a>
<a href = "https://codesandbox.io/s/advance-todo-bootstrap-fontawesome-9diqy">Sandbox Link</a>
<file_sep>/src/App.js
import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import "font-awesome/css/font-awesome.min.css";
import "@fortawesome/react-fontawesome";
import "./styles.css";
class App extends Component {
constructor() {
super();
this.state = {
newID: 5, // because we already have four items in the todoData (to avoid unique key issue)
edit: false,
cloneID: 0,
cloneTitle: "",
todoData: [
{
id: "1",
task: "React Rivision",
completed: false
},
{
id: "2",
task: "Django Rivision",
completed: false
},
{
id: "3",
task: "React + Django projects",
completed: false
},
{
id: "4",
task: "Other Projects",
completed: false
}
]
};
this.handleUserInput = this.handleUserInput.bind(this);
this.handleAddItem = this.handleAddItem.bind(this);
this.handleEdits = this.handleEdits.bind(this);
this.renderEdits = this.renderEdits.bind(this);
this.handleUpdates = this.handleUpdates.bind(this);
this.onRemove = this.onRemove.bind(this);
this.handleStrike = this.handleStrike.bind(this);
this.increment = this.increment.bind(this);
}
// increment id
increment() {
this.setState((prevState) => ({
newID: prevState.newID + 1
}));
}
// Todo Creation Function (part 1)
handleUserInput(event) {
this.setState({
userInput: event.target.value
});
}
// Todo Creation Function (part 2)
handleAddItem() {
const someID = this.state.newID;
//console.log(someID)
this.setState((prevState) => ({
todoData: [
...prevState.todoData,
{ id: someID, task: this.state.userInput }
],
userInput: "" // im telling react to empty my userInput (the input box)
}));
}
// Todo edit funciton (part 1)
// function 1 (runs the very first time (if edit gets clicked))
handleEdits(theId, theTitle) {
this.setState({
edit: true,
cloneID: theId,
cloneTitle: theTitle
});
}
// Todo edit function (part 2)
// function 2 (runs automatically after function 1)
// (will run only when the edit condition is true (when we click on edit button))
renderEdits() {
if (this.state.edit) {
return (
<div>
<form onSubmit={this.handleUpdates}>
<input
autoFocus={true}
placeholder="Update Todos"
type="text"
name="data"
defaultValue={this.state.cloneTitle} // from the cloneTitle
className="form-control"
/>
<button
type="submit"
className="btn btn-sm btn-success ml-2 updateButton"
>
Update
</button>
</form>
</div>
);
}
}
// Todo edit Function (part 3)
// function 3 (will run when function 2 runs)
handleUpdates(event) {
event.preventDefault();
this.setState({
todoData: this.state.todoData.map((item) => {
if (item.id === this.state.cloneID) {
item["task"] = event.target.data.value;
return item;
} else {
return item;
}
})
});
this.setState({
edit: false
});
}
// Todo delete function
onRemove(myId) {
this.setState((prevState) => {
const updatedList = prevState.todoData.filter((each) => each.id !== myId);
return {
todoData: updatedList
};
});
}
handleStrike(theId, theTask) {
const todoData = this.state.todoData.map((item) => {
if (item.id === theId) {
item["id"] = theId;
item["task"] = theTask;
item["completed"] = !item.completed;
return item;
} else {
return item;
}
});
this.setState({
todoData: todoData
});
}
render() {
//console.log(this.state.todoData);
return (
<div className="card mb-3 sizing mx-auto">
{this.renderEdits()}
{this.state.todoData.map((item) => (
<div className="card-body border text-grey" key={item.id}>
<span className={"crossed-line" + (item.completed ? "" : "active")}>
{item.task}
</span>
{/* edit button below */}
<span
onClick={() => this.handleEdits(item.id, item.task)}
className="shift2 mr-1"
>
<i className="fas fa-edit"></i>
</span>
{/* delete button */}
<span onClick={() => this.onRemove(item.id)} className="mr-2">
<i className="shift fas fa-trash ml-20"></i>
</span>
<span
className="shift3"
onClick={() => this.handleStrike(item.id, item.task)}
>
{item.completed ? (
<i className="fas fa-undo-alt"></i>
) : (
<i className="fas fa-check-circle"></i>
)}
</span>
</div>
))}
<br />
<span>
<input
autoFocus={true}
placeholder="Add Todos"
value={this.state.userInput || ""}
onChange={this.handleUserInput}
className="form-control"
/>
<span
style={{ color: "purple" }}
className="addButton"
onClick={() => {
this.handleAddItem();
this.increment();
}}
disabled={!this.state.userInput}
>
<i className="fas fa-plus-square shift ml-20"></i>
</span>
</span>
</div>
);
}
}
export default App;
| a3876370a236ee485fbb89adad90f74bbb5be67d | [
"Markdown",
"JavaScript"
] | 2 | Markdown | YashMarmat/TODO-APP-in-React | e285a1f9541ab4e7c919e39fafeb85c7e6e202dd | ee06e60fa2330a5149286ff5e5f38af5f00422ac |
refs/heads/master | <file_sep>
def get_bmi(h,w):
return w / (h*h)
def get_cond(bmi):
if bmi >= 18.5 and bmi < 25:
return 'normal weight'
elif bmi <18.5:
return 'below normal weight'
elif bmi >=25 and bmi < 30:
return 'overweight'
elif bmi >= 30 and bmi < 35:
return 'class I obesity'
elif bmi >= 35 and bmi < 40:
return 'class II obesity'
elif bmi>=40:
return 'class III obesity'
weight = float(input('weight(kg): '))
height = float(input('height(m): '))
print('bmi: ' + str(get_bmi(height,weight)))
print('condition: ' + str(get_cond(get_bmi(height,weight))))<file_sep>def bubble_sort():
arr = []
try:
for i in range(10):
arr.append(float(input()))
except ValueError:
print("only numbers are accepted as valid input.")
for i in range(10):
for j in range(0, 10 - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
print(bubble_sort())
<file_sep># tdd-task
-added bmi.py
-completed first requirement for bmi
-completed second requirement for bmi
-completed third requirement for bmi
-completed fourth requirement for bmi
*-final version of bmi was pushed*
________________________________
-added bubble_sort.py
-completed first requirement for bubble_sort
-completed second requirement for bubble_sort
-completed third requirement for bubble_sort
-completed fourth requirement for bubble_sort
*-final version of bubble_sort was pushed*
| 26eb03abacde32199c5af0a2d4158e02ececca35 | [
"Markdown",
"Python"
] | 3 | Python | ofekl26/tdd-task | f75a53b64e442844ada47156c0647696d5ebac8a | 30463fb7e4297f9d1069924b6c944363010f4272 |
refs/heads/master | <file_sep>package net.unitecgroup.www.unitecrfid;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.util.ArrayList;
import java.util.Collections;
import static net.unitecgroup.www.unitecrfid.AddAlertDialog.ALERT_DURATION;
import static net.unitecgroup.www.unitecrfid.AddAlertDialog.ALERT_ID;
import static net.unitecgroup.www.unitecrfid.AddAlertDialog.ALERT_POS;
import static net.unitecgroup.www.unitecrfid.AddAlertDialog.ALERT_TIME;
import static net.unitecgroup.www.unitecrfid.AddAlertDialog.ALERT_WEEKDAYS;
/**
*
* http://nemanjakovacevic.net/blog/english/2016/01/12/recyclerview-swipe-to-delete-no-3rd-party-lib-necessary/
* https://github.com/ashrithks/SwipeRecyclerView
*/
public class AlertsActivity extends BaseActivity implements
AddAlertDialog.OnAlertSavedListener,
AlertListAdapter.OnItemDeletedListener {
private static final String ALERT_LIST = "alertList";
private static final String ALERT_DELETE_LIST = "alertDeleteList";
static AlertListAdapter oAlertListAdapter;
RecyclerView mRecyclerView;
FragmentManager fm = getSupportFragmentManager();
AddAlertDialog oAddAlert;
DatabaseTable mDB;
ServerCommunication mServer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alerts);
//Floating Action Button
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
oAddAlert = new AddAlertDialog();
oAddAlert.show(fm, "Dialog Fragment");
}
});
//Receiving query from SEARCH
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//doMySearch(query);
}
mRecyclerView = (RecyclerView) findViewById(R.id.mainListView);
mDB = new DatabaseTable(this);
mServer = new ServerCommunication(this);
// Reading all contacts
ArrayList<Alert> alerts = mDB.getAllAlerts();
//Do not create more than one Adapter to avoid problems with screen rotation
if (oAlertListAdapter == null)
oAlertListAdapter = new AlertListAdapter(this, alerts);
setUpRecyclerView();
}
@Override
protected void onStop() {
super.onStop();
mDB.close();
}
private void setUpRecyclerView() {
oAlertListAdapter.setUndoOn(true);
//mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(oAlertListAdapter);
mRecyclerView.setHasFixedSize(true);
//Create the Alert Edit Dialog, load the previous data.
oAlertListAdapter.SetOnItemClickListener(
new AlertListAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position, String id) {
Bundle args = new Bundle(); //Bundle containing data you are passing to the dialog
//Save alert data to pass it to Dialog
Alert oAlert = oAlertListAdapter.items.get(position);
args.putInt(ALERT_POS, position);
args.putInt(ALERT_ID, oAlert.get_id());
args.putString(ALERT_TIME, oAlert.get_time());
args.putString(ALERT_DURATION, oAlert.get_duration());
args.putIntegerArrayList(ALERT_WEEKDAYS, arrayStringToIntegerArrayList(oAlert.get_weekdays()));
oAddAlert = new AddAlertDialog();
oAddAlert.setArguments(args);
oAddAlert.show(fm, "Dialog Fragment");
}
}
);
setUpItemTouchHelper();
setUpAnimationDecoratorHelper();
}
//Creates a ArrayList<Integer> from String "[1,2,3]"
public static ArrayList<Integer> arrayStringToIntegerArrayList(String arrayString){
String removedBrackets = arrayString.substring(1, arrayString.length() - 1);
String[] individualNumbers = removedBrackets.split(",");
ArrayList<Integer> integerArrayList = new ArrayList<>();
for(String numberString : individualNumbers){
integerArrayList.add(Integer.parseInt(numberString.trim()));
}
Collections.sort(integerArrayList);
return integerArrayList;
}
public void addAlerts() {
ArrayList<Alert> aAlerts = new ArrayList<>();
aAlerts.add(new Alert("06:30", "00:15", "[2,3,4,5,6]"));
aAlerts.add(new Alert("12:00", "00:30", "[2,3]"));
aAlerts.add(new Alert("18:30", "00:10", "[4,5,6]"));
for (Alert cn : aAlerts) {
if (mDB.addAlert(cn) >= 0) {
oAlertListAdapter.addAlert(cn);
}
}
}
public void removeAlerts() {
//This will erase the DB content
mDB.deleteAll();
oAlertListAdapter.removeAll();
}
/**
* This is the standard support library way of implementing "swipe to delete" feature. You can do custom drawing in onChildDraw method
* but whatever you draw will disappear once the swipe is over, and while the items are animating to their new position the recycler view
* background will be visible. That is rarely an desired effect.
*/
private void setUpItemTouchHelper() {
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
// we want to cache these and not allocate anything repeatedly in the onChildDraw method
Drawable background;
Drawable xMark;
int xMarkMargin;
boolean initiated;
private void init() {
background = new ColorDrawable(Color.RED);
xMark = ContextCompat.getDrawable(AlertsActivity.this, R.drawable.ic_clear_24dp);
xMark.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
xMarkMargin = (int) AlertsActivity.this.getResources().getDimension(R.dimen.fab_margin);
initiated = true;
}
// not important, we don't want drag & drop
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
/*
//This is creating problems trying to delete two consecutive rows.
@Override
public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int position = viewHolder.getAdapterPosition();
AlertListAdapter testAdapter = (AlertListAdapter)recyclerView.getAdapter();
if (testAdapter.isUndoOn() && testAdapter.isPendingRemoval(position)) {
return 0;
}
return super.getSwipeDirs(recyclerView, viewHolder);
}
*/
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
int swipedPosition = viewHolder.getAdapterPosition();
AlertListAdapter adapter = (AlertListAdapter)mRecyclerView.getAdapter();
boolean undoOn = adapter.isUndoOn();
if (undoOn) {
adapter.pendingRemoval(swipedPosition);
} else {
adapter.remove(swipedPosition);
}
}
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
View itemView = viewHolder.itemView;
AlertListAdapter adapter = (AlertListAdapter)mRecyclerView.getAdapter();
boolean undoOn = adapter.isUndoOn();
// not sure why, but this method get's called for viewholder that are already swiped away
if (viewHolder.getAdapterPosition() == -1) {
// not interested in those
return;
}
if (!initiated) {
init();
}
// draw red background
background.setBounds(itemView.getRight() + (int) dX, itemView.getTop(), itemView.getRight(), itemView.getBottom());
background.draw(c);
if (!undoOn) {
// draw x mark
int itemHeight = itemView.getBottom() - itemView.getTop();
int intrinsicWidth = xMark.getIntrinsicWidth();
int intrinsicHeight = xMark.getIntrinsicWidth();
int xMarkLeft = itemView.getRight() - xMarkMargin - intrinsicWidth;
int xMarkRight = itemView.getRight() - xMarkMargin;
int xMarkTop = itemView.getTop() + (itemHeight - intrinsicHeight) / 2;
int xMarkBottom = xMarkTop + intrinsicHeight;
xMark.setBounds(xMarkLeft, xMarkTop, xMarkRight, xMarkBottom);
xMark.draw(c);
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
};
ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
mItemTouchHelper.attachToRecyclerView(mRecyclerView);
}
/**
* We're gonna setup another ItemDecorator that will draw the red background in the empty space while the items are animating to thier new positions
* after an item is removed.
*/
private void setUpAnimationDecoratorHelper() {
mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
// we want to cache this and not allocate anything repeatedly in the onDraw method
Drawable background;
boolean initiated;
private void init() {
background = new ColorDrawable(Color.RED);
initiated = true;
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
if (!initiated) {
init();
}
// only if animation is in progress
if (parent.getItemAnimator().isRunning()) {
// some items might be animating down and some items might be animating up to close the gap left by the removed item
// this is not exclusive, both movement can be happening at the same time
// to reproduce this leave just enough items so the first one and the last one would be just a little off screen
// then remove one from the middle
// find first child with translationY > 0
// and last one with translationY < 0
// we're after a rect that is not covered in recycler-view views at this point in time
View lastViewComingDown = null;
View firstViewComingUp = null;
// this is fixed
int left = 0;
int right = parent.getWidth();
// this we need to find out
int top = 0;
int bottom = 0;
// find relevant translating views
int childCount = parent.getLayoutManager().getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getLayoutManager().getChildAt(i);
if (child.getTranslationY() < 0) {
// view is coming down
lastViewComingDown = child;
} else if (child.getTranslationY() > 0) {
// view is coming up
if (firstViewComingUp == null) {
firstViewComingUp = child;
}
}
}
if (lastViewComingDown != null && firstViewComingUp != null) {
// views are coming down AND going up to fill the void
top = lastViewComingDown.getBottom() + (int) lastViewComingDown.getTranslationY();
bottom = firstViewComingUp.getTop() + (int) firstViewComingUp.getTranslationY();
} else if (lastViewComingDown != null) {
// views are going down to fill the void
top = lastViewComingDown.getBottom() + (int) lastViewComingDown.getTranslationY();
bottom = lastViewComingDown.getBottom();
} else if (firstViewComingUp != null) {
// views are coming up to fill the void
top = firstViewComingUp.getTop();
bottom = firstViewComingUp.getTop() + (int) firstViewComingUp.getTranslationY();
}
background.setBounds(left, top, right, bottom);
background.draw(c);
}
super.onDraw(c, parent, state);
}
});
}
/**
* Creates Activity menu
*
* https://developer.android.com/training/appbar/action-views.html
* https://developer.android.com/guide/topics/search/search-dialog.html#SearchableConfiguration
* @param menu
* @return
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.alerts, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
if (searchView != null) {
//TODO: NOT WORKING
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_addAlerts) {
addAlerts();
return true;
} else if (id == R.id.action_removeAlerts) {
removeAlerts();
return true;
} else if (id == R.id.action_updateAlerts) {
oAlertListAdapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected int getNavigationDrawerID() {
return R.id.nav_alerts;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList(ALERT_LIST, oAlertListAdapter.items);
outState.putIntegerArrayList(ALERT_DELETE_LIST, oAlertListAdapter.itemsPendingRemoval);
super.onSaveInstanceState(outState);
}
// This callback is called only when there is a saved instance previously saved using
// onSaveInstanceState(). We restore some state in onCreate() while we can optionally restore
// other state here, possibly usable after onStart() has completed.
// The savedInstanceState Bundle is same as the one used in onCreate().
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
oAlertListAdapter.items = savedInstanceState.getParcelableArrayList(ALERT_LIST);
oAlertListAdapter.itemsPendingRemoval = savedInstanceState.getIntegerArrayList(ALERT_DELETE_LIST);
}
@Override
public void OnAlertSaved(int pos, Alert oAlert) {
if (oAlert.get_id() < 0) {
//Adding new alert to DB
if (mDB.addAlert(oAlert) >= 0) {
oAlertListAdapter.addAlert(oAlert);
}
} else {
//update row at DB
if (mDB.updateAlert(oAlert)) {
oAlertListAdapter.updateAlert(oAlert);
}
}
}
@Override
public boolean OnItemDeleted(int pos, Alert oAlert) {
return mDB.deleteAlert(oAlert);
}
}
| 1280f93b7dc7d6627079546176c9a51510cf3e3f | [
"Java"
] | 1 | Java | vinnyecosta/AlertDemo | 95234d3c3614cb055c8721eea39a4fee75fa99de | 89d328cc653ddac984e45bfc4de9f19a3c77d003 |
refs/heads/master | <file_sep>(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vega-canvas'), require('vega-scenegraph'), require('vega-dataflow'), require('vega-util')) :
typeof define === 'function' && define.amd ? define(['exports', 'vega-canvas', 'vega-scenegraph', 'vega-dataflow', 'vega-util'], factory) :
(factory((global.vegaLabel = {}),global.vega,global.vega,global.vega,global.vega));
}(this, (function (exports,vegaCanvas,vegaScenegraph,vegaDataflow,vegaUtil) { 'use strict';
/*eslint no-console: "warn"*/
/*eslint no-empty: "warn"*/
/**
* Calculate width of `text` with font size `fontSize` and font `font`
* @param {object} context 2d-context of canvas
* @param {string} text the string, which width to be calculated
* @param {number} fontSize font size of `text`
* @param {string} font font of `text`
*/
function labelWidth(context, text, fontSize, font) {
// TODO: support other font properties
context.font = fontSize + 'px ' + font;
return context.measureText(text).width;
}
function checkCollision(x1, y1, x2, y2, bitMap) {
return bitMap.getInRangeScaled(x1, y2, x2, y2) || bitMap.getInRangeScaled(x1, y1, x2, y2 - 1);
}
/*eslint no-console: "warn"*/
const SIZE_FACTOR = 0.707106781186548; // this is 1 over square root of 2
// Options for align
const ALIGN = ['right', 'center', 'left'];
// Options for baseline
const BASELINE = ['bottom', 'middle', 'top'];
class LabelPlacer {
constructor(bitmaps, size, anchors, offsets) {
this.bm0 = bitmaps[0];
this.bm1 = bitmaps[1];
this.width = size[0];
this.height = size[1];
this.anchors = anchors;
this.offsets = offsets;
}
place(d) {
const mb = d.markBound;
// can not be placed if the mark is not visible in the graph bound
if (mb[2] < 0 || mb[5] < 0 || mb[0] > this.width || mb[3] > this.height) {
return false;
}
const context = vegaCanvas.canvas().getContext('2d');
const n = this.offsets.length;
const textHeight = d.textHeight;
const markBound = d.markBound;
const text = d.text;
const font = d.font;
let textWidth = d.textWidth;
let dx, dy, isInside, sizeFactor, insideFactor;
let x, x1, xc, x2, y1, yc, y2;
let _x1, _x2, _y1, _y2;
// for each anchor and offset
for (let i = 0; i < n; i++) {
dx = (this.anchors[i] & 0x3) - 1;
dy = ((this.anchors[i] >>> 0x2) & 0x3) - 1;
isInside = (dx === 0 && dy === 0) || this.offsets[i] < 0;
sizeFactor = dx && dy ? SIZE_FACTOR : 1;
insideFactor = this.offsets[i] < 0 ? -1 : 1;
yc = markBound[4 + dy] + (insideFactor * textHeight * dy) / 2.0 + this.offsets[i] * dy * sizeFactor;
x = markBound[1 + dx] + this.offsets[i] * dx * sizeFactor;
y1 = yc - textHeight / 2.0;
y2 = yc + textHeight / 2.0;
_y1 = this.bm0.scalePixel(y1);
_y2 = this.bm0.scalePixel(y2);
_x1 = this.bm0.scalePixel(x);
if (!textWidth) {
// to avoid finding width of text label,
if (!isLabelPlacable(_x1, _x1, _y1, _y2, this.bm0, this.bm1, x, x, y1, y2, markBound, isInside)) {
// skip this anchor/offset option if fail to place the label with 1px width
continue;
} else {
// Otherwise, find the label width
textWidth = labelWidth(context, text, textHeight, font);
}
}
xc = x + (insideFactor * textWidth * dx) / 2.0;
x1 = xc - textWidth / 2.0;
x2 = xc + textWidth / 2.0;
_x1 = this.bm0.scalePixel(x1);
_x2 = this.bm0.scalePixel(x2);
if (isLabelPlacable(_x1, _x2, _y1, _y2, this.bm0, this.bm1, x1, x2, y1, y2, markBound, isInside)) {
// place label if the position is placable
d.x = !dx ? xc : dx * insideFactor < 0 ? x2 : x1;
d.y = !dy ? yc : dy * insideFactor < 0 ? y2 : y1;
d.align = ALIGN[dx * insideFactor + 1];
d.baseline = BASELINE[dy * insideFactor + 1];
this.bm0.markInRangeScaled(_x1, _y1, _x2, _y2);
return true;
}
}
return false;
}
}
function isLabelPlacable(_x1, _x2, _y1, _y2, bm0, bm1, x1, x2, y1, y2, markBound, isInside) {
return !(
bm0.searchOutOfBound(_x1, _y1, _x2, _y2) ||
(isInside
? checkCollision(_x1, _y1, _x2, _y2, bm1) || !isInMarkBound(x1, y1, x2, y2, markBound)
: checkCollision(_x1, _y1, _x2, _y2, bm0))
);
}
function isInMarkBound(x1, y1, x2, y2, markBound) {
return markBound[0] <= x1 && x2 <= markBound[2] && markBound[3] <= y1 && y2 <= markBound[5];
}
/*eslint no-console: "warn"*/
const X_DIR = [-1, -1, 1, 1];
const Y_DIR = [-1, 1, -1, 1];
class AreaLabelPlacer {
constructor(bitmaps, size, avoidBaseMark) {
this.bm0 = bitmaps[0];
this.bm1 = bitmaps[1];
this.bm2 = bitmaps[2];
this.width = size[0];
this.height = size[1];
this.avoidBaseMark = avoidBaseMark;
}
place(d) {
const context = vegaCanvas.canvas().getContext('2d');
const items = d.datum.datum.items[0].items;
const n = items.length;
const textHeight = d.textHeight;
const textWidth = labelWidth(context, d.text, textHeight, d.font);
const pixelRatio = this.bm1.getPixelRatio();
const stack = new Stack();
let maxSize = this.avoidBaseMark ? textHeight : 0;
let labelPlaced = false;
let labelPlaced2 = false;
let maxAreaWidth = 0;
let x1, x2, y1, y2, x, y, _x, _y, lo, hi, mid, areaWidth, coordinate, nextX, nextY;
for (let i = 0; i < n; i++) {
x1 = items[i].x;
y1 = items[i].y;
x2 = items[i].x2 === undefined ? x1 : items[i].x2;
y2 = items[i].y2 === undefined ? y1 : items[i].y2;
stack.push(this.bm0.scalePixel((x1 + x2) / 2.0), this.bm0.scalePixel((y1 + y2) / 2.0));
while (!stack.isEmpty()) {
coordinate = stack.pop();
_x = coordinate[0];
_y = coordinate[1];
if (!this.bm0.getScaled(_x, _y) && !this.bm1.getScaled(_x, _y) && !this.bm2.getScaled(_x, _y)) {
this.bm2.markScaled(_x, _y);
for (let j = 0; j < 4; j++) {
nextX = _x + X_DIR[j];
nextY = _y + Y_DIR[j];
if (!this.bm2.searchOutOfBound(nextX, nextY, nextX, nextY)) {
stack.push(nextX, nextY);
}
}
x = _x * pixelRatio - this.bm0.padding;
y = _y * pixelRatio - this.bm0.padding;
lo = maxSize;
hi = this.height; // Todo: make this bound smaller;
if (
!checkLabelOutOfBound(x, y, textWidth, textHeight, this.width, this.height) &&
!collide(x, y, textHeight, textWidth, lo, this.bm0, this.bm1)
) {
while (hi - lo >= 1) {
mid = (lo + hi) / 2;
if (collide(x, y, textHeight, textWidth, mid, this.bm0, this.bm1)) {
hi = mid;
} else {
lo = mid;
}
}
if (lo > maxSize) {
d.x = x;
d.y = y;
maxSize = lo;
labelPlaced = true;
}
}
}
}
if (!labelPlaced && !this.avoidBaseMark) {
areaWidth = Math.abs(x2 - x1 + y2 - y1);
x = (x1 + x2) / 2.0;
y = (y1 + y2) / 2.0;
if (
areaWidth >= maxAreaWidth &&
!checkLabelOutOfBound(x, y, textWidth, textHeight, this.width, this.height) &&
!collide(x, y, textHeight, textWidth, textHeight, this.bm0, null)
) {
maxAreaWidth = areaWidth;
d.x = x;
d.y = y;
labelPlaced2 = true;
}
}
}
if (labelPlaced || labelPlaced2) {
x1 = this.bm0.scalePixel(d.x - textWidth / 2.0);
y1 = this.bm0.scalePixel(d.y - textHeight / 2.0);
x2 = this.bm0.scalePixel(d.x + textWidth / 2.0);
y2 = this.bm0.scalePixel(d.y + textHeight / 2.0);
this.bm0.markInRangeScaled(x1, y1, x2, y2);
d.align = 'center';
d.baseline = 'middle';
return true;
}
d.align = 'left';
d.baseline = 'top';
return false;
}
}
function checkLabelOutOfBound(x, y, textWidth, textHeight, width, height) {
return (
x - textWidth / 2.0 < 0 || y - textHeight / 2.0 < 0 || x + textWidth / 2.0 > width || y + textHeight / 2.0 > height
);
}
function collide(x, y, textHeight, textWidth, h, bm0, bm1) {
const w = (textWidth * h) / (textHeight * 2.0);
h = h / 2.0;
const _x1 = bm0.scalePixel(x - w);
const _x2 = bm0.scalePixel(x + w);
const _y1 = bm0.scalePixel(y - h);
const _y2 = bm0.scalePixel(y + h);
return (
bm0.searchOutOfBound(_x1, _y1, _x2, _y2) ||
checkCollision(_x1, _y1, _x2, _y2, bm0) ||
(bm1 && checkCollision(_x1, _y1, _x2, _y2, bm1))
);
}
class Stack {
constructor() {
this.size = 100;
this.xStack = new Int32Array(this.size);
this.yStack = new Int32Array(this.size);
this.idx = 0;
}
push(x, y) {
if (this.idx === this.size - 1) resizeStack(this);
this.xStack[this.idx] = x;
this.yStack[this.idx] = y;
this.idx++;
}
pop() {
if (this.idx > 0) {
this.idx--;
return [this.xStack[this.idx], this.yStack[this.idx]];
} else {
return null;
}
}
isEmpty() {
return this.idx <= 0;
}
}
function resizeStack(obj) {
const newXStack = new Int32Array(obj.size * 2);
const newYStack = new Int32Array(obj.size * 2);
for (let i = 0; i < obj.idx; i++) {
newXStack[i] = obj.xStack[i];
newYStack[i] = obj.yStack[i];
}
obj.xStack = newXStack;
obj.yStack = newYStack;
obj.size *= 2;
}
/*eslint no-fallthrough: "warn" */
const DIV = 0x5;
const MOD = 0x1f;
const SIZE = 0x20;
const right0 = new Uint32Array(SIZE + 1);
const right1 = new Uint32Array(SIZE + 1);
right1[0] = 0x0;
right0[0] = ~right1[0];
for (let i = 1; i <= SIZE; i++) {
right1[i] = (right1[i - 1] << 0x1) | 0x1;
right0[i] = ~right1[i];
}
function applyMark(array, index, mask) {
array[index] |= mask;
}
function applyUnmark(array, index, mask) {
array[index] &= mask;
}
class BitMap {
constructor(width, height, padding) {
this.pixelRatio = Math.sqrt((width * height) / 1000000.0);
// bound pixelRatio to be not less than 1
if (this.pixelRatio < 1) {
this.pixelRatio = 1;
}
this.padding = padding;
this.width = ~~((width + 2 * padding + this.pixelRatio) / this.pixelRatio);
this.height = ~~((height + 2 * padding + this.pixelRatio) / this.pixelRatio);
this.array = new Uint32Array(~~((this.width * this.height + SIZE) / SIZE));
}
/**
* Get pixel ratio between real size and bitmap size
* @returns pixel ratio between real size and bitmap size
*/
getPixelRatio() {
return this.pixelRatio;
}
/**
* Scale real pixel in the chart into bitmap pixel
* @param realPixel the real pixel to be scaled down
* @returns scaled pixel
*/
scalePixel(realPixel) {
return ~~((realPixel + this.padding) / this.pixelRatio);
}
markScaled(x, y) {
const mapIndex = y * this.width + x;
applyMark(this.array, mapIndex >>> DIV, 1 << (mapIndex & MOD));
}
mark(x, y) {
this.markScaled(this.scalePixel(x), this.scalePixel(y));
}
unmarkScaled(x, y) {
const mapIndex = y * this.width + x;
applyUnmark(this.array, mapIndex >>> DIV, ~(1 << (mapIndex & MOD)));
}
unmark(x, y) {
this.unmarkScaled(this.scalePixel(x), this.scalePixel(y));
}
getScaled(x, y) {
const mapIndex = y * this.width + x;
return this.array[mapIndex >>> DIV] & (1 << (mapIndex & MOD));
}
get(x, y) {
return this.getScaled(this.scalePixel(x), this.scalePixel(y));
}
markInRangeScaled(x, y, x2, y2) {
let start, end, indexStart, indexEnd;
for (; y <= y2; y++) {
start = y * this.width + x;
end = y * this.width + x2;
indexStart = start >>> DIV;
indexEnd = end >>> DIV;
if (indexStart === indexEnd) {
applyMark(this.array, indexStart, right0[start & MOD] & right1[(end & MOD) + 1]);
} else {
applyMark(this.array, indexStart, right0[start & MOD]);
applyMark(this.array, indexEnd, right1[(end & MOD) + 1]);
for (let i = indexStart + 1; i < indexEnd; i++) {
applyMark(this.array, i, 0xffffffff);
}
}
}
}
markInRange(x, y, x2, y2) {
return this.markInRangeScaled(this.scalePixel(x), this.scalePixel(y), this.scalePixel(x2), this.scalePixel(y2));
}
unmarkInRangeScaled(x, y, x2, y2) {
let start, end, indexStart, indexEnd;
for (; y <= y2; y++) {
start = y * this.width + x;
end = y * this.width + x2;
indexStart = start >>> DIV;
indexEnd = end >>> DIV;
if (indexStart === indexEnd) {
applyUnmark(this.array, indexStart, right1[start & MOD] | right0[(end & MOD) + 1]);
} else {
applyUnmark(this.array, indexStart, right1[start & MOD]);
applyUnmark(this.array, indexEnd, right0[(end & MOD) + 1]);
for (let i = indexStart + 1; i < indexEnd; i++) {
applyUnmark(this.array, i, 0x0);
}
}
}
}
unmarkInRange(x, y, x2, y2) {
return this.unmarkInRangeScaled(this.scalePixel(x), this.scalePixel(y), this.scalePixel(x2), this.scalePixel(y2));
}
getInRangeScaled(x, y, x2, y2) {
let start, end, indexStart, indexEnd;
for (; y <= y2; y++) {
start = y * this.width + x;
end = y * this.width + x2;
indexStart = start >>> DIV;
indexEnd = end >>> DIV;
if (indexStart === indexEnd) {
if (this.array[indexStart] & right0[start & MOD] & right1[(end & MOD) + 1]) {
return true;
}
} else {
if (this.array[indexStart] & right0[start & MOD]) {
return true;
}
if (this.array[indexEnd] & right1[(end & MOD) + 1]) {
return true;
}
for (let i = indexStart + 1; i < indexEnd; i++) {
if (this.array[i]) {
return true;
}
}
}
}
return false;
}
getInRange(x, y, x2, y2) {
return this.getInRangeScaled(this.scalePixel(x), this.scalePixel(y), this.scalePixel(x2), this.scalePixel(y2));
}
searchOutOfBound(x, y, x2, y2) {
return x < 0 || y < 0 || y2 >= this.height || x2 >= this.width;
}
}
// static function
// bit mask for getting first 2 bytes of alpha value
const ALPHA_MASK = 0xff000000;
// alpha value equivalent to opacity 0.0625
const INSIDE_OPACITY_IN_ALPHA = 0x10000000;
const INSIDE_OPACITY = 0.0625;
/**
* Get bitmaps and fill the with mark information from data
* @param {array} data data of labels to be placed
* @param {array} size size of chart in format [width, height]
* @param {string} marktype marktype of the base mark
* @param {bool} avoidBaseMark a flag if base mark is to be avoided
* @param {array} avoidMarks array of mark data to be avoided
* @param {bool} labelInside a flag if label to be placed inside mark or not
* @param {number} padding padding from the boundary of the chart
*
* @returns array of 2 bitmaps:
* - first bitmap is filled with all the avoiding marks
* - second bitmap is filled with borders of all the avoiding marks (second bit map can be
* undefined if checking border of base mark is not needed when not avoiding any mark)
*/
function prepareBitmap(data, size, marktype, avoidBaseMark, avoidMarks, labelInside, padding) {
const isGroupArea = marktype === 'group' && data[0].datum.datum.items[0].marktype === 'area';
const width = size[0];
const height = size[1];
const n = data.length;
// extract data information from base mark when base mark is to be avoid
// or base mark is implicitly avoid when base mark is group area
if (marktype && (avoidBaseMark || isGroupArea)) {
const items = new Array(n);
for (let i = 0; i < n; i++) {
items[i] = data[i].datum.datum;
}
avoidMarks.push(items);
}
if (avoidMarks.length) {
// when there is at least one mark to be avoided
const context = writeToCanvas(avoidMarks, width, height, labelInside || isGroupArea);
return writeToBitMaps(context, width, height, labelInside, isGroupArea, padding);
} else {
const bitMap = new BitMap(width, height, padding);
if (avoidBaseMark) {
// when there is no base mark but data points are to be avoided
for (let i = 0; i < n; i++) {
const d = data[i];
bitMap.mark(d.markBound[0], d.markBound[3]);
}
}
return [bitMap, undefined];
}
}
/**
* Write marks to be avoided to canvas to be written to bitmap later
* @param {array} avoidMarks array of mark data to be avoided
* @param {number} width width of the chart
* @param {number} height height of the chart
* @param {bool} labelInside a flag if label to be placed inside mark or not
*
* @returns canvas context, to which all avoiding marks are drawn
*/
function writeToCanvas(avoidMarks, width, height, labelInside) {
const m = avoidMarks.length;
// const c = document.getElementById('canvas-render'); // debugging canvas
const c = document.createElement('canvas');
const context = c.getContext('2d');
let originalItems, itemsLen;
c.setAttribute('width', width);
c.setAttribute('height', height);
// draw every avoiding marks into canvas
for (let i = 0; i < m; i++) {
originalItems = avoidMarks[i];
itemsLen = originalItems.length;
if (!itemsLen) {
continue;
}
if (originalItems[0].mark.marktype !== 'group') {
drawMark(context, originalItems, labelInside);
} else {
drawGroup(context, originalItems, labelInside);
}
}
return context;
}
/**
* Write avoid marks from drawn canvas to bitmap
* @param {object} context canvas context, to which all avoiding marks are drawn
* @param {number} width width of the chart
* @param {number} height height of the chart
* @param {bool} labelInside a flag if label to be placed inside mark or not
* @param {bool} isGroupArea a flag if the base mark if group area
* @param {number} padding padding from the boundary of the chart
*
* @returns array of 2 bitmaps:
* - first bitmap is filled with all the avoiding marks
* - second bitmap is filled with borders of all the avoiding marks
*/
function writeToBitMaps(context, width, height, labelInside, isGroupArea, padding) {
const layer1 = new BitMap(width, height, padding);
const layer2 = (labelInside || isGroupArea) && new BitMap(width, height, padding);
const imageData = context.getImageData(0, 0, width, height);
const canvasBuffer = new Uint32Array(imageData.data.buffer);
let x, y, alpha;
if (isGroupArea) {
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
alpha = canvasBuffer[y * width + x] & ALPHA_MASK;
// only fill second layer for group area because labels are only not allowed to place over
// border of area
if (alpha && alpha ^ INSIDE_OPACITY_IN_ALPHA) {
layer2.mark(x, y);
}
}
}
} else {
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
alpha = canvasBuffer[y * width + x] & ALPHA_MASK;
if (alpha) {
// fill first layer if there is something in canvas in that location
layer1.mark(x, y);
// fill second layer if there is a border in canvas in that location
// and label can be placed inside
if (labelInside && alpha ^ INSIDE_OPACITY_IN_ALPHA) {
layer2.mark(x, y);
}
}
}
}
}
return [layer1, layer2];
}
/**
* Draw mark into canvas
* @param {object} context canvas context, to which all avoiding marks are drawn
* @param {array} originalItems mark to be drawn into canvas
* @param {bool} labelInside a flag if label to be placed inside mark or not
*/
function drawMark(context, originalItems, labelInside) {
const n = originalItems.length;
let items;
if (labelInside) {
items = new Array(n);
for (let i = 0; i < n; i++) {
items[i] = prepareMarkItem(originalItems[i]);
}
} else {
items = originalItems;
}
// draw items into canvas
vegaScenegraph.Marks[items[0].mark.marktype].draw(context, {items: items}, null);
}
/**
* draw group of marks into canvas
* @param {object} context canvas context, to which all avoiding marks are drawn
* @param {array} groups group of marks to be drawn into canvas
* @param {bool} labelInside a flag if label to be placed inside mark or not
*/
function drawGroup(context, groups, labelInside) {
const n = groups.length;
let marks;
for (let i = 0; i < n; i++) {
marks = groups[i].items;
for (let j = 0; j < marks.length; j++) {
const g = marks[j];
if (g.marktype !== 'group') {
drawMark(context, g.items, labelInside);
} else {
// recursivly draw group of marks
drawGroup(context, g.items, labelInside);
}
}
}
}
/**
* Prepare item before drawing into canvas (setting stroke and opacity)
* @param {object} originalItem item to be prepared
*
* @returns prepared item
*/
function prepareMarkItem(originalItem) {
const item = {};
for (const key in originalItem) {
item[key] = originalItem[key];
}
if (item.stroke) {
item.strokeOpacity = 1;
}
if (item.fill) {
item.fillOpacity = INSIDE_OPACITY;
item.stroke = '#000';
item.strokeOpacity = 1;
item.strokeWidth = 2;
}
return item;
}
/*eslint no-console: "warn"*/
// 8-bit representation of anchors
const TOP = 0x0,
MIDDLE = 0x1 << 0x2,
BOTTOM = 0x2 << 0x2,
LEFT = 0x0,
CENTER = 0x1,
RIGHT = 0x2;
// Dictionary mapping from text anchor to its number representation
const anchorTextToNumber = {
'top-left': TOP + LEFT,
top: TOP + CENTER,
'top-right': TOP + RIGHT,
left: MIDDLE + LEFT,
middle: MIDDLE + CENTER,
right: MIDDLE + RIGHT,
'bottom-left': BOTTOM + LEFT,
bottom: BOTTOM + CENTER,
'bottom-right': BOTTOM + RIGHT
};
function labelLayout() {
let offsets, sort, anchors, avoidMarks, size;
let avoidBaseMark, lineAnchor, markIndex, padding;
let label = {},
texts = [];
label.layout = function() {
const n = texts.length;
if (!n) {
// return immediately when there is not a label to be placed
return texts;
}
if (!size || size.length !== 2) {
throw Error('Size of chart should be specified as an array of width and height');
}
const data = new Array(n);
const marktype = texts[0].datum && texts[0].datum.mark && texts[0].datum.mark.marktype;
const grouptype = marktype === 'group' && texts[0].datum.items[markIndex].marktype;
const getMarkBoundary = getMarkBoundaryFactory(marktype, grouptype, lineAnchor, markIndex);
const getOriginalOpacity = getOriginalOpacityFactory(texts[0].transformed);
// prepare text mark data for placing
for (let i = 0; i < n; i++) {
const d = texts[i];
data[i] = {
textWidth: undefined,
textHeight: d.fontSize, // fontSize represents text height of a text
fontSize: d.fontSize,
font: d.font,
text: d.text,
sort: sort && sort(d.datum),
markBound: getMarkBoundary(d),
originalOpacity: getOriginalOpacity(d),
opacity: 0,
datum: d
};
}
if (sort) {
// sort field has to be primitive variable type
data.sort((a, b) => a.sort - b.sort);
}
// a flag for determining if it is possible for label to be placed inside its base mark
let labelInside = false;
for (let i = 0; i < anchors.length && !labelInside; i++) {
// label inside if anchor is at center
// label inside if offset to be inside the mark bound
labelInside |= anchors[i] === 0x5 || offsets[i] < 0;
}
const bitmaps = prepareBitmap(data, size, marktype, avoidBaseMark, avoidMarks, labelInside, padding);
if (grouptype === 'area') {
// area chart need another bitmap to find the shape of each area
bitmaps.push(new BitMap(size[0], size[1], padding));
}
const labelPlacer =
grouptype === 'area'
? new AreaLabelPlacer(bitmaps, size, avoidBaseMark)
: new LabelPlacer(bitmaps, size, anchors, offsets);
// place all label
for (let i = 0; i < n; i++) {
const d = data[i];
if (d.originalOpacity !== 0 && labelPlacer.place(d)) {
d.opacity = d.originalOpacity;
}
}
return data;
};
label.texts = function(_) {
if (arguments.length) {
texts = _;
return label;
} else {
return texts;
}
};
label.offset = function(_, len) {
if (arguments.length) {
const n = _.length;
offsets = new Float64Array(len);
for (let i = 0; i < n; i++) {
offsets[i] = _[i] || 0;
}
for (let i = n; i < len; i++) {
offsets[i] = offsets[n - 1];
}
return label;
} else {
return offsets;
}
};
label.anchor = function(_, len) {
if (arguments.length) {
const n = _.length;
anchors = new Int8Array(len);
for (let i = 0; i < n; i++) {
anchors[i] |= anchorTextToNumber[_[i]];
}
for (let i = n; i < len; i++) {
anchors[i] = anchors[n - 1];
}
return label;
} else {
return anchors;
}
};
label.sort = function(_) {
if (arguments.length) {
sort = _;
return label;
} else {
return sort;
}
};
label.avoidMarks = function(_) {
if (arguments.length) {
avoidMarks = _;
return label;
} else {
return sort;
}
};
label.size = function(_) {
if (arguments.length) {
size = _;
return label;
} else {
return size;
}
};
label.avoidBaseMark = function(_) {
if (arguments.length) {
avoidBaseMark = _;
return label;
} else {
return avoidBaseMark;
}
};
label.lineAnchor = function(_) {
if (arguments.length) {
lineAnchor = _;
return label;
} else {
return lineAnchor;
}
};
label.markIndex = function(_) {
if (arguments.length) {
markIndex = _;
return label;
} else {
return markIndex;
}
};
label.padding = function(_) {
if (arguments.length) {
padding = _;
return label;
} else {
return padding;
}
};
return label;
}
/**
* Factory function for geting original opacity from a data point information.
* @param {boolean} transformed a boolean flag if data points are already transformed
*
* @return a function that return originalOpacity property of a data point if
* transformed. Otherwise, a function that return .opacity property of a data point
*/
function getOriginalOpacityFactory(transformed) {
if (transformed) {
return d => d.originalOpacity;
} else {
return d => d.opacity;
}
}
/**
* Factory function for function for getting base mark boundary, depending on mark and group type.
* When mark type is undefined, line or area: boundary is the coordinate of each data point.
* When base mark is grouped line, boundary is either at the beginning or end of the line depending
* on the value of lineAnchor.
* Otherwise, use boundary of base mark.
*
* @param {string} marktype mark type of base mark (marktype can be undefined if label does not use
* reactive geometry to any other mark)
* @param {string} grouptype group type of base mark if mark type is 'group' (grouptype can be
* undefined if the base mark is not in group)
* @param {string} lineAnchor anchor point of group line mark if group type is 'line' can be either
* 'begin' or 'end'
* @param {number} markIndex index of base mark if base mark is in a group with multiple marks
*
* @returns function(d) for getting mark boundary from data point information d
*/
function getMarkBoundaryFactory(marktype, grouptype, lineAnchor, markIndex) {
if (!marktype) {
// no reactive geometry
return d => [d.x, d.x, d.x, d.y, d.y, d.y];
} else if (marktype === 'line' || marktype === 'area') {
return function(d) {
const datum = d.datum;
return [datum.x, datum.x, datum.x, datum.y, datum.y, datum.y];
};
} else if (grouptype === 'line') {
const endItemIndex = lineAnchor === 'begin' ? m => m - 1 : () => 0;
return function(d) {
const items = d.datum.items[markIndex].items;
const m = items.length;
if (m) {
// this line has at least 1 item
const endItem = items[endItemIndex(m)];
return [endItem.x, endItem.x, endItem.x, endItem.y, endItem.y, endItem.y];
} else {
// empty line
const minInt = Number.MIN_SAFE_INTEGER;
return [minInt, minInt, minInt, minInt, minInt, minInt];
}
};
} else {
return function(d) {
const b = d.datum.bounds;
return [b.x1, (b.x1 + b.x2) / 2.0, b.x2, b.y1, (b.y1 + b.y2) / 2.0, b.y2];
};
}
}
/*eslint no-console: "warn"*/
const Output = ['x', 'y', 'opacity', 'align', 'baseline', 'originalOpacity', 'transformed'];
const Params = ['offset'];
const defaultAnchors = ['top-left', 'left', 'bottom-left', 'top', 'bottom', 'top-right', 'right', 'bottom-right'];
function Label(params) {
vegaDataflow.Transform.call(this, labelLayout(), params);
}
Label.Definition = {
type: 'Label',
metadata: {modifies: true},
params: [
{name: 'padding', type: 'number', default: 0},
{name: 'markIndex', type: 'number', default: 0},
{name: 'lineAnchor', type: 'string', values: ['begin', 'end'], default: 'end'},
{name: 'avoidBaseMark', type: 'boolean', default: true},
{name: 'size', type: 'number', array: true, length: [2]},
{name: 'offset', type: 'number', default: [1]},
{name: 'sort', type: 'field'},
{name: 'anchor', type: 'string', default: defaultAnchors},
{name: 'avoidMarks', type: 'data', array: true},
{
name: 'as',
type: 'string',
array: true,
length: Output.length,
default: Output
}
]
};
const prototype = vegaUtil.inherits(Label, vegaDataflow.Transform);
prototype.transform = function(_, pulse) {
function modp(param) {
const p = _[param];
return vegaUtil.isFunction(p) && pulse.modified(p.fields);
}
const mod = _.modified();
if (!(mod || pulse.changed(pulse.ADD_REM) || Params.some(modp))) return;
const data = pulse.materialize(pulse.SOURCE).source;
const labelLayout$$1 = this.value;
const as = _.as || Output;
const offset = Array.isArray(_.offset) ? _.offset : Number.isFinite(_.offset) ? [_.offset] : [1];
const anchor = Array.isArray(_.anchor) ? _.anchor : typeof _.anchor === 'string' ? [_.anchor] : defaultAnchors;
const numberPositions = Math.max(offset.length, anchor.length);
// configure layout
const labels = labelLayout$$1
.texts(data)
.sort(_.sort)
.offset(offset, numberPositions)
.anchor(anchor, numberPositions)
.avoidMarks(_.avoidMarks || [])
.size(_.size)
.avoidBaseMark(_.avoidBaseMark !== undefined ? _.avoidBaseMark : true)
.lineAnchor(_.lineAnchor || 'end')
.markIndex(_.markIndex || 0)
.padding(_.padding || 0)
.layout();
const n = data.length;
// fill the information of transformed labels back into data
let l, t;
for (let i = 0; i < n; i++) {
l = labels[i];
t = l.datum;
t[as[0]] = l.x;
t[as[1]] = l.y;
t[as[2]] = l.opacity;
t[as[3]] = l.align;
t[as[4]] = l.baseline;
t[as[5]] = l.originalOpacity;
t[as[6]] = true;
}
return pulse.reflow(mod).modifies(as);
};
exports.label = Label;
exports.BitMap = BitMap;
exports.labelWidth = labelWidth;
Object.defineProperty(exports, '__esModule', { value: true });
})));
<file_sep>This Jupyter notebook was provided to participants during first-use studies as described in Section 6 of our paper.
You can open the notebook with Google Colab [here](https://colab.research.google.com/github/mitvis/embedding-comparator/blob/master/first_use_study/EC_Interview_Template.ipynb).
<file_sep>"""Preprocesses embedding data for Embedding Comparator.
Computes the local neighborhoods of each object in the embedding model and
dimensionality reduction of all objects with PCA, t-SNE, and UMAP. Write output
as JSON.
The embeddings file should contain the embedding vectors, one embedding per line
and each dimension of embedding tab-separated.
The metadata file should contain the label of each embedding, one per line,
in the same order as embeddings_file.
Note: this script should be used to preprocess each model independently.
Example usage:
python preprocess_data.py \
--embeddings_file=raw_data/glove_6b_vs_twitter/glove_6B_vs_twitter_100d_6B_vectors.tsv \
--metadata_file=raw_data/glove_6b_vs_twitter/glove_6B_vs_twitter_100d_6B_words.tsv \
--outfile=data/glove_6b_vs_twitter/6B_preprocessed.json \
--max_k=250
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import json
import logging
import numpy as np
import sklearn.decomposition as decomposition
import sklearn.manifold as manifold
import sklearn.neighbors as neighbors
import umap
DISTANCE_METRICS = ['cosine', 'euclidean']
def _round_list(l, decimals):
return list(map(lambda x: round(x, decimals), l))
def load_embeddings(filepath):
embeddings = []
with open(filepath, 'r') as f:
for row in f:
embeddings.append(list(map(float, row.strip().split('\t'))))
return np.array(embeddings)
def load_words(filepath):
words = []
with open(filepath, 'r') as f:
for row in f:
words.append(row.strip())
return words
def compute_nearest_neighbors(embeddings, max_k, metric):
neigh = neighbors.NearestNeighbors(n_neighbors=max_k, metric=metric)
neigh.fit(embeddings)
dist, ind = neigh.kneighbors(return_distance=True)
return ind, dist
def create_nearest_neighbors_dicts(embeddings, max_k, metrics, float_decimals):
to_return = [
{metric: None for metric in metrics} for _ in range(len(embeddings))
]
for metric in metrics:
inds, dists = compute_nearest_neighbors(embeddings, max_k, metric)
for i, (ind, dist) in enumerate(zip(inds, dists)):
to_return[i][metric] = {
'knn_ind': ind.tolist(),
'knn_dist': _round_list(dist.tolist(), float_decimals),
}
return to_return
def create_preprocessed_data(embeddings, words, nn_dicts, embeddings_pca,
embeddings_tsne, embeddings_umap, float_decimals):
to_return = []
for i, (embedding, word, nn_dict, embedding_pca, embedding_tsne, embedding_umap) in enumerate(
zip(embeddings, words, nn_dicts, embeddings_pca, embeddings_tsne, embeddings_umap)):
to_return.append({
'idx': i,
'word': word,
#'embedding': list(embedding),
'nearest_neighbors': nn_dict,
'embedding_pca': _round_list(embedding_pca.tolist(), float_decimals),
'embedding_tsne': _round_list(embedding_tsne.tolist(), float_decimals),
'embedding_umap': _round_list(embedding_umap.tolist(), float_decimals),
})
return to_return
def run_pca(embeddings):
pca = decomposition.PCA(n_components=2)
return pca.fit_transform(embeddings)
def run_tsne(embeddings):
tsne = manifold.TSNE(n_components=2)
return tsne.fit_transform(embeddings)
def run_umap(embeddings):
reducer = umap.UMAP()
return reducer.fit_transform(embeddings)
def write_outfile(outfile_path, preprocessed_data):
with open(outfile_path, 'w') as f:
json.dump(preprocessed_data, f, separators=(',', ':'))
def main():
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument('--embeddings_file', type=str, required=True,
help='Path to embeddings file (tsv).')
parser.add_argument('--metadata_file', type=str, required=True,
help='Path to metadata file (tsv).')
parser.add_argument('--outfile', type=str, required=True,
help='Path to write preprocessed data (json).')
parser.add_argument('--max_k', type=int, default=250,
help='Max value of K for defining local neighborhoods (default = 250).')
parser.add_argument('--float_decimals', type=int, default=5,
help='Number of decimals to round floats in outfile (default = 5).')
args = parser.parse_args()
# Load embeddings and words from file.
embeddings = load_embeddings(args.embeddings_file)
words = load_words(args.metadata_file)
# Compute nearest neighbors.
nn_dicts = create_nearest_neighbors_dicts(
embeddings, args.max_k, DISTANCE_METRICS, args.float_decimals)
embeddings_pca = run_pca(embeddings)
embeddings_tsne = run_tsne(embeddings)
embeddings_umap = run_umap(embeddings)
preprocessed_data = create_preprocessed_data(
embeddings, words, nn_dicts, embeddings_pca, embeddings_tsne,
embeddings_umap, args.float_decimals,
)
# Write preprocessed data to outfile.
logging.info('Writing data to outfile: %s' % args.outfile)
write_outfile(args.outfile, preprocessed_data)
if __name__ == '__main__':
main()
<file_sep># Embedding Comparator
This repository contains code for the paper:
[Embedding Comparator: Visualizing Differences in Global Structure and Local Neighborhoods via Small Multiples](https://dl.acm.org/doi/10.1145/3490099.3511122)
<br>
Authors: <NAME>, <NAME>, <NAME>
<br>
IUI 2022
### Embedding Comparator Demo
#### Live Demo
A demo of the Embedding Comparator is available at: <http://vis.mit.edu/embedding-comparator/>
#### Run Locally
You can also run the Embedding Comparator demo locally by cloning this repository and starting a web server, e.g., by running `python3 -m http.server` (Python 3) or `python -m SimpleHTTPServer` (Python 2), and then opening <http://localhost:8000/index.html>.
The case study demos in the paper (preprocessed data) are included in the `data/` directory of this repository.
Due to file size constraints, raw data for these demos (including original embeddings and words in tsv format) can be downloaded [here](http://vis.mit.edu/embedding-comparator/raw_data/).
We recommend viewing the Embedding Comparator in Google Chrome.
### Adding your own Models
Adding your own models to the Embedding Comparator involves two steps:
1. Preprocess each model with the [preprocess_data.py](preprocess_data.py) Python script (details and example in script docstring).
2. Modify the `DATASET_TO_MODELS` object at the top of [embedding_comparator_react.js](embedding_comparator_react.js), adding the model details and path to the processed data (see examples for demo models).
### Citation
If you find the Embedding Comparator useful in your work, please cite:
```bib
@inproceedings{embedding-comparator,
title={{Embedding Comparator}: Visualizing Differences in Global Structure and Local Neighborhoods via Small Multiples},
author={<NAME> and <NAME> and <NAME>},
publisher={Association for Computing Machinery},
booktitle={International Conference on Intelligent User Interfaces (IUI)},
pages={746–766},
year={2022}
}
```
<file_sep>vega.transforms.label = vegaLabel.label;
const CATEGORICAL_COLORS = ["#71bb75", "#a67fb6", "#333"];
const DEFAULT_VEGA_SPEC = {
"$schema": "https://vega.github.io/schema/vega/v5.json",
"autosize": "fit",
"padding": 0,
"width": 470,
"height": 210,
"data": [
{
"name": "data_0",
"values": [],
"transform": [
{
"type": "filter",
"expr": "datum[\"x\"] !== null && !isNaN(datum[\"x\"]) && datum[\"y\"] !== null && !isNaN(datum[\"y\"])"
}
]
}
],
"signals": [
{
"name": "hover",
"on": [
{"events": "mouseover", "update": "datum && (datum.datum || datum)"},
{"events": "mouseout", "update": "null"},
]
},
{
"name": "cell_stroke",
"value": null,
"on": [
{"events": "dblclick", "update": "cell_stroke ? null : 'brown'"},
{"events": "mousedown!", "update": "cell_stroke"}
]
}
],
"marks": [
{
"type": "group",
"from": {
"facet": {
"data": "data_0",
"name": "facet",
"groupby": "model"
}
},
"encode": {
"update": {
"x": {"scale": "model", "field": "model"},
"y": {"value": 0},
"width": {"scale": "model", "band": true},
"height": {"signal": "height"},
"stroke": {"value": "#999"},
"clip": {"value": true}
}
},
"signals": [
{"name": "width", "update": "bandwidth('model')"},
{"name": "height", "value": 210}
],
"scales": [
{
"name": "x",
"type": "linear",
"domain": {"data": "facet", "field": "x"},
"range": [0, {"signal": "width"}],
"nice": true,
"zero": true
},
{
"name": "y",
"type": "linear",
"domain": {"data": "facet", "field": "y"},
"range": [{"signal": "height"}, 0],
"nice": true,
"zero": true
}
],
"marks": [
{
"name": "points",
"type": "symbol",
"style": ["point"],
"from": {"data": "facet"},
"encode": {
"update": {
"x": {"scale": "x", "field": "x"},
"y": {"scale": "y", "field": "y"},
"opacity": {"value": 0},
}
}
},
{
"type": "path",
"name": "cell",
"from": {"data": "points"},
"encode": {
"enter": {
"fill": {"value": "transparent"},
"strokeWidth": {"value": 0.35},
},
"update": {
"path": {"field": "path"},
"stroke": {"signal": "cell_stroke"}
}
},
"transform": [{
"type": "voronoi",
"x": {"expr": "datum.datum.x"},
"y": {"expr": "datum.datum.y"},
"size": [{"signal": "width"}, {"signal": "height"}]
}]
},
{
"type": "symbol",
"style": ["point"],
"from": {"data": "facet"},
"encode": {
"update": {
"x": {"scale": "x", "field": "x"},
"y": {"scale": "y", "field": "y"},
"opacity": {"signal": "datum.color === 'selected_word' || (!hover || (hover && hover.text === datum.text)) ? 0.7 : 0.2"},
"fill": {"scale": "color", "field": "color"},
"stroke": {"value": "transparent"},
"cursor": {"value": "pointer"},
"size": {"signal": "datum.color === 'selected_word' ? 100 : 60"}
}
}
},
{
"name": "labels",
"type": "text",
"from": {"data": "points"},
"encode": {
"update": {
"fill": {"scale": "color", "field": "datum.color"},
"text": {"field": "datum.text"},
"fontSize": {"value": 12},
"fillOpacity": {"signal": "datum.datum.color === 'selected_word' || (!hover || (hover && hover.text === datum.datum.text)) ? 1 : 0.2"},
"fontWeight": {"signal": "datum.datum.color === 'selected_word' || (hover && hover.text === datum.datum.text) ? 'bold' : 'normal'"},
"cursor": {"value": "pointer"},
}
},
"transform": [
{
"type": "label",
"offset": 2,
"size": [{"signal": "width"}, {"signal": "height"}],
"as": ["x", "y", "labelOpacity", "align", "baseline", "originalOpacity", "transformed"]
},
{
"type": "formula",
"as": "opacity",
"expr": "datum.datum.datum.color === 'selected_word' || (hover && hover.text === datum.datum.datum.text) ? 1 : datum.labelOpacity"
},
{
"type": "formula",
"as": "x",
"expr": "datum.datum.datum.color === 'selected_word' || (!datum.x && hover && hover.text === datum.datum.datum.text) ? scale('x', datum.datum.datum.x) + 5 : datum.x"
},
{
"type": "formula",
"as": "y",
"expr": "datum.datum.datum.color === 'selected_word' || (!datum.y && hover && hover.text === datum.datum.datum.text) ? scale('y', datum.datum.datum.y) + 5 : datum.y"
}
]
}
]
}
],
"scales": [
{
"name": "model",
"type": "band",
"domain": {"data": "data_0", "field": "model"},
"range": "width",
"padding": 0
},
{
"name": "color",
"type": "ordinal",
"domain": ["intersection", "difference", "selected_word"],
"range": CATEGORICAL_COLORS
}
]
};
<file_sep>const DATASET_TO_MODELS = {
sentanalysis: {
name: 'Transfer Learning for Sentiment Classification',
models: [
{
name: 'FastText Initial',
path: './data/sentanalysis/initial_fasttext_preprocessed.json',
},
{
name: 'LSTM Fine-tuned',
path: './data/sentanalysis/lstm_finetuned_preprocessed.json',
},
],
},
histwords: {
name: 'HistWords Diachronic Word Embeddings',
models: [
{
name: 'English 1800-1810',
path: './data/histwords/1800_preprocessed.json',
},
{
name: 'English 1850-1860',
path: './data/histwords/1850_preprocessed.json',
},
{
name: 'English 1900-1910',
path: './data/histwords/1900_preprocessed.json',
},
{
name: 'English 1950-1960',
path: './data/histwords/1950_preprocessed.json',
},
{
name: 'English 1990-2000',
path: './data/histwords/1990_preprocessed.json',
},
],
},
emojis: {
name: 'Emoji Representations',
models: [
{
name: 'emoji2vec',
path: './data/emojis/emoji_words_preprocessed.json',
},
{
name: 'Emoji Image Vectors',
path: './data/emojis/emoji_imgs_preprocessed.json',
},
],
},
glove_6b_vs_twitter: {
name: 'GloVe Pre-trained: Wikipedia/News vs. Twitter',
models: [
{
name: 'Wikipedia/News',
path: './data/glove_6b_vs_twitter/6B_preprocessed.json',
},
{
name: 'Twitter',
path: './data/glove_6b_vs_twitter/twitter_preprocessed.json',
},
],
},
};
const DISTANCE_METRICS = {
'cosine': 'Cosine',
'euclidean': 'Euclidean',
};
const SIMILARITY_METRICS = {
'jaccard': 'Jaccard Similarity',
};
const PROJECTION_METHODS = {
'embedding_pca': 'PCA',
'embedding_umap': 'UMAP',
'embedding_tsne': 't-SNE',
}
const DEFAULT_DATASET = 'sentanalysis';
const DEFAULT_DISTANCE_METRIC = 'cosine';
const DEFAULT_SIMILARITY_METRIC = 'jaccard';
const DEFAULT_PROJECTION_METHOD = 'embedding_pca';
const NUM_DOMINOES_PER_COLUMN = 20;
class DatasetSelector extends React.PureComponent {
constructor(props) {
super(props);
this.handleDatasetChange = this.handleDatasetChange.bind(this);
}
handleDatasetChange(e) {
this.props.onChange(e.target.value);
}
initialize() {
$('#dataset-select-dropdown').select2({
minimumResultsForSearch: -1,
});
document.getElementById('dataset-select-dropdown').onchange = this.handleDatasetChange;
}
componentDidMount() {
this.initialize();
}
componentDidUpdate(prevProps) {
this.initialize();
}
render() {
let datasetOptions = [];
for (const key in this.props.datasetToModels) {
datasetOptions.push(
<option value={key} key={key}>
{this.props.datasetToModels[key].name}
</option>);
}
return (
<div className='dataset-section selector'>
<div className='selection-title'>
<div className='selection-title-text'>Dataset</div>
<div className='tooltip-control' data-tooltip="Select a dataset. Then select individual models to compare in the Embedding Comparator.">
?
</div>
</div>
<select id='dataset-select-dropdown' value={this.props.selectedDataset} onChange={this.handleDatasetChange}>
{datasetOptions}
</select>
</div>
);
}
}
class ModelSelector extends React.PureComponent {
constructor(props) {
super(props);
this.handleModelChange = this.handleModelChange.bind(this);
}
handleModelChange(e) {
this.props.onChange(this.props.isModelA, e.target.value);
}
initialize() {
$('#' + this.props.id).select2({
minimumResultsForSearch: -1,
});
document.getElementById(this.props.id).onchange = this.handleModelChange;
}
componentDidMount() {
this.initialize();
}
componentDidUpdate(prevProps) {
this.initialize();
}
render() {
let modelOptions = [];
for (let i = 0; i < this.props.models.length; i++) {
const modelName = this.props.models[i].name;
modelOptions.push(
<option value={i} key={i}>
{modelName}
</option>);
}
return (
<div className='model-selection'>
<div className='selection-title'>
<div className='selection-title-text'>{this.props.title}</div>
</div>
<select id={this.props.id} value={this.props.selectedModelIdx} onChange={this.handleModelChange}>
{modelOptions}
</select>
</div>
);
}
}
class NumNeighborsSelector extends React.PureComponent {
constructor(props) {
super(props);
this.handleNumNeighborsSliderChange = this.handleNumNeighborsSliderChange.bind(this);
}
handleNumNeighborsSliderChange(numNearestNeighbors) {
this.props.onChange(numNearestNeighbors);
}
componentDidMount() {
createNearestNeighborsSlider(
this.props.numNearestNeighbors,
this.handleNumNeighborsSliderChange,
);
}
componentDidUpdate(prevProps) {
createNearestNeighborsSlider(
this.props.numNearestNeighbors,
this.handleNumNeighborsSliderChange,
);
}
render() {
return (
<div className='nearest-neighbor-selection'>
<div className='selection-title'>
<div className='selection-title-text'>
Nearest Neighbors
</div>
<div className='tooltip-control' data-tooltip="Number of neighbors to define the local neighborhood around each point. Similarity for each word is computed based on the similarity of the neighborhoods from each of the embedding models.">
?
</div>
</div>
<div className='num-neighbors-container'>
<div id='num-neighbors-slider'></div>
<div id='num-neighbors-value-continer'></div>
</div>
</div>
);
}
}
class DistanceMetricSelector extends React.PureComponent {
constructor(props) {
super(props);
this.handleDistanceMetricChange = this.handleDistanceMetricChange.bind(this)
}
handleDistanceMetricChange(e) {
this.props.onClick(e.target.value);
}
render() {
let buttons = [];
for (const key in this.props.options) {
var className = "btn btn-sm btn-outline-secondary";
if (key == this.props.distanceMetric) {
className += " active";
}
buttons.push(
<button
value={key}
key={key}
onClick={this.handleDistanceMetricChange}
className={className}>
{this.props.options[key]}
</button>);
}
return (
<div className='distance-metric-selector'>
<div className='selection-title'>
<div className='selection-title-text'>Distance Metric</div>
<div className='tooltip-control' data-tooltip="Distance metric for computing the nearest neighbors around each point.">
?
</div>
</div>
<div className="button-row">
{buttons}
</div>
</div>
);
}
}
class ProjectionMethodSelector extends React.PureComponent {
constructor(props) {
super(props);
this.handleProjectionMethodChange = this.handleProjectionMethodChange.bind(this)
}
handleProjectionMethodChange(e) {
this.props.onClick(e.target.value);
}
render() {
let buttons = [];
for (const key in this.props.options) {
var className = "btn btn-sm btn-outline-secondary";
if (key == this.props.projectionMethod) {
className += " active";
}
buttons.push(
<button
value={key}
key={key}
onClick={this.handleProjectionMethodChange}
className={className}>
{this.props.options[key]}
</button>);
}
return (
<div className='distance-metric-selector'>
<div className='selection-title'>
<div className='selection-title-text'>Projection Method</div>
<div className='tooltip-control' data-tooltip="Projection method used in global projection and local domino plots.">
?
</div>
</div>
<div className="button-row">
{buttons}
</div>
</div>
);
}
}
class SimilarityMetricSelector extends React.PureComponent {
constructor(props) {
super(props);
}
render() {
let buttons = [];
for (const key in this.props.options) {
var className = "btn btn-sm btn-outline-secondary";
if (key == this.props.similarityMetric) {
className += " active";
}
buttons.push(
<button value={key} key={key} className={className}>
{this.props.options[key]}
</button>);
}
return (
<div className='similarity-metric-selector selector'>
<div className='selection-title'>
<div className='selection-title-text'>
Similarity Metric
</div>
<div className='tooltip-control' data-tooltip="Similarity metric between the local neighboors around a given word. Jaccard is the intersection over union (IOU) similarity which measures the overlap between the two sets.">
?
</div>
</div>
<div className="button-row">
{buttons}
</div>
</div>
);
}
}
class SimilarityHistogram extends React.PureComponent {
constructor(props) {
super(props);
}
componentDidMount() {
createSimilarityHistogram(
this.props.values, this.props.onBrush, this.props.brushedWordIdxs);
}
componentDidUpdate(prevProps) {
createSimilarityHistogram(
this.props.values, this.props.onBrush, this.props.brushedWordIdxs);
}
render() {
return (
<div className='histogram'>
<div className='selection-title'>
<div className='selection-title-text'>
Similarity Distribution
</div>
</div>
<div className='similarity-histogram-container'></div>
</div>
);
}
}
class WordDropdown extends React.PureComponent {
constructor(props) {
super(props);
this.handleDropdownChange = this.handleDropdownChange.bind(this);
}
handleDropdownChange(e) {
const selectedWordIndexStr = e.target.value;
const selectedValues = $('#word-selection-dropdown').val();
var selectedWordIdxs = null;
if (selectedValues.length > 0) {
selectedWordIdxs = selectedValues.map(str => parseInt(str, 10));
}
this.props.onChange(selectedWordIdxs);
}
initialize() {
$('#word-selection-dropdown').select2({
width: '100%',
});
document.getElementById('word-selection-dropdown').onchange = this.handleDropdownChange;
}
clearSelectedWords() {
$('#word-selection-dropdown').val(null).trigger('change');
}
componentDidMount() {
this.initialize();
}
componentDidUpdate(prevProps) {
if (this.props.selectedWordIdx === null && prevProps.selectedWordIdx !== null) {
this.clearSelectedWords();
}
this.initialize();
}
render() {
let options = [];
for (let idx = 0; idx < this.props.datasetObjects.length; idx++) {
const obj = this.props.datasetObjects[idx];
options.push(
<option value={idx} key={idx}>
{obj.word}
</option>);
}
const currentDropdown = document.getElementById('word-selection-dropdown');
if (currentDropdown !== null) {
currentDropdown.onchange = null;
}
return (
<div className='word-selection'>
<div className='selection-title'>
<div className='selection-title-text'>
Search for a word
</div>
</div>
<select id='word-selection-dropdown' multiple='multiple'>
{options}
</select>
</div>
);
}
}
class Plot extends React.PureComponent {
constructor(props) {
super(props);
}
doPlot() {
if (this.props.datasetObjects.length == 0) {
return;
}
createScatterPlotPlotly(
this.props.className + '-plotly',
this.props.datasetObjects,
this.props.similarityValues,
this.props.selectedWordIdx,
this.props.distanceMetric,
this.props.numNearestNeighbors,
this.props.onSelection,
this.props.projectionMethod,
);
}
componentDidMount() {
this.doPlot();
}
componentDidUpdate(prevProps) {
if (prevProps.activeDominoWordIdx !== this.props.activeDominoWordIdx) {
updatedScatterPlotSelectedWords(
this.props.className + '-plotly',
this.props.datasetObjects,
this.props.similarityValues,
((this.props.activeDominoWordIdx !== null) ? [this.props.activeDominoWordIdx] : null),
this.props.distanceMetric,
this.props.numNearestNeighbors,
this.props.otherModelDatasetObjects,
);
}
else if (prevProps.selectedWordIdx !== this.props.selectedWordIdx) {
updatedScatterPlotSelectedWords(
this.props.className + '-plotly',
this.props.datasetObjects,
this.props.similarityValues,
this.props.selectedWordIdx,
this.props.distanceMetric,
this.props.numNearestNeighbors,
this.props.otherModelDatasetObjects,
);
}
else {
this.doPlot();
}
}
render() {
return (
<div className={this.props.className}>
<div id={this.props.className + '-plotly'}></div>
</div>
);
}
}
class Domino extends React.PureComponent {
constructor(props) {
super(props);
}
makeDomino() {
if (this.props.wordIdx === null || this.props.dataset1Objects.length == 0 || this.props.dataset2Objects.length == 0) {
return;
}
createDomino(
this.props.className,
this.props.dataset1Objects,
this.props.dataset2Objects,
this.props.wordIdx,
this.props.distanceMetric,
this.props.numNearestNeighbors,
this.props.similarityValues,
this.props.similarityValue,
this.props.projectionMethod,
);
}
makeClickable() {
const domino = d3.select('.' + this.props.className);
const wordIdx = this.props.wordIdx;
const onActiveDominoChange = this.props.onActiveDominoChange;
domino.style('cursor', 'pointer');
domino.on('mouseenter', function() {
onActiveDominoChange(wordIdx);
d3.select(this).classed('domino-active', true);
});
domino.on('mouseleave', function() {
onActiveDominoChange(null);
d3.select(this).classed('domino-active', false);
});
}
componentDidMount() {
this.observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
const {isIntersecting } = entry;
if (isIntersecting) {
this.makeDomino();
this.makeClickable();
this.observer = this.observer.disconnect();
}
});
},
{
root: document.querySelector(".dominoes-column-container"), // relative to viewport
});
this.observer.observe(this.element);
}
componentDidUpdate(prevProps) {
this.updateObserver = new IntersectionObserver(entries => {
entries.forEach(entry => {
const {isIntersecting } = entry;
if (isIntersecting) {
this.makeDomino();
this.makeClickable();
if (this.updateObserver) {
this.updateObserver = this.updateObserver.disconnect();
}
}
});
},
{
root: document.querySelector(".dominoes-column-container"), // relative to viewport
});
this.updateObserver.observe(this.element);
}
render() {
const roundedSimilarity = PERCENT_FORMAT(this.props.similarityValue);
return (
<div className={this.props.className + " domino"} id={this.props.className} tabIndex='-1' ref={el => this.element = el}>
<div className='domino-title'>
<div className='domino-word'>{this.props.word}</div>
<div className='domino-score'>{roundedSimilarity} similar</div>
</div>
<div id={this.props.className + '-words-intersection'} className='domino-words-intersection'></div>
<div id={this.props.className + '-plot'} className='domino-plots'>
</div>
<div id={this.props.className + '-not-intersection'} className='domino-not-intersection'>
<div id={this.props.className + '-words-a'} className='domino-words-a'></div>
<div id={this.props.className + '-words-b'} className='domino-words-b'></div>
</div>
</div>
);
}
}
class DominoesColumn extends React.PureComponent {
constructor(props) {
super(props);
}
render() {
let dominoes = [];
if (this.props.dataset1Objects.length != 0 && this.props.dataset2Objects.length != 0) {
// On page load, if datasetObjects not populated yet, no dominoes.
for (let idx of this.props.wordIdxs) {
dominoes.push(
<Domino
key={'domino-' + idx}
className={'domino-' + idx}
dataset1Objects={this.props.dataset1Objects}
dataset2Objects={this.props.dataset2Objects}
wordIdx={idx}
word={this.props.dataset1Objects[idx].word}
similarityValue={this.props.similarityValues[idx]}
distanceMetric={this.props.distanceMetric}
numNearestNeighbors={this.props.numNearestNeighbors}
similarityValues={this.props.similarityValues}
onActiveDominoChange={this.props.onActiveDominoChange}
projectionMethod={this.props.projectionMethod}
/>
);
}
}
const title = this.props.title.split(' ');
return (
<div>
<div className='domino-column-title'><span className='first-word'>{title[0]}</span> {title.slice(1).join(' ')}</div>
<div className={'domino-column'}>
{dominoes}
</div>
</div>
);
}
}
class ScrollWords extends React.PureComponent {
constructor(props) {
super(props);
}
makeScrollWords() {
if (this.props.words === []) { return; }
createScrollWords(
this.props.wordsIdxs,
this.props.datasetObjects,
this.props.similarityValues,
this.props.containerClass,
this.props.onHover,
);
}
componentDidMount() {
this.makeScrollWords();
}
componentDidUpdate(prevProps) {
this.makeScrollWords();
}
render() {
return (
<div className={this.props.containerClass}></div>
);
}
}
class DominoesContainer extends React.PureComponent {
constructor(props) {
super(props);
}
render() {
// Get word idxs for columns of DominoColumns.
var leastSimilarWordIdxs;
var mostSimilarWordIdxs;
var leastSimilarColumnTitle;
var mostSimilarColumnTitle;
if (this.props.brushedWordIdxs !== null || this.props.globalPlotSelectedWordIdxs !== null) {
const selectedIdxs = ((this.props.brushedWordIdxs !== null) ? this.props.brushedWordIdxs : this.props.globalPlotSelectedWordIdxs);
const sortedIdxBySimilarity = sortIdxsBySimilarityValues(
this.props.similarityValues);
const filteredSortedIdxBySimilarity = [];
for (let idx of sortedIdxBySimilarity) {
if (selectedIdxs.includes(idx)) {
filteredSortedIdxBySimilarity.push(idx);
}
}
const numFirstColumn = Math.min(
Math.ceil(selectedIdxs.length / 2),
this.props.numDominoesPerColumn,
);
const numSecondColumn = Math.min(
filteredSortedIdxBySimilarity.length - numFirstColumn,
this.props.numDominoesPerColumn,
);
leastSimilarWordIdxs = filteredSortedIdxBySimilarity.slice(0, numFirstColumn);
mostSimilarWordIdxs = filteredSortedIdxBySimilarity.reverse().slice(0, numSecondColumn);
leastSimilarColumnTitle = 'Least Similar Filtered Objects';
mostSimilarColumnTitle = 'Most Similar Filtered Objects';
}
else if (this.props.selectedWordIdx !== null) {
const numFirstColumn = Math.ceil(this.props.selectedWordIdx.length / 2);
leastSimilarWordIdxs = this.props.selectedWordIdx.slice(0, numFirstColumn);
mostSimilarWordIdxs = this.props.selectedWordIdx.slice(numFirstColumn);
leastSimilarColumnTitle = 'Selected Objects';
mostSimilarColumnTitle = 'Selected Objects';
}
else {
const sortedIdxBySimilarity = sortIdxsBySimilarityValues(
this.props.similarityValues);
leastSimilarWordIdxs = sortedIdxBySimilarity.slice(
0, this.props.numDominoesPerColumn);
mostSimilarWordIdxs = sortedIdxBySimilarity.reverse().slice(
0, this.props.numDominoesPerColumn);
leastSimilarColumnTitle = 'Least Similar Objects';
mostSimilarColumnTitle = 'Most Similar Objects';
}
return (
<div className='dominoes-column-container' id='dominoes-column-container'>
<div className='dominoes-column-left'>
<DominoesColumn
wordIdxs={leastSimilarWordIdxs}
dataset1Objects={this.props.dataset1Objects}
dataset2Objects={this.props.dataset2Objects}
distanceMetric={this.props.distanceMetric}
numNearestNeighbors={this.props.numNearestNeighbors}
similarityValues={this.props.similarityValues}
title={leastSimilarColumnTitle}
onActiveDominoChange={this.props.onActiveDominoChange}
projectionMethod={this.props.projectionMethod}
/>
<ScrollWords
wordsIdxs={leastSimilarWordIdxs}
datasetObjects={this.props.dataset1Objects}
similarityValues={this.props.similarityValues}
containerClass={'scroll-words-left'}
onHover={this.props.onActiveDominoChange}
/>
</div>
<div className='dominoes-column-right'>
<DominoesColumn
wordIdxs={mostSimilarWordIdxs}
dataset1Objects={this.props.dataset1Objects}
dataset2Objects={this.props.dataset2Objects}
distanceMetric={this.props.distanceMetric}
numNearestNeighbors={this.props.numNearestNeighbors}
similarityValues={this.props.similarityValues}
title={mostSimilarColumnTitle}
onActiveDominoChange={this.props.onActiveDominoChange}
projectionMethod={this.props.projectionMethod}
/>
<ScrollWords
wordsIdxs={mostSimilarWordIdxs}
datasetObjects={this.props.dataset1Objects}
similarityValues={this.props.similarityValues}
containerClass={'scroll-words-right'}
onHover={this.props.onActiveDominoChange}
/>
</div>
</div>
);
}
}
class NearestNeighborTable extends React.PureComponent {
constructor(props) {
super(props);
this.handleWordClick = this.handleWordClick.bind(this);
}
handleWordClick(selectedWordIdx) {
this.props.onClick(selectedWordIdx);
}
createTable() {
createNeighborsTable(
this.props.className,
this.props.datasetObjects,
this.props.distanceMetric,
this.props.selectedWordIdx,
this.handleWordClick,
);
}
componentDidMount() {
this.createTable();
}
componentDidUpdate(prevProps) {
this.createTable();
}
render() {
return (
<div className={this.props.className}></div>
);
}
}
class EmbeddingComparator extends React.Component {
constructor(props) {
super(props);
this.state = {
dataset: DEFAULT_DATASET,
modelAIdx: 0,
modelBIdx: 1,
numNearestNeighbors: DEFAULT_NUM_NEIGHBORS,
distanceMetric: DEFAULT_DISTANCE_METRIC,
similarityMetric: DEFAULT_SIMILARITY_METRIC,
projectionMethod: DEFAULT_PROJECTION_METHOD,
selectedWordIdx: null,
brushedWordIdxs: null,
globalPlotSelectedWordIdxs: null,
activeDominoWordIdx: null,
dataset1Objects: [],
dataset2Objects: [],
similarityValues: [],
};
this.loadDataset = this.loadDataset.bind(this);
this.handleDatasetSelectorChange = this.handleDatasetSelectorChange.bind(this);
this.handleModelChange = this.handleModelChange.bind(this);
this.handleDistanceMetricChange = this.handleDistanceMetricChange.bind(this);
this.handleProjectionMethodChange = this.handleProjectionMethodChange.bind(this);
this.handleNumNeighborsSliderChange = this.handleNumNeighborsSliderChange.bind(this);
this.handleDropdownChange = this.handleDropdownChange.bind(this);
this.handleBrushSelectionChange = this.handleBrushSelectionChange.bind(this);
this.handleGlobalPlotSelectionChange = this.handleGlobalPlotSelectionChange.bind(this);
this.handleActiveDominoChange = this.handleActiveDominoChange.bind(this);
}
componentDidMount() {
this.loadDataset();
}
async loadDataset() {
const [dataset1Objects, dataset2Objects] = await Promise.all([
d3.json(this.props.datasetToModels[this.state.dataset].models[this.state.modelAIdx].path),
d3.json(this.props.datasetToModels[this.state.dataset].models[this.state.modelBIdx].path),
]);
check_dataset_orders_equal(dataset1Objects, dataset2Objects)
const newSimilarityValues = compute_iou_similarities(
dataset1Objects,
dataset2Objects,
this.state.numNearestNeighbors,
this.state.distanceMetric,
);
this.setState({
dataset1Objects: dataset1Objects,
dataset2Objects: dataset2Objects,
similarityValues: newSimilarityValues,
});
}
handleDatasetSelectorChange(dataset) {
this.setState({
dataset: dataset,
modelAIdx: 0,
modelBIdx: 1,
selectedWordIdx: null,
brushedWordIdxs: null,
activeDominoWordIdx: null,
globalPlotSelectedWordIdxs: null,
});
this.loadDataset();
}
handleModelChange(isModelA, modelIdx) {
if (isModelA === null) {
return;
}
if (isModelA) {
this.setState({
modelAIdx: modelIdx,
selectedWordIdx: null,
brushedWordIdxs: null,
globalPlotSelectedWordIdxs: null,
activeDominoWordIdx: null,
});
}
else {
this.setState({
modelBIdx: modelIdx,
selectedWordIdx: null,
brushedWordIdxs: null,
globalPlotSelectedWordIdxs: null,
activeDominoWordIdx: null,
});
}
this.loadDataset();
}
handleDistanceMetricChange(distanceMetric) {
const newSimilarityValues = compute_iou_similarities(
this.state.dataset1Objects,
this.state.dataset2Objects,
this.state.numNearestNeighbors,
distanceMetric,
);
this.setState({
distanceMetric: distanceMetric,
similarityValues: newSimilarityValues,
brushedWordIdxs: null,
});
}
handleProjectionMethodChange(projectionMethod) {
this.setState({
projectionMethod: projectionMethod,
});
}
handleNumNeighborsSliderChange(numNearestNeighbors) {
const clippedNumNearestNeighbors = Math.max(numNearestNeighbors, 1);
const newSimilarityValues = compute_iou_similarities(
this.state.dataset1Objects,
this.state.dataset2Objects,
clippedNumNearestNeighbors,
this.state.distanceMetric,
);
this.setState({
numNearestNeighbors: clippedNumNearestNeighbors,
similarityValues: newSimilarityValues,
brushedWordIdxs: null,
});
}
handleDropdownChange(selectedWordIdx) {
this.setState({
selectedWordIdx: selectedWordIdx,
brushedWordIdxs: null,
globalPlotSelectedWordIdxs: null,
});
}
handleBrushSelectionChange(selectedIdxs) {
this.setState({
brushedWordIdxs: selectedIdxs,
selectedWordIdx: null,
globalPlotSelectedWordIdxs: null,
});
}
handleGlobalPlotSelectionChange(selectedIdxs) {
this.setState({
globalPlotSelectedWordIdxs: selectedIdxs,
brushedWordIdxs: null,
selectedWordIdx: null,
});
}
handleActiveDominoChange(activeDominoWordIdx) {
this.setState({
activeDominoWordIdx: activeDominoWordIdx,
});
}
render() {
return (
<div id='embedding-comparator-content'>
<div className='control-panel'>
<div className='parameter-controls'>
<DatasetSelector
selectedDataset={this.state.dataset}
datasetToModels={this.props.datasetToModels}
modelAIdx={this.props.modelAIdx}
modelBIdx={this.props.modelBIdx}
onChange={this.handleDatasetSelectorChange}
/>
<div className='model-selectors-container'>
<div id='model-a-props' className='model-props'>
<ModelSelector
id='model-a-select-dropdown'
title='Model A'
models={this.props.datasetToModels[this.state.dataset].models}
selectedModelIdx={this.state.modelAIdx}
isModelA={true}
onChange={this.handleModelChange}
/>
<Plot
className={'projector-plot-a-container'}
title={'Projector Plot A'}
datasetObjects={this.state.dataset1Objects}
otherModelDatasetObjects={this.state.dataset2Objects}
selectedWordIdx={this.state.selectedWordIdx}
activeDominoWordIdx={this.state.activeDominoWordIdx}
distanceMetric={this.state.distanceMetric}
projectionMethod={this.state.projectionMethod}
similarityValues={this.state.similarityValues}
numNearestNeighbors={this.state.numNearestNeighbors}
onSelection={this.handleGlobalPlotSelectionChange}
/>
</div>
<div id='model-b-props' className='model-props'>
<ModelSelector
id='model-b-select-dropdown'
title='Model B'
models={this.props.datasetToModels[this.state.dataset].models}
selectedModelIdx={this.state.modelBIdx}
isModelA={false}
onChange={this.handleModelChange}
/>
<Plot
className={'projector-plot-b-container'}
title={'Projector Plot B'}
datasetObjects={this.state.dataset2Objects}
otherModelDatasetObjects={this.state.dataset1Objects}
selectedWordIdx={this.state.selectedWordIdx}
activeDominoWordIdx={this.state.activeDominoWordIdx}
distanceMetric={this.state.distanceMetric}
projectionMethod={this.state.projectionMethod}
similarityValues={this.state.similarityValues}
numNearestNeighbors={this.state.numNearestNeighbors}
onSelection={this.handleGlobalPlotSelectionChange}
/>
</div>
</div>
<div className='similarity'>
<div className='metrics'>
<NumNeighborsSelector
numNearestNeighbors={this.state.numNearestNeighbors}
onChange={this.handleNumNeighborsSliderChange}
/>
<DistanceMetricSelector
options={this.props.distanceMetricOptions}
distanceMetric={this.state.distanceMetric}
onClick={this.handleDistanceMetricChange}
/>
<ProjectionMethodSelector
options={this.props.projectionMethodOptions}
projectionMethod={this.state.projectionMethod}
onClick={this.handleProjectionMethodChange}
/>
</div>
<SimilarityHistogram
values={this.state.similarityValues}
onBrush={this.handleBrushSelectionChange}
brushedWordIdxs={this.state.brushedWordIdxs}
/>
{/* <SimilarityMetricSelector
options={this.props.similarityMetricOptions}
similarityMetric={this.state.similarityMetric}
/> */}
</div>
<div className='word-selection-container'>
<WordDropdown
dataset={this.state.dataset}
datasetObjects={this.state.dataset1Objects}
onChange={this.handleDropdownChange}
selectedWordIdx={this.state.selectedWordIdx}
/>
</div>
</div>
</div>
<div className='main-panel'>
<div className='dominoes-container'>
<DominoesContainer
dataset1Objects={this.state.dataset1Objects}
dataset2Objects={this.state.dataset2Objects}
distanceMetric={this.state.distanceMetric}
projectionMethod={this.state.projectionMethod}
numNearestNeighbors={this.state.numNearestNeighbors}
similarityValues={this.state.similarityValues}
selectedWordIdx={this.state.selectedWordIdx}
brushedWordIdxs={this.state.brushedWordIdxs}
globalPlotSelectedWordIdxs={this.state.globalPlotSelectedWordIdxs}
numDominoesPerColumn={NUM_DOMINOES_PER_COLUMN}
onActiveDominoChange={this.handleActiveDominoChange}
/>
</div>
</div>
</div>
);
}
}
ReactDOM.render(
<EmbeddingComparator
datasetToModels={DATASET_TO_MODELS}
distanceMetricOptions={DISTANCE_METRICS}
similarityMetricOptions={SIMILARITY_METRICS}
projectionMethodOptions={PROJECTION_METHODS}
/>,
document.getElementById('embedding_comparator_root'),
);
| f0d9fc43e33c161eee4e3035acc9e8621ed13507 | [
"JavaScript",
"Python",
"Markdown"
] | 6 | JavaScript | mitvis/embedding-comparator | 5edc5bea187ca59271f99503c3b16cba63528caa | c6ec8de91c565ce8f267e451474322d53f4f1e57 |
refs/heads/master | <repo_name>waelabed/lec12-wepapi<file_sep>/Consume-wepApi-consule/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Consume_wepApi_consule
{
class Program
{
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task<List<Product>> RunAsync()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:7899");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
List<Product> products = null;
HttpResponseMessage response = await client.GetAsync("api/products");
if (response.IsSuccessStatusCode)
{
products = await response.Content.ReadAsAsync<List<Product>>();
}
foreach (var item in products)
{
Console.WriteLine("{0} {1}", item.Name, item.Price);
}
Console.ReadKey();
return products;
}
}
}
| 76d810a74c41bc9e94cefbf474c45304c5de043a | [
"C#"
] | 1 | C# | waelabed/lec12-wepapi | 90c31878fce4ee5c07677fd7fb68e3b0288b1bbc | 1a3e499e18a722e640c27e3318f43a32ab2981a1 |
refs/heads/master | <file_sep>use_frameworks!
target 'iOS_imageSDK_Example' do
pod 'iOS_imageSDK', :path => '../'
target 'iOS_imageSDK_Tests' do
inherit! :search_paths
end
end
| 8605597d36634f3df7e9a9b1de123da6c0cb32c8 | [
"Ruby"
] | 1 | Ruby | JaydeepPatoliya/iOS_imageSDK | 7968476a3b274c62e46dd254ac5d3c97c204b9d1 | bee5c49bb1bef3f093d05d13b63637c5a80b52f1 |
refs/heads/master | <file_sep>package com.wyz.myimagegallery.Util;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;
import com.wyz.myimagegallery.Banco.BancoController;
import com.wyz.myimagegallery.Banco.GalleryDAO;
import com.wyz.myimagegallery.classes.Gallery;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
public class Util {
private static InputStream toInputStream(Bitmap bitmap){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
return bs;
}
public static String ImagetoBase64(Bitmap bitmap){
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
InputStream is= toInputStream(bitmap);
try{
while((bytesRead = is.read(buffer)) != -1){
output.write(buffer,0,bytesRead);
}
}catch (IOException e){
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedString = Base64.encodeToString(bytes,Base64.DEFAULT);
return encodedString;
}
public static Bitmap Base64toImage(String imgstr){
byte[] decodedString = Base64.decode(imgstr,Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(decodedString,0,decodedString.length);
return decodedImage;
}
public static String webToString(InputStream inputStream) {
InputStream localStream = inputStream;
String localString = "";
Writer writer = new StringWriter();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(localStream, "UTF-8"));
String line = reader.readLine();
while (line != null) {
writer.write(line);
line = reader.readLine();
}
localString = writer.toString();
writer.close();
reader.close();
localStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return localString;
}
}
<file_sep>package com.wyz.myimagegallery.classes;
import android.graphics.Bitmap;
/**
* Created by W€µÐr€Y™ on 04/06/2017.
*/
public class Gallery {
private int ID;
private String titulo;
private String detalhes;
private String imagem;
public Gallery() {
}
public Gallery(String titulo, String detalhes) {
this.titulo = titulo;
this.detalhes = detalhes;
}
public Gallery(String titulo, String detalhes, String imagem) {
this.titulo = titulo;
this.detalhes = detalhes;
this.imagem = imagem;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getDetalhes() {
return detalhes;
}
public void setDetalhes(String detalhes) {
this.detalhes = detalhes;
}
public String getImagem() {
return imagem;
}
public void setImagem(String imagem) {
this.imagem = imagem;
}
@Override
public String toString() {
return "GALERIA:\n" +
"TITULO=" + titulo + "\n" +
"DETALHES=" + detalhes + "\n" +
"IMAGEM=" + imagem + "\n";
}
}
<file_sep>package com.wyz.myimagegallery.Activitys;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.wyz.myimagegallery.Banco.BancoController;
import com.wyz.myimagegallery.Banco.GalleryDAO;
import com.wyz.myimagegallery.classes.Gallery;
import com.wyz.myimagegallery.R;
import com.wyz.myimagegallery.Util.Util;
import java.io.IOException;
public class AlterarActivity extends Activity {
EditText titulo;
EditText detalhes;
Button alterar;
Button deletar;
Cursor cursor;
BancoController crud;
String codigo;
ImageView alteraImagem;
final int ACTIVITY_SELECT_IMAGE = 1234;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alterar);
codigo = this.getIntent().getStringExtra("codigo");
crud = new BancoController(getBaseContext());
titulo = (EditText)findViewById(R.id.alteraTitulo);
detalhes = (EditText)findViewById(R.id.alteraDetalhe);
alteraImagem = (ImageView)findViewById(R.id.alteraImagem);
alterar = (Button)findViewById(R.id.alterar);
cursor = crud.carregaDadoById(Integer.parseInt(codigo));
titulo.setText(cursor.getString(cursor.getColumnIndexOrThrow(GalleryDAO.TITULO)));
detalhes.setText(cursor.getString(cursor.getColumnIndexOrThrow(GalleryDAO.DETALHES)));
alteraImagem.setImageBitmap(Util.Base64toImage(cursor.getString(cursor.getColumnIndexOrThrow(GalleryDAO.IMAGEM))));
alteraImagem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Selecione a Imagem"),ACTIVITY_SELECT_IMAGE);
}
});
alterar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Gallery gallery = new Gallery();
gallery.setID(Integer.parseInt(codigo));
gallery.setTitulo(titulo.getText().toString());
gallery.setDetalhes(detalhes.getText().toString());
gallery.setImagem(Util.ImagetoBase64 (((BitmapDrawable)alteraImagem.getDrawable()).getBitmap()));
crud.alteraRegistro(gallery);
Intent intent = new Intent(AlterarActivity.this,ConsultaActivity.class);
startActivity(intent);
finish();
}
});
deletar = (Button)findViewById(R.id.deletar);
deletar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crud.deletaRegistro(Integer.parseInt(codigo));
Intent intent = new Intent(AlterarActivity.this,ConsultaActivity.class);
startActivity(intent);
finish();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode == ACTIVITY_SELECT_IMAGE){
if(resultCode == Activity.RESULT_OK){
if(data != null){
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(),data.getData());
alteraImagem.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}else if(resultCode == Activity.RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Cancelado.", Toast.LENGTH_SHORT).show();
}
}
}
}
}
<file_sep>package com.wyz.myimagegallery.Activitys;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.facebook.FacebookSdk;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.wyz.myimagegallery.R;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MainActivity extends Activity {
private CallbackManager callbackManager;
private LoginButton loginButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
Button Inserir = (Button) findViewById(R.id.Inserir);
Inserir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, InsereActivity.class);
startActivity(intent);
}
});
Button consultar = (Button) findViewById(R.id.consultar);
consultar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, ConsultaActivity.class);
startActivity(intent);
}
});
Button json = (Button) findViewById(R.id.json);
json.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Json.class);
startActivity(intent);
}
});
loginButton = (LoginButton) findViewById(R.id.login_button);
callbackManager = CallbackManager.Factory.create();
try {
PackageInfo info = getPackageManager().getPackageInfo(
getPackageName(),
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
}
catch (PackageManager.NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.i("ID_FB",loginResult.getAccessToken().getUserId());
redirect(loginResult.getAccessToken().getUserId());
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException e) {
}
});
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if(accessToken != null){
redirect(accessToken.getUserId());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private void redirect(String ID){
Intent intent = new Intent(MainActivity.this,ConsultaActivity.class);
intent.putExtra("FB_ID",ID);
startActivity(intent);
}
}<file_sep>package com.wyz.myimagegallery.Activitys;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.wyz.myimagegallery.Banco.BancoController;
import com.wyz.myimagegallery.classes.Gallery;
import com.wyz.myimagegallery.R;
import com.wyz.myimagegallery.Util.Util;
import java.io.IOException;
public class InsereActivity extends Activity {
final int ACTIVITY_SELECT_IMAGE = 1234;
ImageView imageView;
String base64Image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insere);
base64Image = null;
imageView = (ImageView)findViewById(R.id.ImagemInsere);
Button botao = (Button)findViewById(R.id.envia);
Button pega_imagem_botao = (Button)findViewById(R.id.pega_imagem);
pega_imagem_botao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Selecione a Imagem"),ACTIVITY_SELECT_IMAGE);
}
});
botao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BancoController crud = new BancoController(getBaseContext());
EditText titulo = (EditText)findViewById(R.id.InsereTitulo);
EditText detalhes = (EditText)findViewById((R.id.InsereDetalhes));
String tituloString = titulo.getText().toString();
String detalhesString = detalhes.getText().toString();
String imagemString = Util.ImagetoBase64 (((BitmapDrawable)imageView.getDrawable()).getBitmap());
String resultado;
Gallery gallery = new Gallery(tituloString, detalhesString);
gallery.setImagem(imagemString);
resultado = crud.insereDado(gallery);
Toast.makeText(getApplicationContext(), resultado, Toast.LENGTH_LONG).show();
Intent intent = new Intent(InsereActivity.this,ConsultaActivity.class);
startActivity(intent);
finish();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode == ACTIVITY_SELECT_IMAGE){
if(resultCode == Activity.RESULT_OK){
if(data != null){
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(),data.getData());
imageView.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}else if(resultCode == Activity.RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Cancelado.", Toast.LENGTH_SHORT).show();
}
}
}
}
}
| 132cf7dfdd92193d3640b1d5db05ea5ef2075ba3 | [
"Java"
] | 5 | Java | Weudrey/Gallery | 9d1fe8caf6db661ffb3b2253fe3e724ae82e4b6c | 47f27f9a31e0813baa1cbf7128b9cb1a1d6d0175 |
refs/heads/master | <repo_name>nareshkumar-h/charity-requestor-ms<file_sep>/src/test/java/com/revature/charityapprequestorms/service/MailServiceTest.java
package com.revature.charityapprequestorms.service;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.revature.charityapprequestorms.dto.MailDto;
@SpringBootTest
class MailServiceTest {
@Autowired
MailService mailService;
@Autowired
UserService userService;
@Test
void sendMailTest() {
MailDto mailDTO = new MailDto();
mailDTO.setName("keyne");
mailDTO.setEmailId("<EMAIL>");
mailDTO.setTitle("Food");
mailDTO.setDescription("Fund for poor children's survival");
mailDTO.setAmount(10000);
mailDTO.setCategoryName("food");
mailService.sendMail(mailDTO);
assert(true);
}
}
<file_sep>/src/test/java/com/revature/charityapprequestorms/service/FundRequestServiceTest.java
package com.revature.charityapprequestorms.service;
import static org.junit.jupiter.api.Assertions.*;
import java.time.LocalDateTime;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.revature.charityapprequestorms.dto.FundRequestDto;
import com.revature.charityapprequestorms.exception.ServiceException;
import com.revature.charityapprequestorms.model.RequestorTransaction;
@SpringBootTest
class FundRequestServiceTest {
@Autowired
FundRequestService fundRequestService;
@Autowired
UserService userService;
@Autowired
CategoryService categoryService;
@Autowired
MailService mailService;
@Test
void addFundRequestTest() throws ServiceException {
FundRequestDto fundRequestDTO = new FundRequestDto();
fundRequestDTO.setCategoryId(1);
fundRequestDTO.setRequestedBy(1);
fundRequestDTO.setFundNeeded(1000);
fundRequestDTO.setDescription("Food for children");
fundRequestDTO.setTitle("Food");
fundRequestDTO.setActive(true);
fundRequestDTO.setCreatedDate(LocalDateTime.now());
fundRequestDTO.setModifiedDate(LocalDateTime.now());
fundRequestService.addFundRequest(fundRequestDTO);
assertNotNull(fundRequestDTO);
RequestorTransaction requestorTransaction = new RequestorTransaction();
requestorTransaction.setStatus("Verified");
requestorTransaction.setActive(true);
requestorTransaction.setCreatedDate(LocalDateTime.now());
requestorTransaction.setModifiedDate(LocalDateTime.now());
requestorTransaction.setCategoryId(1);
requestorTransaction.setFundNeeded(1000);
requestorTransaction.setRequestedBy(1);
}
@Test
void findAllTest() throws ServiceException {
List<FundRequestDto> fundRequestObj = null;
fundRequestObj = fundRequestService.findAll();
assertNotNull(fundRequestObj);
}
@Test
void findAllRequestTest() throws ServiceException {
List<RequestorTransaction> fundRequestObj = null;
fundRequestObj = fundRequestService.findAllRequest();
assertNotNull(fundRequestObj);
}
@Test
void findByIdTest() throws ServiceException{
FundRequestDto fundRequestObj=null;
fundRequestObj=fundRequestService.findById(1);
assertNotNull(fundRequestObj);
}
}
<file_sep>/src/test/java/com/revature/charityapprequestorms/service/CategoryServiceTest.java
package com.revature.charityapprequestorms.service;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class CategoryServiceTest {
@Test
void getFundTest() {
}
}
| 073f26c3579ced8f9edae24c11441b481722e173 | [
"Java"
] | 3 | Java | nareshkumar-h/charity-requestor-ms | bced5e5a7c381aec2971dfaa66764319e72b85ef | b23306f8ed07daec11fb9e0d6bc8846318d6af82 |
refs/heads/master | <repo_name>zihuxinyu/kmg<file_sep>/kmgLog/logger.go
package kmgLog
import "fmt"
import (
"github.com/bronze1man/kmg/console/kmgContext"
"github.com/bronze1man/kmg/encoding/kmgJson"
"github.com/bronze1man/kmg/kmgFile"
"path/filepath"
"runtime/debug"
"time"
)
type Logger struct {
}
type Priority int
const (
LOG_ALERT Priority = iota
LOG_CRITICAL
LOG_ERROR
LOG_WARNING
LOG_INFO
LOG_DEBUG
)
func (obj *Logger) Log(level Priority, message string) {
fmt.Println(message)
}
func (obj *Logger) Debug(message string) {
obj.Log(LOG_DEBUG, message)
}
func (obj *Logger) Info(message string) {
obj.Log(LOG_INFO, message)
}
func (obj *Logger) Waring(message string) {
obj.Log(LOG_WARNING, message)
}
func (obj *Logger) Error(message string) {
obj.Log(LOG_ERROR, message)
}
func (obj *Logger) Critical(message string) {
obj.Log(LOG_CRITICAL, message)
}
func (obj *Logger) Alert(message string) {
obj.Log(LOG_ALERT, message)
}
func (obj *Logger) LogError(err error) {
debug.PrintStack()
obj.Error(err.Error())
}
func (obj *Logger) VarDump(v interface{}) {
message := fmt.Sprintf("%#v", v)
obj.Log(LOG_DEBUG, message)
}
func init() {
if kmgContext.Default != nil {
kmgFile.Mkdir(kmgContext.Default.LogPath)
}
}
type logRow struct {
Time string
Msg string
Obj interface{}
}
func Log(category string, msg string, obj interface{}) {
logPath := kmgContext.Default.LogPath
toWrite := append(kmgJson.MustMarshal(logRow{
Time: time.Now().Format(time.RFC3339),
Msg: msg,
Obj: obj,
}), byte('\n'))
err := kmgFile.AppendFile(filepath.Join(logPath, category+".log"), toWrite)
if err != nil {
panic(err)
}
return
}
<file_sep>/encoding/kmgBase64/kmgBase64.go
package kmgBase64
import "encoding/base64"
func MustStdBase64DecodeString(s string) (out []byte) {
out, err := base64.StdEncoding.DecodeString(s)
if err != nil {
panic(err)
}
return
}
| e5f1068d96ec86536068e08fd93cb721135db93e | [
"Go"
] | 2 | Go | zihuxinyu/kmg | cb084baeacefb763e1884eda65ad645efe06c740 | e0067ba57d248f53476d5b752627395f9d847e0d |
refs/heads/master | <repo_name>Reynaldi1912/03_praktikum_web_lanjut_satu<file_sep>/database/seeders/AboutSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class AboutSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$about=[
[
'nama' => '<NAME>',
'kelas' => 'TI2D',
'absen' => '22',
'description' => 'Saya Berkuliah di Politeknik Negeri Malang angkatan 2019 , Jurusan Informatika
saya disini berasal dari lumajang , sebelumnya tidak punya basic didalam dunia IT'
],
[
'nama' => '<NAME>',
'kelas' => 'TI2D',
'absen' => '13',
'description' => 'Saya Berkuliah di Politeknik Negeri Malang angkatan 2019 , Jurusan Informatika
saya disini berasal dari probolinggo , sebelumnya basic saya adalah jaringan'
]
];
DB::table('abouts')->insert($about);
}
}
<file_sep>/database/seeders/PostSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$posts=[
[
'nama' => 'MMarble Edu Games',
'kelas' => 'https://www.educastudio.com/category/marbel-edu-games',
'picture' => 'images/project/project-image01.jpg'
],
[
'nama' => 'Marble and friends kids Games',
'kelas' => 'https://www.educastudio.com/category/marbel-and-friends-kids-games',
'picture' => 'images/project/project-image02.jpg'
],
[
'nama' => 'Riri Story Books',
'link' => 'https://www.educastudio.com/category/riri-story-books',
'picture' => 'images/project/project-image03.jpg'
],
[
'nama' => 'Riri Story Books',
'link' => 'https://www.educastudio.com/category/riri-story-books',
'picture' =>'images/project/project-image04.jpg'
]
];
DB::table('posts')->insert($posts);
}
}
<file_sep>/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\PostController;
use App\Http\Controllers\AboutController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Route::get('/', function () {
// return view('welcome');
// });
// Auth::routes();
// Route::get('/home', [App\Http\Controllers\HomeController::class, 'home'])->name('home');
Route::get('/', [HomeController::class, 'home']);
// Route::prefix('/category')->group(function(){
// Route::get('product', [HomeController::class, 'product'])->name('product');
// Route::get('program', [HomeController::class, 'program'])->name('program');
// });
Route::get('product', [PostController::class, 'index'])->name('index');
Route::get('program', [HomeController::class, 'program'])->name('program');
Route::get('/news', [HomeController::class, 'news']);
Route::get('/about', [AboutController::class, 'index']);
Route::get('/contact', [HomeController::class, 'contact']);
Route::get('/', [HomeController::class, 'index']);
<file_sep>/app/Http/Controllers/AboutController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\About;
class AboutController extends Controller
{
public function index(){
$data_about = About::where('id',1)->first();
return view('about', compact('data_about'));
}
}
<file_sep>/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
// public function __construct()
// {
// $this->middleware('auth');
// }
// public function home(){
// return view('Home');
// }
public function news(){
return view('news');
}
// public function product(){
// return view('category.product');
// }
// public function program(){
// return view('category.program');
// }
public function contact(){
return view('contactt');
}
public function about(){
return view('about');
}
public function index(){
return view('index');
}
public function product(){
return view('product');
}
public function program(){
return view('program');
}
}
<file_sep>/app/Http/Controllers/PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
public function index(){
$data_post = Post::all();
return view('product', compact('data_post'));
}
}
| 644928a7127757c77e79cd13ea3b11cdaf0501a9 | [
"PHP"
] | 6 | PHP | Reynaldi1912/03_praktikum_web_lanjut_satu | 14c15581572287d7c33022d2dbe9580cf422fa2b | 2a5ab96f80104b8d659e25b0eb34599f645ee057 |
refs/heads/master | <file_sep>console.log("script loaded")
window.addEventListener( 'load', function() {
let sendButton1 = document.getElementById('send1')
let sendButton2 = document.getElementById('send2')
let attachButton = document.getElementById('attach-button');
let textArea = document.getElementById('textArea')
console.log("window loaded");
textArea.addEventListener('change', function () {
console.dir(textArea);
})
attachButton.addEventListener('click', function() {
console.dir(attachButton);
});
sendButton1.addEventListener('click', function() {
if ((textArea.value.includes("attach") || textArea.value.includes("Attach")) && attachButton.files.length == 0) {
attachButton.style.border = "1px solid red";
confirm("Looks like you said you're attaching something but didn't actually attach it. Don't be that guy. Send anyway? (you will be reviled for this)");
}});
sendButton2.addEventListener('click', function() {
if ((textArea.value.includes("attach") || textArea.value.includes("Attach")) && attachButton.files.length == 0) {
attachButton.style.border = "1px solid red";
confirm("Looks like you said you're attaching something but didn't actually attach it. Don't be that guy. Send anyway? (you will be reviled for this)");
}});
});
| d65fcac2924956cddcba8e119f48d6be5faa4968 | [
"JavaScript"
] | 1 | JavaScript | AnansiRafa/attachment-checker | 77f7c5332ebe0d539f0614d8948df3afa119ff23 | 5c7259fbbc939343614e4a2207d0d30db3eccaa2 |
refs/heads/master | <repo_name>suryaabednego/tugasweb<file_sep>/tugasWEB.PHP
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/0e4b71198dc78edf/geolookup/conditions/q/IA/mugassari.json");
$json_string2 = file_get_contents("http://api.wunderground.com/api/a657d7d2ba430b38/astronomy/q/IA/mugassari.json");
$json_string3 = file_get_contents ("http://api.wunderground.com/api/a657d7d2ba430b38/planner_07010731/q/IA/mugassari.json");
$parsed_json = json_decode ($json_string);
$parsed_json2 = json_decode ($json_string2);
$parsed_json3 = json_decode ($json_string3);
$location = $parsed_json->{'response'}->{'version'};
$test = $parsed_json2->{"moon_phase"}->{"phaseofMoon"};
$a = $parsed_json3->{"trip"}->{"title"};
echo "dapat dilihat dari wilayah jawa tengah,semarang";
echo "<br>";
echo "Current temperature in ${location}\n";
echo "<br>";
echo "dilihat dari perkembangan bulan di wilayah jawa tengah:${test}\n";
echo "<br>";
echo "Jumlah hari di bulan mei : ${a}\n";
?> | fb92690b67087135eb3d61dfeaee037fd38ac69c | [
"PHP"
] | 1 | PHP | suryaabednego/tugasweb | c6a182363aa214314cf224245dee5069a545e006 | 3849d6fee05e73bdce905671003216a07ce75312 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AntaresAzureDNS;
namespace CrossStampFunctional
{
class Program
{
const string _sub = "00e7bb72-7725-4249-8e6b-0d2632b3bfc1";
const string _ws = "eastuswebspace";
const string _dummy = "suwatchet01";
const string _site = "functionsuw200";
const string _siteSlot = "functionslot200";
const string _slotName = "Staging";
const string _sf = "EastUSPlan";
static string _storageAccount = "";
static string _storageKey = "";
static IList<string> _workers = null;
static string _publishingUserName = null;
static string _publishingPassword = null;
static string _validationKey = null;
static string _decryptionKey = null;
const string _geoMasterCmd = @"c:\temp\geomaster\AntaresCmd.exe";
const string _geoRegionCmd = @"c:\temp\georegion\AntaresCmd.exe";
const string _blu1Cmd = @"c:\temp\blu1\AntaresCmd.exe";
const string _blu2Cmd = @"c:\temp\blu2\AntaresCmd.exe";
const string _blu1 = "blu1";
const string _blu2 = "blu2";
const string _full = "Full";
const string _free = "Free";
const string _dnsSuffix = "kudu1.antares-test.windows-int.net";
const string _blu1HostName = "blu1.api.kudu1.antares-test.windows-int.net";
const string _blu2HostName = "blu2.api.kudu1.antares-test.windows-int.net";
static string _blu1IPAddress;
static string _blu2IPAddress;
const string _clientCertPfxFile = @"c:\temp\RdfeTestClientCert2016.pfx";
const string _clientCertPwdFile = @"c:\temp\RdfeTestClientCert2016.pfx.txt";
const string _clientCertThumbprintFile = @"c:\temp\RdfeTestClientCert2016.tp.txt";
static string _clientCertPwd = File.ReadAllText(_clientCertPwdFile).Trim();
static string _clientCertThumbprint = File.ReadAllText(_clientCertThumbprintFile).Trim().ToUpperInvariant();
static int _requestId = 10000000;
static int Main(string[] args)
{
try
{
// initially no timer trigger
Initialize();
CreateDummySite();
CreateFunctionSite();
ValidateHotBackup();
HttpForwardTest();
NotifyFullTest();
ValidateConfigPropagation();
ValidateServerFarmPropagation();
ValidateCertificatesPropagation();
ValidateTimerTriggerPropagation();
NotifyFreeTest();
NotifyFullTest();
SlotCreateFunctionSite();
SlotSwapTest_1();
SlotSwapTest_2();
DeleteFunctionSite();
Console.WriteLine("{0} Summary results: passed", DateTime.Now.ToString("o"));
return 0;
}
catch (Exception ex)
{
Console.WriteLine("{0} Summary results: failed {1}", DateTime.Now.ToString("o"), ex);
return -1;
}
}
static void Initialize()
{
var lines = File.ReadAllLines(@"c:\temp\antfunctions.txt");
_storageAccount = lines[0].Trim();
_storageKey = lines[1].Trim();
InitializeStampIPs();
EnableAllWorkers();
DeleteAllCertificates();
// Reset
RunAndValidate(String.Empty,
_geoMasterCmd,
1,
"DeleteWebSite {0} {1} {2} /deleteEmptyServerFarm /deleteAllSlots",
_sub, _ws, _siteSlot);
RunAndValidate(String.Empty,
_geoMasterCmd,
1,
"DeleteWebSite {0} {1} {2} /deleteEmptyServerFarm /deleteAllSlots",
_sub, _ws, _site);
RunAndValidate(String.Empty,
_geoMasterCmd,
1,
"DeleteWebSite {0} {1} {2}",
_sub, _ws, _dummy);
RunAndValidate("![0]", _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate("!" + _dummy, _geoMasterCmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("!" + _site, _geoMasterCmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("!" + _site, _blu1Cmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("!" + _site, _blu2Cmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("!" + _siteSlot, _geoMasterCmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("!" + _siteSlot, _blu1Cmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("!" + _siteSlot, _blu2Cmd, "ListWebSites {0} {1}", _sub, _ws);
//RunAndValidate("!" + _sf, _geoMasterCmd, "ListServerFarms {0} {1}", _sub, _ws);
//RunAndValidate("!" + _sf, _blu1Cmd, "ListServerFarms {0} {1}", _sub, _ws);
//RunAndValidate("!" + _sf, _blu2Cmd, "ListServerFarms {0} {1}", _sub, _ws);
}
static void InitializeStampIPs()
{
_blu1IPAddress = Dns.GetHostEntry(_blu1HostName).AddressList[0].ToString();
_blu2IPAddress = Dns.GetHostEntry(_blu2HostName).AddressList[0].ToString();
}
static void ValidateDnsHostEntry(string hostName, params string[] ipAddresses)
{
foreach (var ipAddress in ipAddresses)
{
var success = false;
var content = string.Empty;
Console.WriteLine();
for (int i = 0; i < 24 && !success; ++i)
{
Console.WriteLine("ValidateDns: {0}, {1}", hostName, ipAddress);
Console.WriteLine(DateTime.Now.ToString("o"));
var addresses = string.Join(",", GetIpAddresses(hostName));
Console.WriteLine("Dns: {0}, {1}", hostName, addresses);
var expect = ipAddress.Trim('!');
success = addresses.Contains(expect) == !ipAddress.StartsWith("!");
if (!success)
{
Thread.Sleep(5000);
}
//var digUrl = string.Format("http://dig.jsondns.org/IN/{0}/A", hostName);
//using (var client = new HttpClient())
//{
// using (var response = client.GetAsync(digUrl).Result)
// {
// content = "Dig status: " + response.StatusCode;
// Console.WriteLine(content);
// if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.NotFound)
// {
// content = response.Content.ReadAsStringAsync().Result;
// var expect = ipAddress.Trim('!');
// success = content.Contains("\"" + expect + "\"") == !ipAddress.StartsWith("!");
// }
// }
//}
}
if (success)
{
Console.WriteLine("Passed.");
}
else
{
throw new InvalidOperationException(String.Format(DateTime.Now.ToString("o") + ", ValidateDns: {0}, {1}", ipAddress, hostName));
//try
//{
// throw new InvalidOperationException(String.Format(DateTime.Now.ToString("o") + ", ValidateDns: {0}, {1}", ipAddress, hostName));
//}
//catch (Exception ex)
//{
// _dnsExceptions.Add(ex);
//}
}
}
}
static string[] GetIpAddresses(string hostName)
{
var addresses = new List<string>();
GetIpAddresses(hostName, addresses);
return addresses.ToArray();
}
static void GetIpAddresses(string hostName, List<string> addresses)
{
if (hostName.EndsWith(_dnsSuffix))
{
foreach (var name in DNSHelper.ListAllCNameRecords(hostName))
{
GetIpAddresses(name.TrimEnd('.'), addresses);
}
foreach (var aRecord in DNSHelper.ListAllARecords(hostName))
{
addresses.Add(aRecord);
}
}
else
{
var entry = Dns.GetHostEntry(hostName);
addresses.AddRange(entry.AddressList.Select(ip => ip.ToString()));
}
}
//static string GetIpAddresses(string hostName)
//{
// try
// {
// var entry = Dns.GetHostEntry(hostName);
// return string.Join(",", entry.AddressList.Select(ip => "[" + ip.ToString() + "]"));
// }
// catch (Exception ex)
// {
// return ex.Message;
// }
//}
static void CreateDummySite()
{
// Warmup
RunAndValidate(String.Format("{0}.{1}", _dummy, _dnsSuffix),
_geoMasterCmd,
1,
"CreateWebSite {0} {1} {2}",
_sub, _ws, _dummy);
RunAndValidate(_dummy, _geoMasterCmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate(_dummy, _blu1Cmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("Completed successfully", _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
}
static void CreateFunctionSite()
{
// CreateFunctionSite
RunAndValidate(String.Format("{0}.{1}", _site, _dnsSuffix),
_geoMasterCmd,
1,
"CreateFunctionSite {0} {1} {2} /storageAccount:{3} /storageKey:{4} /appSettings:WEBSITE_LOAD_CERTIFICATES=*,FUNCTIONS_EXTENSION_VERSION=~0.8",
_sub, _ws, _site, _storageAccount, _storageKey);
ValidateDnsHostEntry(String.Format("{0}.{1}", _site, _dnsSuffix), _blu1IPAddress, "!" + _blu2IPAddress);
ValidateDnsHostEntry(String.Format("{0}.scm.{1}", _site, _dnsSuffix), _blu1IPAddress, "!" + _blu2IPAddress);
// initially no timer trigger
RetryHelper(() => DeleteTimerTrigger());
RunAndValidate("SyncWebSiteTriggers Response: OK",
_geoMasterCmd,
"SyncWebSiteTriggers {0} {1} {2}",
_sub, _ws, _site);
RunAndValidate("Triggers: [{\"",
_geoMasterCmd,
"GetWebSiteTriggers {0} {1} {2}",
_sub, _ws, _site);
// Get publishing cred
EnsurePublishingCred();
// Get MachineKey
EnsureMachineKey();
}
static void EnsurePublishingCred()
{
if (_publishingUserName == null || _publishingPassword == null)
{
Console.WriteLine(DateTime.Now.ToString("o"));
var output = Run(_blu1Cmd, "GetWebSiteConfig {0} {1} {2}", _sub, _ws, _site);
using (var reader = new StringReader(output))
{
string publishingUserName = null;
string publishingPassword = null;
while (publishingUserName == null || publishingPassword == null)
{
var line = reader.ReadLine();
if (line == null)
{
break;
}
// PublishingUsername: $functionsuw200
// PublishingPassword: <PASSWORD>\
var parts = line.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2)
{
if (parts[0] == "PublishingUsername:")
{
publishingUserName = parts[1];
}
else if (parts[0] == "PublishingPassword:")
{
publishingPassword = parts[1];
}
}
}
if (publishingUserName == null || publishingPassword == null)
{
throw new InvalidOperationException("no publishing cred found. " + output);
}
_publishingUserName = publishingUserName;
_publishingPassword = <PASSWORD>Password;
}
}
}
static void EnsureMachineKey()
{
if (_validationKey == null || _decryptionKey == null)
{
Console.WriteLine(DateTime.Now.ToString("o"));
var output = Run(_blu1Cmd, "GetWebSiteConfig {0} {1} {2}", _sub, _ws, _site);
using (var reader = new StringReader(output))
{
string validationKey = null;
string decryptionKey = null;
while (validationKey == null || decryptionKey == null)
{
var line = reader.ReadLine();
if (line == null)
{
break;
}
// ValidationKey: 9463CD095F3AA2C2EE0663B102CED9C61B40A06D0C3C4ADDD616AA3EA6614064
// Decryption: AES
// DecryptionKey: 7BE95A7E5B94976384F42C9E9CC34027A7CC00E03C3CC8C960C0D8631412C076
var parts = line.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2)
{
if (parts[0] == "ValidationKey:")
{
validationKey = parts[1];
}
else if (parts[0] == "DecryptionKey:")
{
decryptionKey = parts[1];
}
}
}
if (validationKey == null || decryptionKey == null)
{
throw new InvalidOperationException("no machine key found. " + output);
}
_validationKey = validationKey;
_decryptionKey = decryptionKey;
}
}
}
static void ValidateTimerTriggerPropagation()
{
// add timer trigger
RetryHelper(() => AddTimerTrigger());
RunAndValidate("SyncWebSiteTriggers Response: OK",
_geoMasterCmd,
"SyncWebSiteTriggers {0} {1} {2}",
_sub, _ws, _site);
RunAndValidate("\"type\":\"timerTrigger",
_geoMasterCmd,
"GetWebSiteTriggers {0} {1} {2}",
_sub, _ws, _site);
RunAndValidate("\"type\":\"timerTrigger",
_blu2Cmd,
"GetWebSiteTriggers {0} {1} {2}",
_sub, _ws, _site);
}
static void ValidateHotBackup()
{
// Check if hot back up
RunAndValidate("StampName: " + _blu1, _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate("StampName: " + _blu2, _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate("Idle: True", _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate(_site, _blu2Cmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("State: Running", _blu1Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _site);
RunAndValidate("HomeStamp: " + _blu1, _blu1Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _site);
HttpGet(new Uri(String.Format("http://{0}", _blu1HostName)),
String.Format("{0}.{1}", _site, _dnsSuffix),
HttpStatusCode.OK);
RunAndValidate("State: Stopped", _blu2Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _site);
RunAndValidate("HomeStamp: " + _blu1, _blu2Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _site);
// always serve incoming request to slave stamp
HttpGet(new Uri(String.Format("http://{0}", _blu2HostName)),
String.Format("{0}.{1}", _site, _dnsSuffix),
HttpStatusCode.OK);
// Ensure same publishing cred
RunAndValidate("PublishingPassword: " + _publishingPassword,
_blu2Cmd,
"GetWebSiteConfig {0} {1} {2}",
_sub, _ws, _site);
// Ensure same machine key
RunAndValidate("ValidationKey: " + _validationKey,
_blu2Cmd,
"GetWebSiteConfig {0} {1} {2}",
_sub, _ws, _site);
RunAndValidate("DecryptionKey: " + _decryptionKey,
_blu2Cmd,
"GetWebSiteConfig {0} {1} {2}",
_sub, _ws, _site);
}
static void HttpForwardTest()
{
DisableAllWorkers();
// wait for host cache to stale
Console.WriteLine("{0} Sleep 60s", DateTime.Now.ToString("o"));
Thread.Sleep(60000);
HttpGet(new Uri(String.Format("http://{0}.{1}", _site, _dnsSuffix)),
null,
HttpStatusCode.OK);
HttpGet(new Uri(String.Format("https://{0}.{1}", _site, _dnsSuffix)),
null,
HttpStatusCode.OK);
HttpGet(new Uri(String.Format("http://{0}.scm.{1}", _site, _dnsSuffix)),
null,
HttpStatusCode.Redirect);
HttpGet(new Uri(String.Format("https://{0}.scm.{1}", _site, _dnsSuffix)),
null,
HttpStatusCode.Unauthorized);
HttpGet(new Uri(String.Format("https://{0}.scm.{1}", _site, _dnsSuffix)),
null,
HttpStatusCode.OK,
_publishingUserName,
_publishingPassword);
// http forward should lead to notifyfull
RunAndValidate("!Idle: True", _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate("State: Running", _blu2Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _site);
EnableAllWorkers();
// slave should scale back
// TODO, suwatch: flaky
// HACK HACK
// wait for Notify Full to stale
Console.WriteLine("{0} Sleep 300s", DateTime.Now.ToString("o"));
Thread.Sleep(300000);
RunAndValidate("Completed successfully.",
_geoRegionCmd,
"Notify {0} {1} {2} {3} {4} {5}",
_blu2, _free, _sub, _ws, _site, _sf);
RunAndValidate("Idle: True", _geoRegionCmd, 120, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate("State: Stopped", _blu2Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _site);
}
static void DisableAllWorkers()
{
foreach (var worker in GetAllWorkers())
{
SetWorkerState(worker, enabled: false);
}
CheckCapacity(_blu1Cmd, hasCapacity: false);
}
static void EnableAllWorkers()
{
foreach (var worker in GetAllWorkers())
{
SetWorkerState(worker, enabled: true);
}
CheckCapacity(_blu1Cmd, hasCapacity: true);
}
static void SetWorkerState(string worker, bool enabled)
{
RunAndValidate(String.Format("Web worker {0} has been updated", worker),
_blu1Cmd,
"SetWebWorkerState WebSites {0} /enabled:{1}", worker, enabled ? '1' : '0');
}
static IList<string> GetAllWorkers()
{
if (_workers == null)
{
Console.WriteLine(DateTime.Now.ToString("o"));
var output = Run(_blu1Cmd, "ListWebWorkers WebSites");
var workers = new List<string>();
using (var reader = new StringReader(output))
{
while (true)
{
var line = reader.ReadLine();
if (line == null)
{
break;
}
IPAddress address;
if (IPAddress.TryParse(line.Trim(), out address))
{
workers.Add(address.ToString());
}
}
}
if (!workers.Any())
{
throw new InvalidOperationException("no worker found. " + output);
}
_workers = workers;
}
return _workers;
}
static void SlotCreateFunctionSite()
{
// CreateFunctionSite and slot
RunAndValidate(String.Format("{0}.{1}", _siteSlot, _dnsSuffix),
_geoMasterCmd,
1,
"CreateFunctionSite {0} {1} {2} /storageAccount:{3} /storageKey:{4} /appSettings:WEBSITE_LOAD_CERTIFICATES=*,FUNCTIONS_EXTENSION_VERSION=~0.8",
_sub, _ws, _siteSlot, _storageAccount, _storageKey);
RunAndValidate(String.Format("{0}-{1}.{2}", _siteSlot, _slotName.ToLowerInvariant(), _dnsSuffix),
_geoMasterCmd,
1,
"CreateWebSiteSlot {0} {1} {2} {3}",
_sub, _ws, _siteSlot, _slotName);
// pushing trigger
RunAndValidate("SyncWebSiteTriggers Response: OK",
_geoMasterCmd,
"SyncWebSiteTriggers {0} {1} {2}",
_sub, _ws, _siteSlot);
RunAndValidate("CSharpHttpTriggerProduction",
_geoMasterCmd,
"GetWebSiteTriggers {0} {1} {2}",
_sub, _ws, _siteSlot);
RunAndValidate("SyncWebSiteTriggers Response: OK",
_geoMasterCmd,
"SyncWebSiteTriggers {0} {1} {2}({3})",
_sub, _ws, _siteSlot, _slotName);
RunAndValidate("CSharpHttpTriggerStaging",
_geoMasterCmd,
"GetWebSiteTriggers {0} {1} {2}({3})",
_sub, _ws, _siteSlot, _slotName);
// Propagate
SlotValidateHotBackup();
// HttpGet Production
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerProduction?name=foo", _blu1HostName)),
String.Format("{0}.{1}", _siteSlot, _dnsSuffix),
HttpStatusCode.OK,
expectedContent: _siteSlot + "(Production)");
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerProduction?name=foo", _blu2HostName)),
String.Format("{0}.{1}", _siteSlot, _dnsSuffix),
HttpStatusCode.OK,
expectedContent: _siteSlot + "(Production)");
// HttpGet Staging
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerStaging?name=foo", _blu1HostName)),
String.Format("{0}-{1}.{2}", _siteSlot, _slotName.ToLowerInvariant(), _dnsSuffix),
HttpStatusCode.OK,
expectedContent: _siteSlot + "(Staging)");
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerStaging?name=foo", _blu2HostName)),
String.Format("{0}-{1}.{2}", _siteSlot, _slotName.ToLowerInvariant(), _dnsSuffix),
HttpStatusCode.NotFound);
}
static void SlotValidateHotBackup()
{
// Check if hot back up Production
RunAndValidate("StampName: " + _blu1, _geoRegionCmd, "ListSiteStamps /siteName:{0}", _siteSlot);
RunAndValidate("StampName: " + _blu2, _geoRegionCmd, "ListSiteStamps /siteName:{0}", _siteSlot);
RunAndValidate("Idle: True", _geoRegionCmd, "ListSiteStamps /siteName:{0}", _siteSlot);
RunAndValidate(_siteSlot, _blu2Cmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("State: Running", _blu1Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _siteSlot);
RunAndValidate("HomeStamp: " + _blu1, _blu1Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _siteSlot);
HttpGet(new Uri(String.Format("http://{0}", _blu1HostName)),
String.Format("{0}.{1}", _siteSlot, _dnsSuffix),
HttpStatusCode.OK);
RunAndValidate("State: Stopped", _blu2Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _siteSlot);
RunAndValidate("HomeStamp: " + _blu1, _blu2Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _siteSlot);
// Check if hot back up Staging
RunAndValidate("!StampName: " + _blu1, _geoRegionCmd, "ListSiteStamps /siteName:{0}-{1}", _siteSlot, _slotName.ToLowerInvariant());
RunAndValidate("!StampName: " + _blu2, _geoRegionCmd, "ListSiteStamps /siteName:{0}-{1}", _siteSlot, _slotName.ToLowerInvariant());
RunAndValidate("State: Running", _blu1Cmd, "GetWebSite {0} {1} {2}({3})", _sub, _ws, _siteSlot, _slotName.ToLowerInvariant());
RunAndValidate("HomeStamp: " + _blu1, _blu1Cmd, "GetWebSite {0} {1} {2}({3})", _sub, _ws, _siteSlot, _slotName.ToLowerInvariant());
RunAndValidate("(404) Not Found", _blu2Cmd, "GetWebSite {0} {1} {2}({3})", _sub, _ws, _siteSlot, _slotName.ToLowerInvariant());
// ensure trigger propagation
RunAndValidate("CSharpHttpTriggerProduction",
_blu2Cmd,
"GetWebSiteTriggers {0} {1} {2}",
_sub, _ws, _siteSlot);
}
static void SlotSwapTest_1()
{
SwapSiteSlots();
// Trigger has swap
RunAndValidate("CSharpHttpTriggerStaging",
_geoMasterCmd,
"GetWebSiteTriggers {0} {1} {2}",
_sub, _ws, _siteSlot);
RunAndValidate("CSharpHttpTriggerProduction",
_geoMasterCmd,
"GetWebSiteTriggers {0} {1} {2}({3})",
_sub, _ws, _siteSlot, _slotName);
// ensure trigger propagation
RunAndValidate("CSharpHttpTriggerStaging",
_blu2Cmd,
"GetWebSiteTriggers {0} {1} {2}",
_sub, _ws, _siteSlot);
// HttpGet Production
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerStaging?name=foo", _blu1HostName)),
String.Format("{0}.{1}", _siteSlot, _dnsSuffix),
HttpStatusCode.OK,
expectedContent: _siteSlot + "(Staging)");
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerStaging?name=foo", _blu2HostName)),
String.Format("{0}.{1}", _siteSlot, _dnsSuffix),
HttpStatusCode.OK,
expectedContent: _siteSlot + "(Staging)");
// HttpGet Staging
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerProduction?name=foo", _blu1HostName)),
String.Format("{0}-{1}.{2}", _siteSlot, _slotName.ToLowerInvariant(), _dnsSuffix),
HttpStatusCode.OK,
expectedContent: _siteSlot + "(Production)");
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerProduction?name=foo", _blu2HostName)),
String.Format("{0}-{1}.{2}", _siteSlot, _slotName.ToLowerInvariant(), _dnsSuffix),
HttpStatusCode.NotFound);
}
static void SlotSwapTest_2()
{
SwapSiteSlots();
// Trigger has swap
RunAndValidate("CSharpHttpTriggerProduction",
_geoMasterCmd,
"GetWebSiteTriggers {0} {1} {2}",
_sub, _ws, _siteSlot);
RunAndValidate("CSharpHttpTriggerStaging",
_geoMasterCmd,
"GetWebSiteTriggers {0} {1} {2}({3})",
_sub, _ws, _siteSlot, _slotName);
// ensure trigger propagation
RunAndValidate("CSharpHttpTriggerProduction",
_blu2Cmd,
"GetWebSiteTriggers {0} {1} {2}",
_sub, _ws, _siteSlot);
// HttpGet Production
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerProduction?name=foo", _blu1HostName)),
String.Format("{0}.{1}", _siteSlot, _dnsSuffix),
HttpStatusCode.OK,
expectedContent: _siteSlot + "(Production)");
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerProduction?name=foo", _blu2HostName)),
String.Format("{0}.{1}", _siteSlot, _dnsSuffix),
HttpStatusCode.OK,
expectedContent: _siteSlot + "(Production)");
// HttpGet Staging
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerStaging?name=foo", _blu1HostName)),
String.Format("{0}-{1}.{2}", _siteSlot, _slotName.ToLowerInvariant(), _dnsSuffix),
HttpStatusCode.OK,
expectedContent: _siteSlot + "(Staging)");
HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTriggerStaging?name=foo", _blu2HostName)),
String.Format("{0}-{1}.{2}", _siteSlot, _slotName.ToLowerInvariant(), _dnsSuffix),
HttpStatusCode.NotFound);
}
static void SwapSiteSlots()
{
Console.WriteLine(DateTime.Now.ToString("o"));
//RequestID = 3dc25123-0e04-4674-932e-994d74f2a642, request created at 2016-09-26T05:37:54.5169457Z
//Request to swap site slot 'functionslot200' with slot 'Staging' has been submitted.
//Use the command below to get the status of the request:
//AntaresCmd.exe GetWebSiteOperation 00e7bb72-7725-4249-8e6b-0d2632b3bfc1 eastuswebspace functionslot200
//df6eb4ec-3ebd-407c-a534-03b8e54565cb
var output = Run(_geoMasterCmd, "SwapWebSiteSlots {0} {1} {2} {3}", _sub, _ws, _siteSlot, _slotName);
var success = false;
var operationCmd = string.Empty;
using (var reader = new StringReader(output))
{
while (string.IsNullOrEmpty(operationCmd))
{
var line = reader.ReadLine();
if (line == null)
break;
if (success)
{
if (line.Trim().StartsWith("AntaresCmd.exe GetWebSiteOperation "))
{
operationCmd = line.Trim();
break;
}
continue;
}
success = line.Contains(string.Format("Request to swap site slot '{0}' with slot '{1}' has been submitted", _siteSlot, _slotName));
}
}
if (!success || string.IsNullOrEmpty(operationCmd))
{
throw new InvalidOperationException("Fail SwapSiteSlots\r\n" + output);
}
RunAndValidate("Status: Succeeded",
_geoMasterCmd,
operationCmd.Replace("AntaresCmd.exe ", string.Empty));
}
static void NotifyFullTest()
{
// ensure capacities
CheckCapacity(_blu1Cmd, hasCapacity: true);
CheckCapacity(_blu2Cmd, hasCapacity: true);
// Notify full
RunAndValidate("Completed successfully.",
_geoRegionCmd,
"Notify {0} {1} {2} {3} {4} {5}",
_blu1, _full, _sub, _ws, _site, _sf);
RunAndValidate("StampName: blu1", _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate("StampName: blu2", _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate(_site, _blu2Cmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("!Idle: True", _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate("State: Running", _blu2Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _site);
ValidateDnsHostEntry(String.Format("{0}.{1}", _site, _dnsSuffix), _blu1IPAddress, _blu2IPAddress);
ValidateDnsHostEntry(String.Format("{0}.scm.{1}", _site, _dnsSuffix), _blu1IPAddress, "!" + _blu2IPAddress);
HttpGet(new Uri(String.Format("http://{0}", _blu2HostName)),
String.Format("{0}.{1}", _site, _dnsSuffix),
HttpStatusCode.OK);
}
static void CheckCapacity(string antaresCmd, bool hasCapacity)
{
RunAndValidate("Size: 1536, Available: ",
antaresCmd,
"GetDynamicSkuContainerCapacities");
if (hasCapacity)
{
RunAndValidate("!Size: 1536, Available: 0",
antaresCmd,
"GetDynamicSkuContainerCapacities");
}
else
{
RunAndValidate("Size: 1536, Available: 0",
antaresCmd,
"GetDynamicSkuContainerCapacities");
}
}
static void ValidateConfigPropagation()
{
// compensate for clock skew
Console.WriteLine("{0} Sleep 60s", DateTime.Now.ToString("o"));
Thread.Sleep(60000);
// UpdateWebSiteConfig propagation
RunAndValidate(String.Format("Configuration for website {0} has been updated.", _site),
_geoMasterCmd,
"UpdateWebSiteConfig {0} {1} {2} {3}",
_sub, _ws, _site, "/scmType:LocalGit");
RunAndValidate("ScmType: LocalGit",
_blu2Cmd,
"GetWebSiteConfig {0} {1} {2}",
_sub, _ws, _site);
// Ensure same publishing cred
RunAndValidate("PublishingPassword: " + _publishingPassword,
_blu2Cmd,
"GetWebSiteConfig {0} {1} {2}",
_sub, _ws, _site);
// Ensure same machine key
RunAndValidate("ValidationKey: " + _validationKey,
_blu2Cmd,
"GetWebSiteConfig {0} {1} {2}",
_sub, _ws, _site);
RunAndValidate("DecryptionKey: " + _decryptionKey,
_blu2Cmd,
"GetWebSiteConfig {0} {1} {2}",
_sub, _ws, _site);
RunAndValidate("HomeStamp: " + _blu1, _blu1Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _site);
RunAndValidate("HomeStamp: " + _blu1, _blu2Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _site);
}
static void ValidateServerFarmPropagation()
{
// compensate for clock skew
Console.WriteLine("{0} Sleep 60s", DateTime.Now.ToString("o"));
Thread.Sleep(60000);
var lastModifiedTime1 = GetServerFarmLastModifiedTime(_geoMasterCmd);
var lastModifiedTime2 = GetServerFarmLastModifiedTime(_blu2Cmd);
if (lastModifiedTime1 > lastModifiedTime2)
{
throw new InvalidOperationException(lastModifiedTime1 + " > " + lastModifiedTime2);
}
// UpdateServerFarm propagation
RunAndValidate(String.Format("Server farm {0} has been updated.", _sf),
_geoMasterCmd,
"UpdateServerFarm {0} {1} {2} Dynamic /workerSize:0",
_sub, _ws, _sf);
var lastModifiedTime = GetServerFarmLastModifiedTime(_geoMasterCmd);
if (lastModifiedTime1 > lastModifiedTime)
{
throw new InvalidOperationException(lastModifiedTime1 + " > " + lastModifiedTime);
}
if (lastModifiedTime2 > lastModifiedTime)
{
throw new InvalidOperationException(lastModifiedTime2 + " > " + lastModifiedTime);
}
lastModifiedTime1 = lastModifiedTime;
lastModifiedTime = lastModifiedTime2;
for (int i = 24; lastModifiedTime == lastModifiedTime2; --i)
{
if (i <= 0)
{
throw new InvalidOperationException("Timeout waiting for serverFarm change");
}
Thread.Sleep(5000);
lastModifiedTime = GetServerFarmLastModifiedTime(_blu2Cmd);
}
if (lastModifiedTime1 > lastModifiedTime)
{
throw new InvalidOperationException(lastModifiedTime1 + " > " + lastModifiedTime);
}
if (lastModifiedTime2 > lastModifiedTime)
{
throw new InvalidOperationException(lastModifiedTime2 + " > " + lastModifiedTime);
}
}
static DateTime GetServerFarmLastModifiedTime(string cmd)
{
Console.WriteLine(DateTime.Now.ToString("o"));
var output = Run(cmd, "GetServerFarm {0} {1} {2}", _sub, _ws, _sf);
using (var reader = new StringReader(output))
{
while (true)
{
var line = reader.ReadLine();
if (line == null)
{
break;
}
// LastModifiedTimeUtc: 8/31/2016 9:23:38 PM
var parts = line.Trim().Split(new[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2 && parts[0] == "LastModifiedTimeUtc")
{
return DateTime.Parse(parts[1].Trim()).ToLocalTime();
}
}
}
throw new InvalidOperationException(output);
}
static void DeleteAllCertificates()
{
foreach (var thumbprint in GetAllCertificates())
{
RunAndValidate("Certificate was deleted.",
_geoMasterCmd,
"DeleteCertificate {0} {1} {2}",
_sub, _ws, thumbprint);
}
}
static IList<string> GetAllCertificates()
{
Console.WriteLine(DateTime.Now.ToString("o"));
var output = Run(_geoMasterCmd, "GetCertificates {0} {1}", _sub, _ws);
var thumbprints = new List<string>();
using (var reader = new StringReader(output))
{
while (true)
{
var line = reader.ReadLine();
if (line == null)
{
break;
}
var index = line.IndexOf("Thumbprint: ");
if (index >= 0)
{
thumbprints.Add(line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Last().Trim());
}
}
}
return thumbprints;
}
static void ValidateCertificatesPropagation()
{
// compensate for clock skew
Console.WriteLine("{0} Sleep 60s", DateTime.Now.ToString("o"));
Thread.Sleep(60000);
// AddCertificates propagation
RunAndValidate(String.Format("Certficates were added to the webspace", _site),
_geoMasterCmd,
"AddCertificates {0} {1} {2} {3}",
_sub, _ws, _clientCertPfxFile, _clientCertPwd);
RunAndValidate("Thumbprint: " + _clientCertThumbprint,
_blu2Cmd,
"GetCertificates {0} {1}",
_sub, _ws);
// Hit the site
//HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTrigger?name=foo", _blu1HostName)),
// String.Format("{0}.{1}", _site, _dnsSuffix),
// HttpStatusCode.OK,
// expectedContent: _clientCertThumbprint);
//HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTrigger?name=foo", _blu2HostName)),
// String.Format("{0}.{1}", _site, _dnsSuffix),
// HttpStatusCode.OK,
// expectedContent: _clientCertThumbprint);
// DeleteCertificate propagation
RunAndValidate("Certificate was deleted.",
_geoMasterCmd,
"DeleteCertificate {0} {1} {2}",
_sub, _ws, _clientCertThumbprint);
RunAndValidate("!Thumbprint:",
_blu2Cmd,
"GetCertificates {0} {1}",
_sub, _ws);
// Hit the site
//HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTrigger?name=foo", _blu1HostName)),
// String.Format("{0}.{1}", _site, _dnsSuffix),
// HttpStatusCode.OK,
// expectedContent: "!" + _clientCertThumbprint);
//HttpGet(new Uri(String.Format("http://{0}/api/CSharpHttpTrigger?name=foo", _blu2HostName)),
// String.Format("{0}.{1}", _site, _dnsSuffix),
// HttpStatusCode.OK,
// expectedContent: "!" + _clientCertThumbprint);
}
static void NotifyFreeTest()
{
// Notify free from blu2
RunAndValidate("Completed successfully.",
_geoRegionCmd,
"Notify {0} {1} {2} {3} {4} {5}",
_blu2, _free, _sub, _ws, _site, _sf);
RunAndValidate("StampName: " + _blu1, _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate("StampName: " + _blu2, _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate("Idle: True", _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate(_site, _blu2Cmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("State: Running", _blu1Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _site);
HttpGet(new Uri(String.Format("http://{0}", _blu1HostName)),
String.Format("{0}.{1}", _site, _dnsSuffix),
HttpStatusCode.OK);
RunAndValidate("State: Stopped", _blu2Cmd, "GetWebSite {0} {1} {2}", _sub, _ws, _site);
// always serve incoming request to slave stamp
HttpGet(new Uri(String.Format("http://{0}", _blu2HostName)),
String.Format("{0}.{1}", _site, _dnsSuffix),
HttpStatusCode.OK);
ValidateDnsHostEntry(String.Format("{0}.{1}", _site, _dnsSuffix), _blu1IPAddress, "!" + _blu2IPAddress);
ValidateDnsHostEntry(String.Format("{0}.scm.{1}", _site, _dnsSuffix), _blu1IPAddress, "!" + _blu2IPAddress);
}
static void DeleteFunctionSite()
{
RunAndValidate(String.Empty,
_geoMasterCmd,
1,
"DeleteWebSite {0} {1} {2} /deleteEmptyServerFarm /deleteAllSlots",
_sub, _ws, _siteSlot);
RunAndValidate(String.Empty,
_geoMasterCmd,
1,
"DeleteWebSite {0} {1} {2} /deleteEmptyServerFarm /deleteAllSlots",
_sub, _ws, _site);
RunAndValidate("![0]", _geoRegionCmd, "ListSiteStamps /siteName:{0}", _site);
RunAndValidate("!" + _site, _geoMasterCmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("!" + _site, _blu1Cmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("!" + _site, _blu2Cmd, 240, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("![0]", _geoRegionCmd, "ListSiteStamps /siteName:{0}", _siteSlot);
RunAndValidate("!" + _siteSlot, _geoMasterCmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("!" + _siteSlot, _blu1Cmd, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate("!" + _siteSlot, _blu2Cmd, 240, "ListWebSites {0} {1}", _sub, _ws);
RunAndValidate(_ws, _blu1Cmd, "ListWebSpaces {0}", _sub);
RunAndValidate("!" + _ws, _blu2Cmd, "ListWebSpaces {0}", _sub);
ValidateDnsHostEntry(String.Format("{0}.{1}", _site, _dnsSuffix), "!" + _blu1IPAddress, "!" + _blu2IPAddress);
ValidateDnsHostEntry(String.Format("{0}.scm.{1}", _site, _dnsSuffix), "!" + _blu1IPAddress, "!" + _blu2IPAddress);
}
static bool HasTimerTrigger()
{
var request = GetTimerTriggerRequest();
request.Method = "GET";
var requestId = Guid.Empty.ToString().Replace("00000000-", Interlocked.Increment(ref _requestId) + "-");
request.Headers.Add("x-ms-request-id", requestId);
Console.WriteLine();
Console.Write(DateTime.Now.ToString("o") + ", HasTimerTrigger ");
Console.Write("x-ms-request-id: " + requestId + " ");
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine("response " + response.StatusCode);
return true;
}
}
catch (Exception ex)
{
if (ex.Message.Contains("Not Found"))
{
Console.WriteLine("response NotFound");
return false;
}
throw;
}
}
static void DeleteTimerTrigger()
{
var request = GetTimerTriggerRequest();
request.Method = "DELETE";
request.Headers.Add("If-Match", "*");
var requestId = Guid.Empty.ToString().Replace("00000000-", Interlocked.Increment(ref _requestId) + "-");
request.Headers.Add("x-ms-request-id", requestId);
Console.WriteLine();
Console.Write(DateTime.Now.ToString("o") + ", DeleteTimerTrigger ");
Console.Write("x-ms-request-id: " + requestId + " ");
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine("response " + response.StatusCode);
}
}
catch (WebException ex)
{
if (!ex.Message.Contains("(404)"))
{
throw;
}
}
}
static void RetryHelper(Action action)
{
int max = 5;
while (true)
{
try
{
action();
break;
}
catch (Exception ex)
{
Console.WriteLine(ex);
if (max-- < 0)
throw;
}
Thread.Sleep(5000);
}
}
static void AddTimerTrigger()
{
const string TimerTriggerFile = @"c:\temp\SampleTimerTrigger_function.json";
var request = GetTimerTriggerRequest();
request.Method = "PUT";
request.Headers.Add("If-Match", "*");
request.ContentType = "application/json";
var requestId = Guid.Empty.ToString().Replace("00000000-", Interlocked.Increment(ref _requestId) + "-");
request.Headers.Add("x-ms-request-id", requestId);
Console.WriteLine();
Console.Write(DateTime.Now.ToString("o") + ", AddTimerTrigger ");
Console.Write("x-ms-request-id: " + requestId + " ");
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(File.ReadAllText(TimerTriggerFile));
}
using (var response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine("response " + response.StatusCode);
}
}
static HttpWebRequest GetTimerTriggerRequest()
{
var timerTriggerUrl = String.Format("https://{0}/vfs/site/wwwroot/SampleTimerTrigger/function.json", _blu1HostName);
var request = (HttpWebRequest)WebRequest.Create(timerTriggerUrl);
request.Credentials = new NetworkCredential("auxtm230", "iis6!dfu");
request.Host = String.Format("{0}.scm.{1}", _site, _dnsSuffix);
request.UserAgent = "CrossStampFunctional/0.0.0.0";
return request;
}
static bool RunAndValidate(string expected, string exe, string format, params object[] args)
{
return RunAndValidate(expected, exe, 60, format, args);
}
static bool RunAndValidate(string expected, string exe, int numRetries, string format, params object[] args)
{
Console.WriteLine();
Console.WriteLine("Expected: {0}", expected);
var notContains = expected.StartsWith("!");
if (notContains)
{
expected = expected.Substring(1);
}
for (int i = 0; i < numRetries; ++i)
{
Console.WriteLine(DateTime.Now.ToString("o"));
var output = Run(exe, format, args);
if (notContains)
{
if (output.IndexOf(expected, StringComparison.OrdinalIgnoreCase) < 0)
{
Console.WriteLine("Passed.");
return true;
}
}
else if (output.IndexOf(expected, StringComparison.OrdinalIgnoreCase) >= 0)
{
Console.WriteLine("Passed.");
return true;
}
if (notContains)
{
Console.WriteLine("Must NOT contains " + expected);
}
else
{
Console.WriteLine("Must contains " + expected);
}
if ((i + 1) >= numRetries)
{
Console.WriteLine(output);
break;
}
Thread.Sleep(1000);
}
throw new InvalidOperationException("Command did not return expected result!");
}
static string Run(string exe, string format, params object[] args)
{
Console.WriteLine("Run: {0} {1}", exe, String.Format(format, args));
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = exe,
Arguments = String.Format(format, args),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
var output = new StringBuilder();
while (!proc.StandardOutput.EndOfStream)
{
var line = proc.StandardOutput.ReadLine();
//Console.WriteLine(line);
output.AppendLine(line);
}
proc.WaitForExit();
Console.WriteLine("ExitCode: {0}", proc.ExitCode);
return output.ToString();
}
static void HttpGet(Uri uri, string host, HttpStatusCode expected, string userName = null, string password = null, string expectedContent = null)
{
for (int i = 0; i < 60; ++i)
{
var requestId = Guid.Empty.ToString().Replace("00000000-", Interlocked.Increment(ref _requestId) + "-");
Console.WriteLine(DateTime.Now.ToString("o"));
Console.WriteLine("HttpGet: {0}", uri);
Console.WriteLine("Host: {0}", host);
Console.WriteLine("x-ms-request-id: {0}", requestId);
using (var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }))
{
if (host != null)
{
client.DefaultRequestHeaders.Host = host;
}
client.DefaultRequestHeaders.Add("x-ms-request-id", requestId);
if (userName != null && password != null)
{
var byteArray = Encoding.ASCII.GetBytes(String.Format("{0}:{1}", userName, password));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("CrossStampFunctional", "1.0.0.0")));
try
{
var now = DateTime.UtcNow;
using (var response = client.GetAsync(uri).Result)
{
Console.WriteLine("Latency: {0} ms", (int)(DateTime.UtcNow - now).TotalMilliseconds);
if (response.StatusCode == expected && IsResponseContentMatch(expectedContent, response))
{
Console.WriteLine("HttpStatus: {0} == {1}", response.StatusCode, expected);
Console.WriteLine("Passed.");
Console.WriteLine();
return;
}
if (response.StatusCode != expected)
{
Console.WriteLine("HttpStatus: {0} != {1}", response.StatusCode, expected);
}
else
{
Console.WriteLine("Content Not Match: {0}", expectedContent);
}
IEnumerable<string> poweredBys;
if (response.Headers.TryGetValues("X-Powered-By", out poweredBys))
{
Console.WriteLine("X-Powered-By: {0}", string.Join("; ", poweredBys));
}
else
{
Console.WriteLine("No X-Powered-By header!");
}
Console.WriteLine();
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex);
Console.WriteLine();
}
}
Thread.Sleep(5000);
}
throw new InvalidOperationException("Command did not return expected result!");
}
static bool IsResponseContentMatch(string expected, HttpResponseMessage response)
{
if (String.IsNullOrEmpty(expected))
{
return true;
}
var negate = expected.StartsWith("!");
if (negate)
{
expected = expected.TrimStart('!');
}
var actual = response.Content.ReadAsStringAsync().Result;
if (negate)
{
return actual.IndexOf(expected, StringComparison.OrdinalIgnoreCase) < 0;
}
else
{
return actual.IndexOf(expected, StringComparison.OrdinalIgnoreCase) >= 0;
}
}
}
} | 336d3b140ba2a63a26b5c7ca7204d44aa6d82bd3 | [
"C#"
] | 1 | C# | suwatch/CrossStampFunctional | f26fb40045f76ee994385973226696000ac3f682 | 8fc22dd524c928b61f6ffbf0d614b8dad5a9fccc |
refs/heads/main | <repo_name>tnaswin/arabic-to-roman<file_sep>/README.md
# Arabic-to-Roman conversion
A function which turns an Arabic number into a Roman numeral in its minimal form using the "standard" subtractive notation as described on Wikipedia <http://en.wikipedia.org/wiki/Roman_numerals#Reading_Roman_numerals>.
## To execute this script
Clone this repository and run the below command from your terminal:
```sh
python3 convert.py
```
---
### Technologies
Script is written using:
* Python version: 3.8.5
<file_sep>/convert.py
"""
Converting Arabic number into a Roman numeral in its minimal form
using the "standard" subtractive notation.
Example:
The numerals for 4 (IV) and 9 (IX) are written using "subtractive notation",
where the first symbol (I) is subtracted from the larger one (V, or X),
thus avoiding the clumsier (IIII, and VIIII).
The largest number that can be displayed in this notation is 3999 (MMMCMXCIX).
Returns: Roman numeral
Return type: string
"""
def convert_to_roman(arabic_number):
arabic_roman_map = [
(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')
]
roman_numeral = ''
for arabic, roman in arabic_roman_map:
while arabic_number >= arabic:
roman_numeral += roman
arabic_number -= arabic
return roman_numeral
print(" Arabic number to Roman numeral Conversion.\n")
while True:
try:
arabic_number = int(
input(" Enter a positive integer less than or equal to 3999: ")
)
except ValueError:
print("\n Provide an integer value")
continue
if 0 < arabic_number < 4000:
break
else:
print("\n Please enter a valid input ...")
roman_numeral = convert_to_roman(arabic_number)
print(f"\n Arabic Number= {arabic_number}, Roman Numeral= {roman_numeral}\n")
| 4703cbc0c8b3b95c38046466ef14fd53d8ba1c62 | [
"Markdown",
"Python"
] | 2 | Markdown | tnaswin/arabic-to-roman | c3d621b87039b3ba0574ba770cc19b6bc6ac4ac5 | b688589a65855583180245020646f41c2be8976b |
refs/heads/master | <file_sep>#include "ros/ros.h"
#include "std_msgs/Empty.h"
#include "geometry_msgs/Twist.h"
#include "ardrone_autonomy/Navdata.h"
#include "sensor_msgs/Imu.h"
#include <sstream>
#include <iostream>
#include <math.h>
#include <string>
ardrone_autonomy::Navdata msg_in;
geometry_msgs::Twist msgpos_in;
sensor_msgs::Imu msgyaw_in;
void read_navdata(const ardrone_autonomy::Navdata::ConstPtr& msg)
{
msg_in.altd = msg->altd;
}
void read_yaw(const sensor_msgs::Imu::ConstPtr& msgyaw)
{
msgyaw_in.orientation.x = msgyaw->orientation.x;
msgyaw_in.orientation.y = msgyaw->orientation.y;
msgyaw_in.orientation.z = msgyaw->orientation.z;
msgyaw_in.orientation.w = msgyaw->orientation.w;
}
void read_pos(const geometry_msgs::Twist::ConstPtr& msgpos)//subscriber for position
{
msgpos_in.linear.x = msgpos->linear.x;
msgpos_in.linear.y = msgpos->linear.y;
msgpos_in.linear.z = msgpos->linear.z;
msgpos_in.angular.z = msgpos->angular.z;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "pid");
ros::NodeHandle n;
std_msgs::Empty my_msg;
geometry_msgs::Twist m;
ros::Publisher takeoff = n.advertise<std_msgs::Empty>("/ardrone/takeoff", 10,true);
takeoff.publish(my_msg);
ros::Publisher twist;
twist = n.advertise<geometry_msgs::Twist>("/cmd_vel", 1);
ros::Subscriber read = n.subscribe("/ardrone/navdata", 1000, read_navdata);
ros::Subscriber readyaw = n.subscribe("/ardrone/Imu", 1000, read_yaw);
ros::Subscriber readpos = n.subscribe("destination/pose",1000, read_pos);
int c;
for(c=0;c<10;c++)
c++;
ros::Rate loop_rate(10);
m.linear.z = 0;
m.linear.y = 0;
m.angular.x = 0;
m.angular.y = 0;
m.angular.z = 0;
m.linear.x = 0;
float z1,y1,x1,yy1;
//altitude + yaw
float z = msgpos_in.linear.z;
float y=msgpos_in.angular.z;
z1 = msg_in.altd;
//don't use this conversion use library for conversion
y1 = asin(2*msgyaw_in.orientation.x*msgyaw_in.orientation.y + 2*msgyaw_in.orientation.z*msgyaw_in.orientation.w); //don't use this conversion use library for conversion
// x and yy
x1 = msgpos_in.linear.x;
yy1 = msgpos_in.linear.y;
//altitude + yaw
float error,pre_error,integral,derivative,errory,pre_errory,integraly,derivativey;
integral =0;
integraly = 0;
pre_errory = 0;
//x and yy
float errorx,pre_errorx,integralx,derivativex,erroryy,pre_erroryy,integralyy,derivativeyy;
integralx = 0;
integralyy = 0;
pre_errorx = 0;
pre_erroryy = 0;
float kp,ki,kd,kpy,kiy,kdy,kpx,kix,kdx,kpyy,kiyy,kdyy;
if(argc > 1)
{
kp = std::atof(argv[1]);
kd = std::atof(argv[2]);
ki = std::atof(argv[3]);
kpy = std::atof(argv[4]);
kdy = std::atof(argv[5]);
kiy = std::atof(argv[6]);
kpx = std::atof(argv[7]);
kdx = std::atof(argv[8]);
kix = std::atof(argv[9]);
kpyy = std::atof(argv[10]);
kdyy = std::atof(argv[11]);
kiyy = std::atof(argv[12]);
}
else
{
kp = 0.11;
ki = 0.0000081;
kd = 2.0;
kpy = 0.03;
kdy = 0.1;
kiy = 0;
kpx = 0.11;
kix = 0.0000081;
kdx = 2;
kpyy = 0.11;
kiyy = 0.0000081;
kdyy = 2;
}
std::cout<<"Kp: "<<kp<<" Kd: "<<kd<<" Ki: "<<ki<<std::endl;
std::cout<<"Kpy: "<<kpy<<" Kdy: "<<kdy<<" Kiy: "<<kiy<<std::endl;
int region = 1;
int regiony=1;
while (ros::ok())
{ //altitude + yaw
if(abs(error) >500)
region = 1;
else if ((abs(error) < 500) && (abs(error) > 100))
region = 5;
else
region = 10;
if(abs(errory) >500)
regiony = 1;
else if ((abs(errory) < 500) && (abs(errory) > 100))
regiony = 5;
else
regiony = 10;
if(errory>=0)
{
if(errory>=180)
errory = 360 - errory;
}
else if(errory<0)
{
errory = (360 + errory)*(-1);
}
// x and yy
/* if(abs(error) >500)
region = 1;
else if ((abs(error) < 500) && (abs(error) > 100))
region = 5;
else
region = 10;*/
//altitude + yaw
errory = (y - y1)/70;
integraly = integraly + errory;
derivativey = errory-pre_errory;
error = (z - z1)/70;
integral = integral + error;
derivative = error-pre_error;
//x and yy
errorx =(msgpos_in.linear.x)/70;
integralx = integralx + errorx;
derivativex = errorx - pre_errorx;
erroryy =(msgpos_in.linear.y)/70;
integralyy = integralyy + erroryy;
derivativeyy = erroryy - pre_erroryy;
if(abs(error)>0.01)
{
//altitude + yaw
m.linear.z = kp*error + kd*derivative/region + ki*integral*region;
}
else
m.linear.z = 0;
if(abs(errory)>0.1)
{
m.angular.z = kpy*errory + kdy*derivativey/regiony + kiy*integraly*regiony;
}
else
m.angular.z = 0;
if(abs(errorx)>0.01)
{
//x and yy
m.linear.x = kpx*errorx + kdx*derivativex + kix*integralx;
}
else
m.linear.x = 0;
if(abs(erroryy)>0.01)
{
m.linear.y = kpyy*erroryy + kdyy*derivativeyy + kiyy*integralyy;
}
else
{
m.linear.y = 0;
}
ROS_INFO("%.2f %.2f %.2f %.2f %.2f %.2f %.2f", msg_in.rotZ, errory, integraly, derivativey, m.angular.z,y,y1);
twist.publish(m);
//altitude + yaw
pre_error = error;
z1 = msg_in.altd;
pre_errory = errory;
//don't use this conversion use library
y1 = asin(2*msgyaw_in.orientation.x*msgyaw_in.orientation.y + 2*msgyaw_in.orientation.z*msgyaw_in.orientation.w); //don't use this conversion use library
//x and yy
pre_errorx = errorx;
pre_erroryy = erroryy;
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<file_sep>#include "ros/ros.h"
#include "std_msgs/Empty.h"
#include "geometry_msgs/Twist.h"
#include "ardrone_autonomy/Navdata.h"
#include "sensor_msgs/Imu.h"
#include <sstream>
#include <iostream>
#include <math.h>
#include <string>
#include <eigen3/Eigen/Geometry>
ardrone_autonomy::Navdata msg_in;
geometry_msgs::Twist msgpos_in;
sensor_msgs::Imu msgyaw_in;
Eigen::Quaterniond quat_orientation;
#define PI 3.14149265
double yaw,pitch,roll;
void read_navdata(const ardrone_autonomy::Navdata::ConstPtr& msg)
{
msg_in.altd = msg->altd;
}
struct Quaternionm
{
double w, x, y, z;
};
void GetEulerAngles(Quaternionm q, double& yaw, double& pitch, double& roll)
{
const double w2 = q.w*q.w;
const double x2 = q.x*q.x;
const double y2 = q.y*q.y;
const double z2 = q.z*q.z;
const double unitLength = w2 + x2 + y2 + z2; // Normalised == 1, otherwise correction divisor.
const double abcd = q.w*q.x + q.y*q.z;
const double eps = 1e-7; // TODO: pick from your math lib instead of hardcoding.
const double pi = 3.14159265358979323846; // TODO: pick from your math lib instead of hardcoding.
if (abcd > (0.5-eps)*unitLength)
{
yaw = 2 * atan2(q.y, q.w);
pitch = pi;
roll = 0;
}
else if (abcd < (-0.5+eps)*unitLength)
{
yaw = -2 * ::atan2(q.y, q.w);
pitch = -pi;
roll = 0;
}
else
{
const double adbc = q.w*q.z - q.x*q.y;
const double acbd = q.w*q.y - q.x*q.z;
yaw = ::atan2(2*adbc, 1 - 2*(z2+x2));
pitch = ::asin(2*abcd/unitLength);
roll = ::atan2(2*acbd, 1 - 2*(y2+x2));
}
}
void read_yaw(const sensor_msgs::Imu::ConstPtr& msgyaw)
{
msgyaw_in.orientation.x = msgyaw->orientation.x;
msgyaw_in.orientation.y = msgyaw->orientation.y;
msgyaw_in.orientation.z = msgyaw->orientation.z;
msgyaw_in.orientation.w = msgyaw->orientation.w;
Quaternionm myq;
myq.x = msgyaw->orientation.x;
myq.y = msgyaw->orientation.y;
myq.z = msgyaw->orientation.z;
myq.w = msgyaw->orientation.w;
GetEulerAngles(myq, yaw, pitch, roll);
//ROS_INFO("Angles %lf %lf %lf",yaw,pitch,roll);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "altipid");
ros::NodeHandle n;
std_msgs::Empty my_msg;
geometry_msgs::Twist m;
ros::Publisher takeoff = n.advertise<std_msgs::Empty>("/ardrone/takeoff", 10,true);
takeoff.publish(my_msg);
ros::Publisher twist;
twist = n.advertise<geometry_msgs::Twist>("/cmd_vel", 1);
ros::Subscriber read = n.subscribe("/ardrone/navdata", 1000, read_navdata);
ros::Subscriber readyaw = n.subscribe("/ardrone/imu", 1000, read_yaw);
int c;
for(c=0;c<10;c++)
c++;
ros::Rate loop_rate(10);
m.linear.z = 0.0;
m.linear.y = 0.0;
m.angular.x = 0.0;
m.angular.y = 0.0;
m.angular.z = 0.0;
m.linear.x = 0.0;
double z1,y1;
double z = 1000.0;
double y =45.0;
z1 = msg_in.altd;
//don't use this conversion use library for conversion
y1 = yaw*180/PI;
double error,pre_error,integral,derivative,errory,pre_errory,integraly,derivativey;
integral =0;
integraly = 0;
pre_error = 0;
pre_errory = 0;
double kp,ki,kd,kpy,kiy,kdy;
if(argc > 1)
{
kp = std::atof(argv[1]);
kd = std::atof(argv[2]);
ki = std::atof(argv[3]);
kpy = std::atof(argv[4]);
kdy = std::atof(argv[5]);
kiy = std::atof(argv[6]);
}
else
{
kp = 0.11;
ki = 0.0000081;
kd = 2.0;
kpy = 0.003;
kdy = 0.1;
kiy = 0.0;
}
std::cout<<"Kp: "<<kp<<" Kd: "<<kd<<" Ki: "<<ki<<std::endl;
std::cout<<"Kpy: "<<kpy<<" Kdy: "<<kdy<<" Kiy: "<<kiy<<std::endl;
int region = 1;
int regiony=1;
while (ros::ok())
{ //altitude + yaw
if(abs(error) >500)
region = 1;
else if ((abs(error) < 500) && (abs(error) > 100))
region = 5;
else
region = 10;
if(abs(errory) >500)
regiony = 1;
else if ((abs(errory) < 500) && (abs(errory) > 100))
regiony = 5;
else
regiony = 10;
errory = (y - y1);
integraly = integraly + errory;
derivativey = errory-pre_errory;
if(errory>=0.0)
{
if(errory>=180.0)
errory = 360 - errory;
}
else if(errory<0.0)
{
if(errory<=-180)
errory = 360 + errory;
}
error = (z - z1)/70.0;
integral = integral + error;
derivative = error-pre_error;
if(abs(error)>0.01)
{
//altitude + yaw
m.linear.z = kp*error + kd*derivative/region + ki*integral*region;
}
else
m.linear.z = 0;
if(abs(errory)>0.00001)
{
m.angular.z = kpy*errory + kdy*derivativey/regiony + kiy*integraly*regiony;
}
else
m.angular.z = 0;
twist.publish(m);
ROS_INFO("%lf %lf %lf %lf %lf %lf",z1,error,m.linear.z,y1,errory,m.angular.z);
pre_error = error;
z1 = msg_in.altd;
pre_errory = errory;
//don't use this conversion use library
y1 = yaw*180/PI;
ros::spinOnce();
loop_rate.sleep();
}
}
| 60d878644b72ab27e9d17f0381656bf4416cc9db | [
"C++"
] | 2 | C++ | ManashRaja/grid_localization | 675e0fca6d37f4d92d360aecb9a7d646ebac3354 | b8d858d7ec21aae5c28213c923cc553128d1bde4 |
refs/heads/master | <file_sep># Generated by mlNewProject at Wed Mar 27 21:08:33 PHT 2019<file_sep><?php
namespace App;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Client;
use App\FeedbackModel;
class AppService
{
private function getServerUrl() {
$ml_host = config('app.ml_host');
$ml_port = config('app.ml_port');
return $ml_host . ':' . $ml_port . '/';
}
private function getRestUrl($extension_name) {
return $this->getServerUrl() . 'v1/resources/' . $extension_name;
}
private function getAuth() {
$ml_username = config('app.ml_username');
$ml_password = config('app.ml_password');
return [ $ml_username, $ml_password, '<PASSWORD>' ];
}
private function handleException(RequestException $e) {
// properly handle error here
echo $e->getResponse()->getBody();
}
public function submitFeedback(FeedbackModel $model) {
try {
$client = new Client();
$response = $client->put($this->getRestUrl('feedback'), [
'auth' => $this->getAuth(),
'json' => $model->getAttributes()
]);
return $response->getStatusCode() == 201;
}
catch(RequestException $e) {
$this->handleException($e);
}
}
public function getExpenseTypes() {
try {
$client = new Client();
$response = $client->get($this->getRestUrl('expenseTypes'), [
'auth' => $this->getAuth()
]);
$jsonDoc = json_decode($response->getBody(), true);
return $jsonDoc["expenseTypes"];
}
catch(RequestException $e) {
$this->handleException($e);
}
}
public function addExpense(ExpenseModel $model) {
try {
$client = new Client();
$response = $client->put($this->getRestUrl('expense'), [
'auth' => $this->getAuth(),
'json' => $model->getAttributes()
]);
$jsonResponse = json_decode($response->getBody(), true);
return $jsonResponse["expenseId"];
}
catch(RequestException $e) {
$this->handleException($e);
}
}
public function addExpenseReceipt($expenseId, $file) {
try {
$filename = time() . '.' . $file->extension();
$uri = '/expense/' . $expenseId . '/' . $filename;
$client = new Client();
$response = $client->put($this->getServerUrl() . 'v1/documents', [
'auth' => $this->getAuth(),
'query' => [
'uri' => $uri,
'collection' => 'expenseReceipt'
],
'headers' => [
'Content-type' => $file->getMimeType()
],
'body' => fopen($file->path(), 'r')
]);
return $response->getStatusCode() == 201;
}
catch(RequestException $e) {
$this->handleException($e);
}
}
public function searchExpenses($qtext) {
try {
$client = new Client();
$response = $client->get($this->getRestUrl('expense'), [
'auth' => $this->getAuth(),
'query' => [
'rs:qtext' => $qtext
]
]);
$jsonResponse = json_decode($response->getBody(), true);
$jsonResponse['results'] = $jsonResponse['results'] == null ? [] : $jsonResponse['results'];
return $jsonResponse;
}
catch(RequestException $e) {
$this->handleException($e);
}
}
public function approveExpense($expenseId) {
try {
$client = new Client();
$response = $client->put($this->getRestUrl('expenseApprove'), [
'auth' => $this->getAuth(),
'query' => [
'rs:expenseId' => $expenseId
]
]);
return $response->getStatusCode() == 204;
}
catch(RequestException $e) {
$this->handleException($e);
}
}
public function rejectExpense($expenseId) {
try {
$client = new Client();
$response = $client->put($this->getRestUrl('expenseReject'), [
'auth' => $this->getAuth(),
'query' => [
'rs:expenseId' => $expenseId
]
]);
return $response->getStatusCode() == 204;
}
catch(RequestException $e) {
$this->handleException($e);
}
}
public function getExpenseReceipt($expenseId) {
try {
$client = new Client();
$response = $client->get($this->getRestUrl('expenseReceipt'), [
'auth' => $this->getAuth(),
'query' => [
'rs:expenseId' => $expenseId
]
]);
return [
'content-type' => $response->getHeader('Content-Type'),
'content' => $response->getBody()
];
}
catch(RequestException $e) {
$this->handleException($e);
}
}
}
<file_sep># Generated by mlNewProject at Wed Mar 27 21:08:33 PHT 2019
# Please be sure to ignore this file in version control!<file_sep><?php
namespace App;
use Illuminate\Http\Request;
class ExpenseModel
{
private $attributes = [];
public function fromRequest(Request $request) {
$this->attributes = [
'expenseType' => $request->input('expenseType'),
'reimbursable' => $request->input('reimbursable'),
'name' => $request->input('name'),
'reason' => $request->input('reason'),
];
}
public function getAttributes() {
return $this->attributes;
}
}
<file_sep><?php
namespace App;
use Illuminate\Http\Request;
class FeedbackModel
{
private $attributes = [];
public function fromRequest(Request $request) {
$this->attributes = [
'category' => $request->input('category'),
'feedback' => $request->input('feedback'),
'email' => $request->input('email'),
'anonymous' => $request->input('anonymous') == 'on' ? true : false,
];
}
public function getAttributes() {
return $this->attributes;
}
}
<file_sep>'use strict';
function get(context, params) {
// return static document
return cts.doc("/settings/expenseTypes.json");
}
exports.GET = get;<file_sep>'use strict';
var jsearch = require('/MarkLogic/jsearch.sjs');
function get(context, params) {
var qtext = params.qtext || null;
var query = [ cts.collectionQuery('expense') ];
if (qtext) {
query.push(cts.wordQuery(qtext));
}
return jsearch.documents()
.where(query)
.map(function(item) {
// the results of jsearch can be verbose, so we'll edit the results
return {
uri: item.uri,
expenseId: item.document.envelope.headers.expenseId,
expense: item.document.envelope.content.expense
};
})
.result();
}
function put(context, params, input) {
// the JSON payload
var source = input.toObject();
var timestamp = fn.currentDateTime();
var expenseId = sem.uuidString();
// construct document
var doc = {
"envelope": {
// internal metadata
"headers": {
"expenseId": expenseId,
"createdOn": timestamp // save timestamp "as-is" so it can be indexed
},
// the canonical or preferred structure of the data
"content": {
"expense": {
"type": source.expenseType || null,
"reimbursable": source.reimbursable === 'yes',
"reason": source.reason || null,
"submittedBy": source.name,
"submittedOn": timestamp.toObject(), // save timestamp as something JS can parse
"status": "Open"
}
},
// save a "raw" copy of the input
"source": source
}
};
// add to database
xdmp.documentInsert("/expense/" + expenseId + ".json", doc, {
collections: ["expense"]
});
// return response
context.outputStatus = [201, "Created"];
return {
"expenseId": expenseId
};
}
exports.GET = get;
exports.PUT = put;<file_sep># Sample Forms App
A sample project showing how to build a simple form data entry and processing application using PHP and MarkLogic.
## Requirements
- [PHP 7.2](https://www.php.net/manual/en/install.php)
- [Composer](https://getcomposer.org/doc/00-intro.md)
- [Laravel 5.8](https://laravel.com/docs/5.8/installation)
- Latest version of [MarkLogic 9](https://developer.marklogic.com/products)
## Project Setup
This project was created using the following steps:
### Setup Project Directory
Use Laravel to scaffold a new project.
1. Open a terminal.
2. Create a new Laravel project by running the command `laravel new ml-php-sampleforms`. This will create a new directory named *ml-php-sampleforms*.
### Setup Gradle
Setup Gradle for automating our MarkLogic configuration and deployment. These steps are similar to those specified [here](https://github.com/marklogic-community/ml-gradle).
1. Change directory to `ml-php-sampleforms`.
2. Create a new file named `build.gradle`.
3. Open `build.gradle` in a text editor and enter the following line:
```gradle
plugins { id "com.marklogic.ml-gradle" version "3.13.0" }
```
4. Run `gradle mlNewProject`.
5. Gradle will prompt for an *Application name*, which will be used as a basis for database names and other parts of the database configuration. Enter *ml-php-sampleforms*.
6. You will be prompted next for *host*; press ENTER to use the default (localhost).
7. Next will be admin username and password; use the defaults (admin).
8. Next will be the *REST API port*. Enter any port number not currently in use. In this instance, the project uses port 9020.
9. Next will be the *Test REST API port*. Leave this blank for the meantime.
10. Next will be support for multiple environments. Enter `y`.
11. Next will be for generating resource files. Enter `y`.
### Verify/Test
1. Open a terminal and run `php artisan serve`.
2. Open a browser and navigate to the development server (usually `http://127.0.0.1:8000`).
3. If successful, a default Laravel web page should be displayed.
4. Run `gradle mlDeploy`.
5. Navigate to `http://localhost:8001` to open the MarkLogic admin page.
6. If deployment was successful, we should see the `ml-php-sampleforms` under *App Servers*.
### Initial Coding
1. Run `php artisan make:auth` for authentication scaffolding. Best to do this early as it modifies code, even if there are no plans to configure authentication yet.
2. To prepare the project for source control (Git), open `.gitignore` file and add a line for `.gradle` and `build`.
3. Add [Guzzle](http://docs.guzzlephp.org/en/stable/overview.html) for PHP using composer by modifying `composer.json` as described [here](http://docs.guzzlephp.org/en/stable/overview.html#installation).<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\AppService;
class ExpenseAdminController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function index(Request $request)
{
$qtext = $request->input('qtext');
$qtext = $qtext == null ? '' : $qtext;
$service = new AppService();
$search = $service->searchExpenses($qtext);
return view('expense.admin')->with('search', $search);
}
public function receipt($expenseId) {
$service = new AppService();
$result = $service->getExpenseReceipt($expenseId);
return response($result['content'])
->header('Content-Type', $result['content-type']);
}
public function approve(Request $request) {
$expenseId = $request->query('expenseId');
$service = new AppService();
$success = $service->approveExpense($expenseId);
if ($success) {
return redirect()->action('ExpenseAdminController@index');
}
else {
return redirect()->view('oops');
}
}
public function reject(Request $request) {
$expenseId = $request->query('expenseId');
$service = new AppService();
$success = $service->rejectExpense($expenseId);
if ($success) {
return redirect()->action('ExpenseAdminController@index');
}
else {
return redirect()->view('oops');
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\AppService;
use App\FeedbackModel;
class FeedbackController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function index()
{
return view('feedback');
}
public function done()
{
return view('feedback-done');
}
public function submit(Request $request)
{
$model = new FeedbackModel();
$model->fromRequest($request);
// validate content
// save to db
$service = new AppService();
$success = $service->submitFeedback($model);
if ($success) {
return redirect()->action('FeedbackController@done');
}
else {
return redirect()->view('oops');
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\AppService;
use App\ExpenseModel;
class ExpenseController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function getStep1()
{
$service = new AppService();
$expenseTypes = $service->getExpenseTypes();
return view('expense.step1')->with('expenseTypes', $expenseTypes);
}
public function getStep2(Request $request)
{
$expenseId = $request->session()->get('expenseId');
return view('expense.step2')->with('expenseId', $expenseId);
}
public function done()
{
return view('expense.done');
}
public function postStep1(Request $request)
{
$validatedData = $request->validate([
'expenseType' => 'required',
'reimbursable' => 'required',
'name' => 'required',
'reason' => 'required',
]);
$model = new ExpenseModel();
$model->fromRequest($request);
// save to db
$service = new AppService();
$expenseId = $service->addExpense($model);
if ($expenseId) {
return redirect()->action('ExpenseController@getStep2')->with('expenseId', $expenseId);
}
else {
return redirect()->view('oops');
}
}
public function postStep2(Request $request)
{
$expenseId = $request->input('expenseId');
$fileToUpload = $request->file('fileToUpload');
// save to db
$service = new AppService();
$success = $service->addExpenseReceipt($expenseId, $fileToUpload);
if ($success) {
return redirect()->action('ExpenseController@done');
}
else {
return redirect()->view('oops');
}
}
}
<file_sep>plugins { id "com.marklogic.ml-gradle" version "3.12.0" }<file_sep>'use strict';
function get(context, params) {
var expenseId = params.expenseId || null;
if (!expenseId) {
context.outputStatus = [400, "Bad Request"];
}
var directory = '/expense/' + expenseId + '/';
return fn.head(xdmp.directory(directory));
}
exports.GET = get;<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/feedback', 'FeedbackController@index')->name('feedback')->middleware('guest');
Route::post('/feedback', 'FeedbackController@submit');
Route::get('/feedback-done', 'FeedbackController@done')->name('feedback-done')->middleware('guest');
Route::get('/expense/step1', 'ExpenseController@getStep1')->name('postExpense')->middleware('guest');
Route::post('/expense/step1', 'ExpenseController@postStep1')->middleware('guest');
Route::get('/expense/step2', 'ExpenseController@getStep2')->middleware('guest');
Route::post('/expense/step2', 'ExpenseController@postStep2')->middleware('guest');
Route::get('/expense/done', 'ExpenseController@done')->middleware('guest');
Route::get('/expense/admin', 'ExpenseAdminController@index')->name('expense-admin');
Route::post('/expense/approve', 'ExpenseAdminController@approve');
Route::post('/expense/reject', 'ExpenseAdminController@reject');
Route::get('/expense/receipt/{expenseId}', 'ExpenseAdminController@receipt');
| e4b2779f23e75223538f7cb987ccceacfaa70896 | [
"JavaScript",
"Markdown",
"INI",
"Gradle",
"PHP"
] | 14 | INI | mfgumban/ml-php-sampleforms | 83c2f0ae8bf37be99f9737b5fa8759ecdb417ad0 | e88cdf66f452eebc561c83b693b6a28bbf3649ae |
refs/heads/master | <repo_name>rsnyder49/sessions_controller_lab-v-000<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
def logged_in?
session[:username]
end
end
| 56bf2cfe315e9aeebf96f18554814ac2f4db3f8a | [
"Ruby"
] | 1 | Ruby | rsnyder49/sessions_controller_lab-v-000 | 6abf952e95aa0072f840a924dd92968faa1df1ed | 5ef02993be56bcb7c53b51086ddd4ca606418bde |
refs/heads/master | <file_sep><?php
class Contact
{
private $personName;
private $phoneNumber;
private $address;
// Contact constructor
function __construct($personName, $phoneNumber, $address)
{
$this->personName = $personName;
$this->phoneNumber = $phoneNumber;
$this->address = $address;
}
// personName Getter and Setter
function getPersonName()
{
return $this->personName;
}
function setPersonName($new_personName)
{
$this->personName = (string) $new_personName;
}
// phoneNumber Getter and Setter
function getPhoneNumber()
{
return $this->phoneNumber;
}
function setPhoneNumber($new_phoneNumber)
{
$this->phoneNumber = (string) $new_phoneNumber;
}
// address Getter and Setter
function getAddress()
{
return $this->address;
}
function setAddress($new_address)
{
$this->address = (string) $new_address;
}
// METHODS
function save()
{
array_push($_SESSION['list_of_contacts'], $this);
}
static function getAll()
{
return $_SESSION['list_of_contacts'];
}
static function deleteAll()
{
$_SESSION['list_of_contacts'] = array();
}
}
?>
<file_sep># _Address Book Webpage_
#### _A webpage that acts as an address book, 10 February 2017_
#### By _**<NAME>**_
## To see the site live, click the link below:
[Live Address Book](https://php-address-book.herokuapp.com/)
## Description
_A webpage that allows a user to enter a contact including a person's name, phone number and address. It also allows a user to save a contact, view contacts list, and delete the list._
## Setup/Installation Requirements
* In terminal run the following commands to setup the database:
1. _Fork and clone this repository from_ [gitHub](https://github.com/michaela-davis/php_address-book.git).
2. Navigate to the root directory of the project in which ever CLI shell you are using and run the command: `composer install`.
3. Create a local server in the /web directory within the project folder using the command: `php -S localhost:8000` (assuming you are using a mac).
4. Open the directory http://localhost:8000/ in any standard web browser.
## Known Bugs
_None so far._
## Support and contact details
_Please contact <EMAIL> with concerns or comments._
## Technologies Used
* _HTML_
* _CSS_
* _PHP_
* _Silex_
* _Twig_
* _Composer_
### License
*MIT license*
Copyright (c) 2017 **_<NAME>_**
| 66712c1be23eb24bb74d5b35c833e50cf270bece | [
"Markdown",
"PHP"
] | 2 | PHP | Michaela-Davis/php_address-book | deb79af8d5eda45f85f56a81b713136619383c78 | bf923c5aef4142f3666f480291dbffbcf0bd9b1e |
refs/heads/main | <file_sep># Swagger\Client\PeriodicoApi
All URIs are relative to *https://dc.directchannel.it/ApiRest*
Method | HTTP request | Description
------------- | ------------- | -------------
[**periodicoCallPeriodico**](PeriodicoApi.md#periodicoCallPeriodico) | **POST** /v1/api/Periodico/CallPeriodico |
[**periodicoGet**](PeriodicoApi.md#periodicoGet) | **GET** /v1/api/Periodico/Get |
[**periodicoInsertPeriodici**](PeriodicoApi.md#periodicoInsertPeriodici) | **POST** /v1/api/Periodico/InsertPeriodici |
[**periodicoUpdateAttivita**](PeriodicoApi.md#periodicoUpdateAttivita) | **POST** /v1/api/Periodico/UpdateAttivita |
# **periodicoCallPeriodico**
> object periodicoCallPeriodico($raw_string, $ambiente)
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new Swagger\Client\Api\PeriodicoApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$raw_string = new \Swagger\Client\Model\CallRegolare(); // \Swagger\Client\Model\CallRegolare |
$ambiente = "ambiente_example"; // string |
try {
$result = $apiInstance->periodicoCallPeriodico($raw_string, $ambiente);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling PeriodicoApi->periodicoCallPeriodico: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**raw_string** | [**\Swagger\Client\Model\CallRegolare**](../Model/CallRegolare.md)| |
**ambiente** | **string**| | [optional]
### Return type
**object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json, text/json, application/xml, text/xml, application/x-www-form-urlencoded
- **Accept**: application/json, text/json, application/xml, text/xml
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **periodicoGet**
> object periodicoGet($cl_codice)
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new Swagger\Client\Api\PeriodicoApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$cl_codice = "cl_codice_example"; // string |
try {
$result = $apiInstance->periodicoGet($cl_codice);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling PeriodicoApi->periodicoGet: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**cl_codice** | **string**| |
### Return type
**object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json, text/json, application/xml, text/xml
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **periodicoInsertPeriodici**
> object periodicoInsertPeriodici($raw_string, $ambiente)
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new Swagger\Client\Api\PeriodicoApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$raw_string = array(new \Swagger\Client\Model\Periodici()); // \Swagger\Client\Model\Periodici[] |
$ambiente = "ambiente_example"; // string |
try {
$result = $apiInstance->periodicoInsertPeriodici($raw_string, $ambiente);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling PeriodicoApi->periodicoInsertPeriodici: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**raw_string** | [**\Swagger\Client\Model\Periodici[]**](../Model/Periodici.md)| |
**ambiente** | **string**| | [optional]
### Return type
**object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json, text/json, application/xml, text/xml, application/x-www-form-urlencoded
- **Accept**: application/json, text/json, application/xml, text/xml
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **periodicoUpdateAttivita**
> object periodicoUpdateAttivita($raw_string, $ambiente)
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new Swagger\Client\Api\PeriodicoApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$raw_string = array(new \Swagger\Client\Model\Periodici()); // \Swagger\Client\Model\Periodici[] |
$ambiente = "ambiente_example"; // string |
try {
$result = $apiInstance->periodicoUpdateAttivita($raw_string, $ambiente);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling PeriodicoApi->periodicoUpdateAttivita: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**raw_string** | [**\Swagger\Client\Model\Periodici[]**](../Model/Periodici.md)| |
**ambiente** | **string**| | [optional]
### Return type
**object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json, text/json, application/xml, text/xml, application/x-www-form-urlencoded
- **Accept**: application/json, text/json, application/xml, text/xml
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
<file_sep><?php
/**
* AzioneTest
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace Swagger\Client;
/**
* AzioneTest Class Doc Comment
*
* @category Class
* @description Azione
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class AzioneTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "Azione"
*/
public function testAzione()
{
}
/**
* Test attribute "codice_cliente"
*/
public function testPropertyCodiceCliente()
{
}
/**
* Test attribute "campagna"
*/
public function testPropertyCampagna()
{
}
/**
* Test attribute "data_azione"
*/
public function testPropertyDataAzione()
{
}
/**
* Test attribute "note"
*/
public function testPropertyNote()
{
}
}
<file_sep><?php
/**
* Versamento
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace Swagger\Client\Model;
use \ArrayAccess;
use \Swagger\Client\ObjectSerializer;
/**
* Versamento Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class Versamento implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'Versamento';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'id_versamento' => 'int',
'id_regolare' => 'int',
'id_web' => 'string',
'codice_cliente' => 'string',
'codice_soggetto_versante' => 'string',
'codice_centro_ricavo' => 'string',
'codice_partner' => 'string',
'codice_riferimento' => 'string',
'campagna' => 'object',
'centro' => 'object',
'canale' => 'object',
'bambino' => 'object',
'progetto' => 'object',
'conto' => 'object',
'evento' => 'object',
'codice_transazione' => 'string',
'importo' => 'float',
'metodo' => 'string',
'descrizione_metodo' => 'string',
'data_operazione' => 'string',
'data_valuta' => 'string',
'note' => 'string',
'tipo' => 'object',
'sotto_tipo' => 'object',
'lotto' => 'string',
'escludi_attestato' => 'string',
'flag_one_off' => 'bool',
'prodotti' => '\Swagger\Client\Model\VersamentoProdotti[]'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'id_versamento' => 'int32',
'id_regolare' => 'int32',
'id_web' => null,
'codice_cliente' => null,
'codice_soggetto_versante' => null,
'codice_centro_ricavo' => null,
'codice_partner' => null,
'codice_riferimento' => null,
'campagna' => null,
'centro' => null,
'canale' => null,
'bambino' => null,
'progetto' => null,
'conto' => null,
'evento' => null,
'codice_transazione' => null,
'importo' => 'float',
'metodo' => null,
'descrizione_metodo' => null,
'data_operazione' => null,
'data_valuta' => null,
'note' => null,
'tipo' => null,
'sotto_tipo' => null,
'lotto' => null,
'escludi_attestato' => null,
'flag_one_off' => null,
'prodotti' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'id_versamento' => 'idVersamento',
'id_regolare' => 'idRegolare',
'id_web' => 'idWeb',
'codice_cliente' => 'CodiceCliente',
'codice_soggetto_versante' => 'CodiceSoggettoVersante',
'codice_centro_ricavo' => 'codiceCentroRicavo',
'codice_partner' => 'CodicePartner',
'codice_riferimento' => 'CodiceRiferimento',
'campagna' => 'Campagna',
'centro' => 'Centro',
'canale' => 'Canale',
'bambino' => 'Bambino',
'progetto' => 'Progetto',
'conto' => 'Conto',
'evento' => 'Evento',
'codice_transazione' => 'CodiceTransazione',
'importo' => 'Importo',
'metodo' => 'Metodo',
'descrizione_metodo' => 'DescrizioneMetodo',
'data_operazione' => 'DataOperazione',
'data_valuta' => 'DataValuta',
'note' => 'Note',
'tipo' => 'Tipo',
'sotto_tipo' => 'SottoTipo',
'lotto' => 'Lotto',
'escludi_attestato' => 'EscludiAttestato',
'flag_one_off' => 'flagOneOff',
'prodotti' => 'Prodotti'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'id_versamento' => 'setIdVersamento',
'id_regolare' => 'setIdRegolare',
'id_web' => 'setIdWeb',
'codice_cliente' => 'setCodiceCliente',
'codice_soggetto_versante' => 'setCodiceSoggettoVersante',
'codice_centro_ricavo' => 'setCodiceCentroRicavo',
'codice_partner' => 'setCodicePartner',
'codice_riferimento' => 'setCodiceRiferimento',
'campagna' => 'setCampagna',
'centro' => 'setCentro',
'canale' => 'setCanale',
'bambino' => 'setBambino',
'progetto' => 'setProgetto',
'conto' => 'setConto',
'evento' => 'setEvento',
'codice_transazione' => 'setCodiceTransazione',
'importo' => 'setImporto',
'metodo' => 'setMetodo',
'descrizione_metodo' => 'setDescrizioneMetodo',
'data_operazione' => 'setDataOperazione',
'data_valuta' => 'setDataValuta',
'note' => 'setNote',
'tipo' => 'setTipo',
'sotto_tipo' => 'setSottoTipo',
'lotto' => 'setLotto',
'escludi_attestato' => 'setEscludiAttestato',
'flag_one_off' => 'setFlagOneOff',
'prodotti' => 'setProdotti'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'id_versamento' => 'getIdVersamento',
'id_regolare' => 'getIdRegolare',
'id_web' => 'getIdWeb',
'codice_cliente' => 'getCodiceCliente',
'codice_soggetto_versante' => 'getCodiceSoggettoVersante',
'codice_centro_ricavo' => 'getCodiceCentroRicavo',
'codice_partner' => 'getCodicePartner',
'codice_riferimento' => 'getCodiceRiferimento',
'campagna' => 'getCampagna',
'centro' => 'getCentro',
'canale' => 'getCanale',
'bambino' => 'getBambino',
'progetto' => 'getProgetto',
'conto' => 'getConto',
'evento' => 'getEvento',
'codice_transazione' => 'getCodiceTransazione',
'importo' => 'getImporto',
'metodo' => 'getMetodo',
'descrizione_metodo' => 'getDescrizioneMetodo',
'data_operazione' => 'getDataOperazione',
'data_valuta' => 'getDataValuta',
'note' => 'getNote',
'tipo' => 'getTipo',
'sotto_tipo' => 'getSottoTipo',
'lotto' => 'getLotto',
'escludi_attestato' => 'getEscludiAttestato',
'flag_one_off' => 'getFlagOneOff',
'prodotti' => 'getProdotti'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['id_versamento'] = isset($data['id_versamento']) ? $data['id_versamento'] : null;
$this->container['id_regolare'] = isset($data['id_regolare']) ? $data['id_regolare'] : null;
$this->container['id_web'] = isset($data['id_web']) ? $data['id_web'] : null;
$this->container['codice_cliente'] = isset($data['codice_cliente']) ? $data['codice_cliente'] : null;
$this->container['codice_soggetto_versante'] = isset($data['codice_soggetto_versante']) ? $data['codice_soggetto_versante'] : null;
$this->container['codice_centro_ricavo'] = isset($data['codice_centro_ricavo']) ? $data['codice_centro_ricavo'] : null;
$this->container['codice_partner'] = isset($data['codice_partner']) ? $data['codice_partner'] : null;
$this->container['codice_riferimento'] = isset($data['codice_riferimento']) ? $data['codice_riferimento'] : null;
$this->container['campagna'] = isset($data['campagna']) ? $data['campagna'] : null;
$this->container['centro'] = isset($data['centro']) ? $data['centro'] : null;
$this->container['canale'] = isset($data['canale']) ? $data['canale'] : null;
$this->container['bambino'] = isset($data['bambino']) ? $data['bambino'] : null;
$this->container['progetto'] = isset($data['progetto']) ? $data['progetto'] : null;
$this->container['conto'] = isset($data['conto']) ? $data['conto'] : null;
$this->container['evento'] = isset($data['evento']) ? $data['evento'] : null;
$this->container['codice_transazione'] = isset($data['codice_transazione']) ? $data['codice_transazione'] : null;
$this->container['importo'] = isset($data['importo']) ? $data['importo'] : null;
$this->container['metodo'] = isset($data['metodo']) ? $data['metodo'] : null;
$this->container['descrizione_metodo'] = isset($data['descrizione_metodo']) ? $data['descrizione_metodo'] : null;
$this->container['data_operazione'] = isset($data['data_operazione']) ? $data['data_operazione'] : null;
$this->container['data_valuta'] = isset($data['data_valuta']) ? $data['data_valuta'] : null;
$this->container['note'] = isset($data['note']) ? $data['note'] : null;
$this->container['tipo'] = isset($data['tipo']) ? $data['tipo'] : null;
$this->container['sotto_tipo'] = isset($data['sotto_tipo']) ? $data['sotto_tipo'] : null;
$this->container['lotto'] = isset($data['lotto']) ? $data['lotto'] : null;
$this->container['escludi_attestato'] = isset($data['escludi_attestato']) ? $data['escludi_attestato'] : null;
$this->container['flag_one_off'] = isset($data['flag_one_off']) ? $data['flag_one_off'] : null;
$this->container['prodotti'] = isset($data['prodotti']) ? $data['prodotti'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets id_versamento
*
* @return int
*/
public function getIdVersamento()
{
return $this->container['id_versamento'];
}
/**
* Sets id_versamento
*
* @param int $id_versamento id_versamento
*
* @return $this
*/
public function setIdVersamento($id_versamento)
{
$this->container['id_versamento'] = $id_versamento;
return $this;
}
/**
* Gets id_regolare
*
* @return int
*/
public function getIdRegolare()
{
return $this->container['id_regolare'];
}
/**
* Sets id_regolare
*
* @param int $id_regolare id_regolare
*
* @return $this
*/
public function setIdRegolare($id_regolare)
{
$this->container['id_regolare'] = $id_regolare;
return $this;
}
/**
* Gets id_web
*
* @return string
*/
public function getIdWeb()
{
return $this->container['id_web'];
}
/**
* Sets id_web
*
* @param string $id_web id_web
*
* @return $this
*/
public function setIdWeb($id_web)
{
$this->container['id_web'] = $id_web;
return $this;
}
/**
* Gets codice_cliente
*
* @return string
*/
public function getCodiceCliente()
{
return $this->container['codice_cliente'];
}
/**
* Sets codice_cliente
*
* @param string $codice_cliente codice_cliente
*
* @return $this
*/
public function setCodiceCliente($codice_cliente)
{
$this->container['codice_cliente'] = $codice_cliente;
return $this;
}
/**
* Gets codice_soggetto_versante
*
* @return string
*/
public function getCodiceSoggettoVersante()
{
return $this->container['codice_soggetto_versante'];
}
/**
* Sets codice_soggetto_versante
*
* @param string $codice_soggetto_versante codice_soggetto_versante
*
* @return $this
*/
public function setCodiceSoggettoVersante($codice_soggetto_versante)
{
$this->container['codice_soggetto_versante'] = $codice_soggetto_versante;
return $this;
}
/**
* Gets codice_centro_ricavo
*
* @return string
*/
public function getCodiceCentroRicavo()
{
return $this->container['codice_centro_ricavo'];
}
/**
* Sets codice_centro_ricavo
*
* @param string $codice_centro_ricavo codice_centro_ricavo
*
* @return $this
*/
public function setCodiceCentroRicavo($codice_centro_ricavo)
{
$this->container['codice_centro_ricavo'] = $codice_centro_ricavo;
return $this;
}
/**
* Gets codice_partner
*
* @return string
*/
public function getCodicePartner()
{
return $this->container['codice_partner'];
}
/**
* Sets codice_partner
*
* @param string $codice_partner codice_partner
*
* @return $this
*/
public function setCodicePartner($codice_partner)
{
$this->container['codice_partner'] = $codice_partner;
return $this;
}
/**
* Gets codice_riferimento
*
* @return string
*/
public function getCodiceRiferimento()
{
return $this->container['codice_riferimento'];
}
/**
* Sets codice_riferimento
*
* @param string $codice_riferimento codice_riferimento
*
* @return $this
*/
public function setCodiceRiferimento($codice_riferimento)
{
$this->container['codice_riferimento'] = $codice_riferimento;
return $this;
}
/**
* Gets campagna
*
* @return object
*/
public function getCampagna()
{
return $this->container['campagna'];
}
/**
* Sets campagna
*
* @param object $campagna campagna
*
* @return $this
*/
public function setCampagna($campagna)
{
$this->container['campagna'] = $campagna;
return $this;
}
/**
* Gets centro
*
* @return object
*/
public function getCentro()
{
return $this->container['centro'];
}
/**
* Sets centro
*
* @param object $centro centro
*
* @return $this
*/
public function setCentro($centro)
{
$this->container['centro'] = $centro;
return $this;
}
/**
* Gets canale
*
* @return object
*/
public function getCanale()
{
return $this->container['canale'];
}
/**
* Sets canale
*
* @param object $canale canale
*
* @return $this
*/
public function setCanale($canale)
{
$this->container['canale'] = $canale;
return $this;
}
/**
* Gets bambino
*
* @return object
*/
public function getBambino()
{
return $this->container['bambino'];
}
/**
* Sets bambino
*
* @param object $bambino bambino
*
* @return $this
*/
public function setBambino($bambino)
{
$this->container['bambino'] = $bambino;
return $this;
}
/**
* Gets progetto
*
* @return object
*/
public function getProgetto()
{
return $this->container['progetto'];
}
/**
* Sets progetto
*
* @param object $progetto progetto
*
* @return $this
*/
public function setProgetto($progetto)
{
$this->container['progetto'] = $progetto;
return $this;
}
/**
* Gets conto
*
* @return object
*/
public function getConto()
{
return $this->container['conto'];
}
/**
* Sets conto
*
* @param object $conto conto
*
* @return $this
*/
public function setConto($conto)
{
$this->container['conto'] = $conto;
return $this;
}
/**
* Gets evento
*
* @return object
*/
public function getEvento()
{
return $this->container['evento'];
}
/**
* Sets evento
*
* @param object $evento evento
*
* @return $this
*/
public function setEvento($evento)
{
$this->container['evento'] = $evento;
return $this;
}
/**
* Gets codice_transazione
*
* @return string
*/
public function getCodiceTransazione()
{
return $this->container['codice_transazione'];
}
/**
* Sets codice_transazione
*
* @param string $codice_transazione codice_transazione
*
* @return $this
*/
public function setCodiceTransazione($codice_transazione)
{
$this->container['codice_transazione'] = $codice_transazione;
return $this;
}
/**
* Gets importo
*
* @return float
*/
public function getImporto()
{
return $this->container['importo'];
}
/**
* Sets importo
*
* @param float $importo importo
*
* @return $this
*/
public function setImporto($importo)
{
$this->container['importo'] = $importo;
return $this;
}
/**
* Gets metodo
*
* @return string
*/
public function getMetodo()
{
return $this->container['metodo'];
}
/**
* Sets metodo
*
* @param string $metodo metodo
*
* @return $this
*/
public function setMetodo($metodo)
{
$this->container['metodo'] = $metodo;
return $this;
}
/**
* Gets descrizione_metodo
*
* @return string
*/
public function getDescrizioneMetodo()
{
return $this->container['descrizione_metodo'];
}
/**
* Sets descrizione_metodo
*
* @param string $descrizione_metodo descrizione_metodo
*
* @return $this
*/
public function setDescrizioneMetodo($descrizione_metodo)
{
$this->container['descrizione_metodo'] = $descrizione_metodo;
return $this;
}
/**
* Gets data_operazione
*
* @return string
*/
public function getDataOperazione()
{
return $this->container['data_operazione'];
}
/**
* Sets data_operazione
*
* @param string $data_operazione data_operazione
*
* @return $this
*/
public function setDataOperazione($data_operazione)
{
$this->container['data_operazione'] = $data_operazione;
return $this;
}
/**
* Gets data_valuta
*
* @return string
*/
public function getDataValuta()
{
return $this->container['data_valuta'];
}
/**
* Sets data_valuta
*
* @param string $data_valuta data_valuta
*
* @return $this
*/
public function setDataValuta($data_valuta)
{
$this->container['data_valuta'] = $data_valuta;
return $this;
}
/**
* Gets note
*
* @return string
*/
public function getNote()
{
return $this->container['note'];
}
/**
* Sets note
*
* @param string $note note
*
* @return $this
*/
public function setNote($note)
{
$this->container['note'] = $note;
return $this;
}
/**
* Gets tipo
*
* @return object
*/
public function getTipo()
{
return $this->container['tipo'];
}
/**
* Sets tipo
*
* @param object $tipo tipo
*
* @return $this
*/
public function setTipo($tipo)
{
$this->container['tipo'] = $tipo;
return $this;
}
/**
* Gets sotto_tipo
*
* @return object
*/
public function getSottoTipo()
{
return $this->container['sotto_tipo'];
}
/**
* Sets sotto_tipo
*
* @param object $sotto_tipo sotto_tipo
*
* @return $this
*/
public function setSottoTipo($sotto_tipo)
{
$this->container['sotto_tipo'] = $sotto_tipo;
return $this;
}
/**
* Gets lotto
*
* @return string
*/
public function getLotto()
{
return $this->container['lotto'];
}
/**
* Sets lotto
*
* @param string $lotto lotto
*
* @return $this
*/
public function setLotto($lotto)
{
$this->container['lotto'] = $lotto;
return $this;
}
/**
* Gets escludi_attestato
*
* @return string
*/
public function getEscludiAttestato()
{
return $this->container['escludi_attestato'];
}
/**
* Sets escludi_attestato
*
* @param string $escludi_attestato escludi_attestato
*
* @return $this
*/
public function setEscludiAttestato($escludi_attestato)
{
$this->container['escludi_attestato'] = $escludi_attestato;
return $this;
}
/**
* Gets flag_one_off
*
* @return bool
*/
public function getFlagOneOff()
{
return $this->container['flag_one_off'];
}
/**
* Sets flag_one_off
*
* @param bool $flag_one_off flag_one_off
*
* @return $this
*/
public function setFlagOneOff($flag_one_off)
{
$this->container['flag_one_off'] = $flag_one_off;
return $this;
}
/**
* Gets prodotti
*
* @return \Swagger\Client\Model\VersamentoProdotti[]
*/
public function getProdotti()
{
return $this->container['prodotti'];
}
/**
* Sets prodotti
*
* @param \Swagger\Client\Model\VersamentoProdotti[] $prodotti prodotti
*
* @return $this
*/
public function setProdotti($prodotti)
{
$this->container['prodotti'] = $prodotti;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep><?php
/**
* ClientiSubscription
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace Swagger\Client\Model;
use \ArrayAccess;
use \Swagger\Client\ObjectSerializer;
/**
* ClientiSubscription Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class ClientiSubscription implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'ClientiSubscription';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'id_cliente' => 'int',
'codice_argomento' => 'string',
'descrizione_argomento' => 'string',
'codice_gruppo' => 'string',
'descrizione_gruppo' => 'string',
'attiva' => 'bool',
'data_iscrizione' => 'string',
'data_disiscrizione' => 'string'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'id_cliente' => 'int32',
'codice_argomento' => null,
'descrizione_argomento' => null,
'codice_gruppo' => null,
'descrizione_gruppo' => null,
'attiva' => null,
'data_iscrizione' => null,
'data_disiscrizione' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'id_cliente' => 'IdCliente',
'codice_argomento' => 'CodiceArgomento',
'descrizione_argomento' => 'DescrizioneArgomento',
'codice_gruppo' => 'CodiceGruppo',
'descrizione_gruppo' => 'DescrizioneGruppo',
'attiva' => 'Attiva',
'data_iscrizione' => 'DataIscrizione',
'data_disiscrizione' => 'DataDisiscrizione'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'id_cliente' => 'setIdCliente',
'codice_argomento' => 'setCodiceArgomento',
'descrizione_argomento' => 'setDescrizioneArgomento',
'codice_gruppo' => 'setCodiceGruppo',
'descrizione_gruppo' => 'setDescrizioneGruppo',
'attiva' => 'setAttiva',
'data_iscrizione' => 'setDataIscrizione',
'data_disiscrizione' => 'setDataDisiscrizione'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'id_cliente' => 'getIdCliente',
'codice_argomento' => 'getCodiceArgomento',
'descrizione_argomento' => 'getDescrizioneArgomento',
'codice_gruppo' => 'getCodiceGruppo',
'descrizione_gruppo' => 'getDescrizioneGruppo',
'attiva' => 'getAttiva',
'data_iscrizione' => 'getDataIscrizione',
'data_disiscrizione' => 'getDataDisiscrizione'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['id_cliente'] = isset($data['id_cliente']) ? $data['id_cliente'] : null;
$this->container['codice_argomento'] = isset($data['codice_argomento']) ? $data['codice_argomento'] : null;
$this->container['descrizione_argomento'] = isset($data['descrizione_argomento']) ? $data['descrizione_argomento'] : null;
$this->container['codice_gruppo'] = isset($data['codice_gruppo']) ? $data['codice_gruppo'] : null;
$this->container['descrizione_gruppo'] = isset($data['descrizione_gruppo']) ? $data['descrizione_gruppo'] : null;
$this->container['attiva'] = isset($data['attiva']) ? $data['attiva'] : null;
$this->container['data_iscrizione'] = isset($data['data_iscrizione']) ? $data['data_iscrizione'] : null;
$this->container['data_disiscrizione'] = isset($data['data_disiscrizione']) ? $data['data_disiscrizione'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets id_cliente
*
* @return int
*/
public function getIdCliente()
{
return $this->container['id_cliente'];
}
/**
* Sets id_cliente
*
* @param int $id_cliente id_cliente
*
* @return $this
*/
public function setIdCliente($id_cliente)
{
$this->container['id_cliente'] = $id_cliente;
return $this;
}
/**
* Gets codice_argomento
*
* @return string
*/
public function getCodiceArgomento()
{
return $this->container['codice_argomento'];
}
/**
* Sets codice_argomento
*
* @param string $codice_argomento codice_argomento
*
* @return $this
*/
public function setCodiceArgomento($codice_argomento)
{
$this->container['codice_argomento'] = $codice_argomento;
return $this;
}
/**
* Gets descrizione_argomento
*
* @return string
*/
public function getDescrizioneArgomento()
{
return $this->container['descrizione_argomento'];
}
/**
* Sets descrizione_argomento
*
* @param string $descrizione_argomento descrizione_argomento
*
* @return $this
*/
public function setDescrizioneArgomento($descrizione_argomento)
{
$this->container['descrizione_argomento'] = $descrizione_argomento;
return $this;
}
/**
* Gets codice_gruppo
*
* @return string
*/
public function getCodiceGruppo()
{
return $this->container['codice_gruppo'];
}
/**
* Sets codice_gruppo
*
* @param string $codice_gruppo codice_gruppo
*
* @return $this
*/
public function setCodiceGruppo($codice_gruppo)
{
$this->container['codice_gruppo'] = $codice_gruppo;
return $this;
}
/**
* Gets descrizione_gruppo
*
* @return string
*/
public function getDescrizioneGruppo()
{
return $this->container['descrizione_gruppo'];
}
/**
* Sets descrizione_gruppo
*
* @param string $descrizione_gruppo descrizione_gruppo
*
* @return $this
*/
public function setDescrizioneGruppo($descrizione_gruppo)
{
$this->container['descrizione_gruppo'] = $descrizione_gruppo;
return $this;
}
/**
* Gets attiva
*
* @return bool
*/
public function getAttiva()
{
return $this->container['attiva'];
}
/**
* Sets attiva
*
* @param bool $attiva attiva
*
* @return $this
*/
public function setAttiva($attiva)
{
$this->container['attiva'] = $attiva;
return $this;
}
/**
* Gets data_iscrizione
*
* @return string
*/
public function getDataIscrizione()
{
return $this->container['data_iscrizione'];
}
/**
* Sets data_iscrizione
*
* @param string $data_iscrizione data_iscrizione
*
* @return $this
*/
public function setDataIscrizione($data_iscrizione)
{
$this->container['data_iscrizione'] = $data_iscrizione;
return $this;
}
/**
* Gets data_disiscrizione
*
* @return string
*/
public function getDataDisiscrizione()
{
return $this->container['data_disiscrizione'];
}
/**
* Sets data_disiscrizione
*
* @param string $data_disiscrizione data_disiscrizione
*
* @return $this
*/
public function setDataDisiscrizione($data_disiscrizione)
{
$this->container['data_disiscrizione'] = $data_disiscrizione;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep><?php
/**
* ClientiGruppi
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace Swagger\Client\Model;
use \ArrayAccess;
use \Swagger\Client\ObjectSerializer;
/**
* ClientiGruppi Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class ClientiGruppi implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'ClientiGruppi';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'codice_cliente' => 'string',
'codice_cliente_gruppo' => 'string',
'id_ruolo' => 'string',
'descrizione_ruolo' => 'string',
'data_gruppo' => 'string'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'codice_cliente' => null,
'codice_cliente_gruppo' => null,
'id_ruolo' => null,
'descrizione_ruolo' => null,
'data_gruppo' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'codice_cliente' => 'CodiceCliente',
'codice_cliente_gruppo' => 'CodiceClienteGruppo',
'id_ruolo' => 'idRuolo',
'descrizione_ruolo' => 'DescrizioneRuolo',
'data_gruppo' => 'DataGruppo'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'codice_cliente' => 'setCodiceCliente',
'codice_cliente_gruppo' => 'setCodiceClienteGruppo',
'id_ruolo' => 'setIdRuolo',
'descrizione_ruolo' => 'setDescrizioneRuolo',
'data_gruppo' => 'setDataGruppo'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'codice_cliente' => 'getCodiceCliente',
'codice_cliente_gruppo' => 'getCodiceClienteGruppo',
'id_ruolo' => 'getIdRuolo',
'descrizione_ruolo' => 'getDescrizioneRuolo',
'data_gruppo' => 'getDataGruppo'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['codice_cliente'] = isset($data['codice_cliente']) ? $data['codice_cliente'] : null;
$this->container['codice_cliente_gruppo'] = isset($data['codice_cliente_gruppo']) ? $data['codice_cliente_gruppo'] : null;
$this->container['id_ruolo'] = isset($data['id_ruolo']) ? $data['id_ruolo'] : null;
$this->container['descrizione_ruolo'] = isset($data['descrizione_ruolo']) ? $data['descrizione_ruolo'] : null;
$this->container['data_gruppo'] = isset($data['data_gruppo']) ? $data['data_gruppo'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets codice_cliente
*
* @return string
*/
public function getCodiceCliente()
{
return $this->container['codice_cliente'];
}
/**
* Sets codice_cliente
*
* @param string $codice_cliente codice_cliente
*
* @return $this
*/
public function setCodiceCliente($codice_cliente)
{
$this->container['codice_cliente'] = $codice_cliente;
return $this;
}
/**
* Gets codice_cliente_gruppo
*
* @return string
*/
public function getCodiceClienteGruppo()
{
return $this->container['codice_cliente_gruppo'];
}
/**
* Sets codice_cliente_gruppo
*
* @param string $codice_cliente_gruppo codice_cliente_gruppo
*
* @return $this
*/
public function setCodiceClienteGruppo($codice_cliente_gruppo)
{
$this->container['codice_cliente_gruppo'] = $codice_cliente_gruppo;
return $this;
}
/**
* Gets id_ruolo
*
* @return string
*/
public function getIdRuolo()
{
return $this->container['id_ruolo'];
}
/**
* Sets id_ruolo
*
* @param string $id_ruolo id_ruolo
*
* @return $this
*/
public function setIdRuolo($id_ruolo)
{
$this->container['id_ruolo'] = $id_ruolo;
return $this;
}
/**
* Gets descrizione_ruolo
*
* @return string
*/
public function getDescrizioneRuolo()
{
return $this->container['descrizione_ruolo'];
}
/**
* Sets descrizione_ruolo
*
* @param string $descrizione_ruolo descrizione_ruolo
*
* @return $this
*/
public function setDescrizioneRuolo($descrizione_ruolo)
{
$this->container['descrizione_ruolo'] = $descrizione_ruolo;
return $this;
}
/**
* Gets data_gruppo
*
* @return string
*/
public function getDataGruppo()
{
return $this->container['data_gruppo'];
}
/**
* Sets data_gruppo
*
* @param string $data_gruppo data_gruppo
*
* @return $this
*/
public function setDataGruppo($data_gruppo)
{
$this->container['data_gruppo'] = $data_gruppo;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep><?php
/**
* AnagraficaApi
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace Swagger\Client\Api;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use Swagger\Client\ApiException;
use Swagger\Client\Configuration;
use Swagger\Client\HeaderSelector;
use Swagger\Client\ObjectSerializer;
/**
* AnagraficaApi Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class AnagraficaApi
{
/**
* @var ClientInterface
*/
protected $client;
/**
* @var Configuration
*/
protected $config;
/**
* @var HeaderSelector
*/
protected $headerSelector;
/**
* @param ClientInterface $client
* @param Configuration $config
* @param HeaderSelector $selector
*/
public function __construct(
ClientInterface $client = null,
Configuration $config = null,
HeaderSelector $selector = null
) {
$this->client = $client ?: new Client();
$this->config = $config ?: new Configuration();
$this->headerSelector = $selector ?: new HeaderSelector();
}
/**
* @return Configuration
*/
public function getConfig()
{
return $this->config;
}
/**
* Operation anagraficaGet
*
* @param string $cl_codice cl_codice (required)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Clienti
*/
public function anagraficaGet($cl_codice)
{
list($response) = $this->anagraficaGetWithHttpInfo($cl_codice);
return $response;
}
/**
* Operation anagraficaGetWithHttpInfo
*
* @param string $cl_codice (required)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of \Swagger\Client\Model\Clienti, HTTP status code, HTTP response headers (array of strings)
*/
public function anagraficaGetWithHttpInfo($cl_codice)
{
$returnType = '\Swagger\Client\Model\Clienti';
$request = $this->anagraficaGetRequest($cl_codice);
try {
$options = $this->createHttpClientOption();
try {
$response = $this->client->send($request, $options);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$request->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\Swagger\Client\Model\Clienti',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
}
throw $e;
}
}
/**
* Operation anagraficaGetAsync
*
*
*
* @param string $cl_codice (required)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function anagraficaGetAsync($cl_codice)
{
return $this->anagraficaGetAsyncWithHttpInfo($cl_codice)
->then(
function ($response) {
return $response[0];
}
);
}
/**
* Operation anagraficaGetAsyncWithHttpInfo
*
*
*
* @param string $cl_codice (required)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function anagraficaGetAsyncWithHttpInfo($cl_codice)
{
$returnType = '\Swagger\Client\Model\Clienti';
$request = $this->anagraficaGetRequest($cl_codice);
return $this->client
->sendAsync($request, $this->createHttpClientOption())
->then(
function ($response) use ($returnType) {
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
},
function ($exception) {
$response = $exception->getResponse();
$statusCode = $response->getStatusCode();
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$exception->getRequest()->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
);
}
/**
* Create request for operation 'anagraficaGet'
*
* @param string $cl_codice (required)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Psr7\Request
*/
protected function anagraficaGetRequest($cl_codice)
{
// verify the required parameter 'cl_codice' is set
if ($cl_codice === null || (is_array($cl_codice) && count($cl_codice) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $cl_codice when calling anagraficaGet'
);
}
$resourcePath = '/v1/api/Anagrafica/Get';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// query params
if ($cl_codice !== null) {
$queryParams['cl_codice'] = ObjectSerializer::toQueryValue($cl_codice);
}
// body params
$_tempBody = null;
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json', 'text/json', 'application/xml', 'text/xml']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json', 'text/json', 'application/xml', 'text/xml'],
[]
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
if($headers['Content-Type'] === 'application/json') {
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass) {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
// array has no __toString(), so we should encode it manually
if(is_array($httpBody)) {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody));
}
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'GET',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
/**
* Operation anagraficaInsertCliente
*
* @param \Swagger\Client\Model\Clienti[] $raw_string raw_string (required)
* @param bool $controllo controllo (optional)
* @param string $ambiente ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Clienti[]
*/
public function anagraficaInsertCliente($raw_string, $controllo = null, $ambiente = null)
{
list($response) = $this->anagraficaInsertClienteWithHttpInfo($raw_string, $controllo, $ambiente);
return $response;
}
/**
* Operation anagraficaInsertClienteWithHttpInfo
*
* @param \Swagger\Client\Model\Clienti[] $raw_string (required)
* @param bool $controllo (optional)
* @param string $ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of \Swagger\Client\Model\Clienti[], HTTP status code, HTTP response headers (array of strings)
*/
public function anagraficaInsertClienteWithHttpInfo($raw_string, $controllo = null, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Clienti[]';
$request = $this->anagraficaInsertClienteRequest($raw_string, $controllo, $ambiente);
try {
$options = $this->createHttpClientOption();
try {
$response = $this->client->send($request, $options);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$request->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\Swagger\Client\Model\Clienti[]',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
}
throw $e;
}
}
/**
* Operation anagraficaInsertClienteAsync
*
*
*
* @param \Swagger\Client\Model\Clienti[] $raw_string (required)
* @param bool $controllo (optional)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function anagraficaInsertClienteAsync($raw_string, $controllo = null, $ambiente = null)
{
return $this->anagraficaInsertClienteAsyncWithHttpInfo($raw_string, $controllo, $ambiente)
->then(
function ($response) {
return $response[0];
}
);
}
/**
* Operation anagraficaInsertClienteAsyncWithHttpInfo
*
*
*
* @param \Swagger\Client\Model\Clienti[] $raw_string (required)
* @param bool $controllo (optional)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function anagraficaInsertClienteAsyncWithHttpInfo($raw_string, $controllo = null, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Clienti[]';
$request = $this->anagraficaInsertClienteRequest($raw_string, $controllo, $ambiente);
return $this->client
->sendAsync($request, $this->createHttpClientOption())
->then(
function ($response) use ($returnType) {
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
},
function ($exception) {
$response = $exception->getResponse();
$statusCode = $response->getStatusCode();
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$exception->getRequest()->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
);
}
/**
* Create request for operation 'anagraficaInsertCliente'
*
* @param \Swagger\Client\Model\Clienti[] $raw_string (required)
* @param bool $controllo (optional)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Psr7\Request
*/
protected function anagraficaInsertClienteRequest($raw_string, $controllo = null, $ambiente = null)
{
// verify the required parameter 'raw_string' is set
if ($raw_string === null || (is_array($raw_string) && count($raw_string) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $raw_string when calling anagraficaInsertCliente'
);
}
$resourcePath = '/v1/api/Anagrafica/InsertCliente';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// query params
if ($controllo !== null) {
$queryParams['Controllo'] = ObjectSerializer::toQueryValue($controllo);
}
// query params
if ($ambiente !== null) {
$queryParams['Ambiente'] = ObjectSerializer::toQueryValue($ambiente);
}
// body params
$_tempBody = null;
if (isset($raw_string)) {
$_tempBody = $raw_string;
}
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json', 'text/json', 'application/xml', 'text/xml']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json', 'text/json', 'application/xml', 'text/xml'],
['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded']
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
if($headers['Content-Type'] === 'application/json') {
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass) {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
// array has no __toString(), so we should encode it manually
if(is_array($httpBody)) {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody));
}
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'POST',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
/**
* Operation anagraficaUpdateCliente
*
* @param \Swagger\Client\Model\Clienti[] $raw_string raw_string (required)
* @param string $ambiente ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Clienti[]
*/
public function anagraficaUpdateCliente($raw_string, $ambiente = null)
{
list($response) = $this->anagraficaUpdateClienteWithHttpInfo($raw_string, $ambiente);
return $response;
}
/**
* Operation anagraficaUpdateClienteWithHttpInfo
*
* @param \Swagger\Client\Model\Clienti[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of \Swagger\Client\Model\Clienti[], HTTP status code, HTTP response headers (array of strings)
*/
public function anagraficaUpdateClienteWithHttpInfo($raw_string, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Clienti[]';
$request = $this->anagraficaUpdateClienteRequest($raw_string, $ambiente);
try {
$options = $this->createHttpClientOption();
try {
$response = $this->client->send($request, $options);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$request->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\Swagger\Client\Model\Clienti[]',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
}
throw $e;
}
}
/**
* Operation anagraficaUpdateClienteAsync
*
*
*
* @param \Swagger\Client\Model\Clienti[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function anagraficaUpdateClienteAsync($raw_string, $ambiente = null)
{
return $this->anagraficaUpdateClienteAsyncWithHttpInfo($raw_string, $ambiente)
->then(
function ($response) {
return $response[0];
}
);
}
/**
* Operation anagraficaUpdateClienteAsyncWithHttpInfo
*
*
*
* @param \Swagger\Client\Model\Clienti[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function anagraficaUpdateClienteAsyncWithHttpInfo($raw_string, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Clienti[]';
$request = $this->anagraficaUpdateClienteRequest($raw_string, $ambiente);
return $this->client
->sendAsync($request, $this->createHttpClientOption())
->then(
function ($response) use ($returnType) {
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
},
function ($exception) {
$response = $exception->getResponse();
$statusCode = $response->getStatusCode();
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$exception->getRequest()->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
);
}
/**
* Create request for operation 'anagraficaUpdateCliente'
*
* @param \Swagger\Client\Model\Clienti[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Psr7\Request
*/
protected function anagraficaUpdateClienteRequest($raw_string, $ambiente = null)
{
// verify the required parameter 'raw_string' is set
if ($raw_string === null || (is_array($raw_string) && count($raw_string) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $raw_string when calling anagraficaUpdateCliente'
);
}
$resourcePath = '/v1/api/Anagrafica/UpdateCliente';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// query params
if ($ambiente !== null) {
$queryParams['Ambiente'] = ObjectSerializer::toQueryValue($ambiente);
}
// body params
$_tempBody = null;
if (isset($raw_string)) {
$_tempBody = $raw_string;
}
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json', 'text/json', 'application/xml', 'text/xml']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json', 'text/json', 'application/xml', 'text/xml'],
['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded']
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
if($headers['Content-Type'] === 'application/json') {
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass) {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
// array has no __toString(), so we should encode it manually
if(is_array($httpBody)) {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody));
}
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'POST',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
/**
* Create http client option
*
* @throws \RuntimeException on file opening failure
* @return array of http client options
*/
protected function createHttpClientOption()
{
$options = [];
if ($this->config->getDebug()) {
$options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
if (!$options[RequestOptions::DEBUG]) {
throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
}
}
return $options;
}
}
<file_sep><?php
/**
* CallRegolareTest
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace Swagger\Client;
/**
* CallRegolareTest Class Doc Comment
*
* @category Class
* @description CallRegolare
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class CallRegolareTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "CallRegolare"
*/
public function testCallRegolare()
{
}
/**
* Test attribute "id_regolare"
*/
public function testPropertyIdRegolare()
{
}
/**
* Test attribute "codice_esito"
*/
public function testPropertyCodiceEsito()
{
}
/**
* Test attribute "codice_motivo_rinuncia"
*/
public function testPropertyCodiceMotivoRinuncia()
{
}
/**
* Test attribute "data_rinuncia"
*/
public function testPropertyDataRinuncia()
{
}
/**
* Test attribute "codice_campagna"
*/
public function testPropertyCodiceCampagna()
{
}
/**
* Test attribute "importo"
*/
public function testPropertyImporto()
{
}
/**
* Test attribute "frequenza"
*/
public function testPropertyFrequenza()
{
}
/**
* Test attribute "stato"
*/
public function testPropertyStato()
{
}
}
<file_sep><?php
/**
* Periodici
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace Swagger\Client\Model;
use \ArrayAccess;
use \Swagger\Client\ObjectSerializer;
/**
* Periodici Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class Periodici implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'Periodici';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'id' => 'int',
'codice_donatore' => 'string',
'codice_soggetto_versante' => 'string',
'campagna' => 'object',
'centro' => 'object',
'canale' => 'object',
'codice_bambino' => 'string',
'progetto' => 'object',
'tema' => 'object',
'stato' => 'object',
'importo' => 'float',
'frequenza' => 'int',
'metodo_pagamento' => 'object',
'data_richiesta' => 'string',
'ora_richiesta' => 'string',
'data_delega' => 'string',
'data_promessa' => 'string',
'data_prossima_richiesta' => 'string',
'codice_dialogatore_interno' => 'string',
'codice_dialogatore_esterno' => 'string',
'nome_dialogatore_esterno' => 'string',
'urn' => 'string',
'url' => 'string',
'lotto' => 'string',
'locazione' => 'string',
'citta_locazione' => 'string',
'nome_titolare' => 'string',
'codice_titolare' => 'string',
'iban' => 'string',
'bic' => 'string',
'token' => 'string',
'mese_token' => 'string',
'anno_token' => 'string',
'provider_incasso' => 'string',
'carta_prepagata' => 'bool',
'note' => 'string',
'id_capogruppo' => 'int',
'tipo_lead' => 'string',
'genera_sostegno' => 'bool',
'preferenza_continente' => 'string',
'preferenza_nazione' => 'string',
'preferenza_eta_minima' => 'string',
'preferenza_eta_massima' => 'string',
'preferenza_genere' => 'string',
'id_campagna' => 'int',
'id_centro' => 'int',
'gruppo_incassi' => 'int',
'codice_nazione' => 'string',
'cin_iban' => 'string',
'cin_bban' => 'string',
'abi' => 'string',
'cab' => 'string',
'conto' => 'string',
'flag_one_off' => 'string',
'masked_pan' => 'string',
'numero_carta' => 'string',
'anno_carta' => 'int',
'mese_carta' => 'int',
'data_inizio_sospensione' => 'string',
'data_fine_sospensione' => 'string',
'id_motivo_rinuncia' => 'int',
'data_rinuncia' => 'string'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'id' => 'int32',
'codice_donatore' => null,
'codice_soggetto_versante' => null,
'campagna' => null,
'centro' => null,
'canale' => null,
'codice_bambino' => null,
'progetto' => null,
'tema' => null,
'stato' => null,
'importo' => 'float',
'frequenza' => 'int32',
'metodo_pagamento' => null,
'data_richiesta' => null,
'ora_richiesta' => null,
'data_delega' => null,
'data_promessa' => null,
'data_prossima_richiesta' => null,
'codice_dialogatore_interno' => null,
'codice_dialogatore_esterno' => null,
'nome_dialogatore_esterno' => null,
'urn' => null,
'url' => null,
'lotto' => null,
'locazione' => null,
'citta_locazione' => null,
'nome_titolare' => null,
'codice_titolare' => null,
'iban' => null,
'bic' => null,
'token' => null,
'mese_token' => null,
'anno_token' => null,
'provider_incasso' => null,
'carta_prepagata' => null,
'note' => null,
'id_capogruppo' => 'int32',
'tipo_lead' => null,
'genera_sostegno' => null,
'preferenza_continente' => null,
'preferenza_nazione' => null,
'preferenza_eta_minima' => null,
'preferenza_eta_massima' => null,
'preferenza_genere' => null,
'id_campagna' => 'int32',
'id_centro' => 'int32',
'gruppo_incassi' => 'int32',
'codice_nazione' => null,
'cin_iban' => null,
'cin_bban' => null,
'abi' => null,
'cab' => null,
'conto' => null,
'flag_one_off' => null,
'masked_pan' => null,
'numero_carta' => null,
'anno_carta' => 'int32',
'mese_carta' => 'int32',
'data_inizio_sospensione' => null,
'data_fine_sospensione' => null,
'id_motivo_rinuncia' => 'int32',
'data_rinuncia' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'id' => 'ID',
'codice_donatore' => 'CodiceDonatore',
'codice_soggetto_versante' => 'CodiceSoggettoVersante',
'campagna' => 'Campagna',
'centro' => 'Centro',
'canale' => 'Canale',
'codice_bambino' => 'CodiceBambino',
'progetto' => 'Progetto',
'tema' => 'Tema',
'stato' => 'Stato',
'importo' => 'Importo',
'frequenza' => 'Frequenza',
'metodo_pagamento' => 'MetodoPagamento',
'data_richiesta' => 'DataRichiesta',
'ora_richiesta' => 'OraRichiesta',
'data_delega' => 'DataDelega',
'data_promessa' => 'DataPromessa',
'data_prossima_richiesta' => 'DataProssimaRichiesta',
'codice_dialogatore_interno' => 'CodiceDialogatoreInterno',
'codice_dialogatore_esterno' => 'CodiceDialogatoreEsterno',
'nome_dialogatore_esterno' => 'NomeDialogatoreEsterno',
'urn' => 'urn',
'url' => 'url',
'lotto' => 'Lotto',
'locazione' => 'Locazione',
'citta_locazione' => 'CittaLocazione',
'nome_titolare' => 'NomeTitolare',
'codice_titolare' => 'CodiceTitolare',
'iban' => 'IBAN',
'bic' => 'BIC',
'token' => 'Token',
'mese_token' => 'MeseToken',
'anno_token' => 'AnnoToken',
'provider_incasso' => 'ProviderIncasso',
'carta_prepagata' => 'CartaPrepagata',
'note' => 'Note',
'id_capogruppo' => 'idCapogruppo',
'tipo_lead' => 'TipoLead',
'genera_sostegno' => 'GeneraSostegno',
'preferenza_continente' => 'PreferenzaContinente',
'preferenza_nazione' => 'PreferenzaNazione',
'preferenza_eta_minima' => 'PreferenzaEtaMinima',
'preferenza_eta_massima' => 'PreferenzaEtaMassima',
'preferenza_genere' => 'PreferenzaGenere',
'id_campagna' => 'idCampagna',
'id_centro' => 'idCentro',
'gruppo_incassi' => 'GruppoIncassi',
'codice_nazione' => 'CodiceNazione',
'cin_iban' => 'cinIban',
'cin_bban' => 'cinBban',
'abi' => 'ABI',
'cab' => 'CAB',
'conto' => 'Conto',
'flag_one_off' => 'FlagOneOff',
'masked_pan' => 'MaskedPan',
'numero_carta' => 'NumeroCarta',
'anno_carta' => 'AnnoCarta',
'mese_carta' => 'MeseCarta',
'data_inizio_sospensione' => 'DataInizioSospensione',
'data_fine_sospensione' => 'DataFineSospensione',
'id_motivo_rinuncia' => 'idMotivoRinuncia',
'data_rinuncia' => 'DataRinuncia'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'id' => 'setId',
'codice_donatore' => 'setCodiceDonatore',
'codice_soggetto_versante' => 'setCodiceSoggettoVersante',
'campagna' => 'setCampagna',
'centro' => 'setCentro',
'canale' => 'setCanale',
'codice_bambino' => 'setCodiceBambino',
'progetto' => 'setProgetto',
'tema' => 'setTema',
'stato' => 'setStato',
'importo' => 'setImporto',
'frequenza' => 'setFrequenza',
'metodo_pagamento' => 'setMetodoPagamento',
'data_richiesta' => 'setDataRichiesta',
'ora_richiesta' => 'setOraRichiesta',
'data_delega' => 'setDataDelega',
'data_promessa' => 'setDataPromessa',
'data_prossima_richiesta' => 'setDataProssimaRichiesta',
'codice_dialogatore_interno' => 'setCodiceDialogatoreInterno',
'codice_dialogatore_esterno' => 'setCodiceDialogatoreEsterno',
'nome_dialogatore_esterno' => 'setNomeDialogatoreEsterno',
'urn' => 'setUrn',
'url' => 'setUrl',
'lotto' => 'setLotto',
'locazione' => 'setLocazione',
'citta_locazione' => 'setCittaLocazione',
'nome_titolare' => 'setNomeTitolare',
'codice_titolare' => 'setCodiceTitolare',
'iban' => 'setIban',
'bic' => 'setBic',
'token' => 'setToken',
'mese_token' => 'setMeseToken',
'anno_token' => 'setAnnoToken',
'provider_incasso' => 'setProviderIncasso',
'carta_prepagata' => 'setCartaPrepagata',
'note' => 'setNote',
'id_capogruppo' => 'setIdCapogruppo',
'tipo_lead' => 'setTipoLead',
'genera_sostegno' => 'setGeneraSostegno',
'preferenza_continente' => 'setPreferenzaContinente',
'preferenza_nazione' => 'setPreferenzaNazione',
'preferenza_eta_minima' => 'setPreferenzaEtaMinima',
'preferenza_eta_massima' => 'setPreferenzaEtaMassima',
'preferenza_genere' => 'setPreferenzaGenere',
'id_campagna' => 'setIdCampagna',
'id_centro' => 'setIdCentro',
'gruppo_incassi' => 'setGruppoIncassi',
'codice_nazione' => 'setCodiceNazione',
'cin_iban' => 'setCinIban',
'cin_bban' => 'setCinBban',
'abi' => 'setAbi',
'cab' => 'setCab',
'conto' => 'setConto',
'flag_one_off' => 'setFlagOneOff',
'masked_pan' => 'setMaskedPan',
'numero_carta' => 'setNumeroCarta',
'anno_carta' => 'setAnnoCarta',
'mese_carta' => 'setMeseCarta',
'data_inizio_sospensione' => 'setDataInizioSospensione',
'data_fine_sospensione' => 'setDataFineSospensione',
'id_motivo_rinuncia' => 'setIdMotivoRinuncia',
'data_rinuncia' => 'setDataRinuncia'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'id' => 'getId',
'codice_donatore' => 'getCodiceDonatore',
'codice_soggetto_versante' => 'getCodiceSoggettoVersante',
'campagna' => 'getCampagna',
'centro' => 'getCentro',
'canale' => 'getCanale',
'codice_bambino' => 'getCodiceBambino',
'progetto' => 'getProgetto',
'tema' => 'getTema',
'stato' => 'getStato',
'importo' => 'getImporto',
'frequenza' => 'getFrequenza',
'metodo_pagamento' => 'getMetodoPagamento',
'data_richiesta' => 'getDataRichiesta',
'ora_richiesta' => 'getOraRichiesta',
'data_delega' => 'getDataDelega',
'data_promessa' => 'getDataPromessa',
'data_prossima_richiesta' => 'getDataProssimaRichiesta',
'codice_dialogatore_interno' => 'getCodiceDialogatoreInterno',
'codice_dialogatore_esterno' => 'getCodiceDialogatoreEsterno',
'nome_dialogatore_esterno' => 'getNomeDialogatoreEsterno',
'urn' => 'getUrn',
'url' => 'getUrl',
'lotto' => 'getLotto',
'locazione' => 'getLocazione',
'citta_locazione' => 'getCittaLocazione',
'nome_titolare' => 'getNomeTitolare',
'codice_titolare' => 'getCodiceTitolare',
'iban' => 'getIban',
'bic' => 'getBic',
'token' => 'getToken',
'mese_token' => 'getMeseToken',
'anno_token' => 'getAnnoToken',
'provider_incasso' => 'getProviderIncasso',
'carta_prepagata' => 'getCartaPrepagata',
'note' => 'getNote',
'id_capogruppo' => 'getIdCapogruppo',
'tipo_lead' => 'getTipoLead',
'genera_sostegno' => 'getGeneraSostegno',
'preferenza_continente' => 'getPreferenzaContinente',
'preferenza_nazione' => 'getPreferenzaNazione',
'preferenza_eta_minima' => 'getPreferenzaEtaMinima',
'preferenza_eta_massima' => 'getPreferenzaEtaMassima',
'preferenza_genere' => 'getPreferenzaGenere',
'id_campagna' => 'getIdCampagna',
'id_centro' => 'getIdCentro',
'gruppo_incassi' => 'getGruppoIncassi',
'codice_nazione' => 'getCodiceNazione',
'cin_iban' => 'getCinIban',
'cin_bban' => 'getCinBban',
'abi' => 'getAbi',
'cab' => 'getCab',
'conto' => 'getConto',
'flag_one_off' => 'getFlagOneOff',
'masked_pan' => 'getMaskedPan',
'numero_carta' => 'getNumeroCarta',
'anno_carta' => 'getAnnoCarta',
'mese_carta' => 'getMeseCarta',
'data_inizio_sospensione' => 'getDataInizioSospensione',
'data_fine_sospensione' => 'getDataFineSospensione',
'id_motivo_rinuncia' => 'getIdMotivoRinuncia',
'data_rinuncia' => 'getDataRinuncia'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['id'] = isset($data['id']) ? $data['id'] : null;
$this->container['codice_donatore'] = isset($data['codice_donatore']) ? $data['codice_donatore'] : null;
$this->container['codice_soggetto_versante'] = isset($data['codice_soggetto_versante']) ? $data['codice_soggetto_versante'] : null;
$this->container['campagna'] = isset($data['campagna']) ? $data['campagna'] : null;
$this->container['centro'] = isset($data['centro']) ? $data['centro'] : null;
$this->container['canale'] = isset($data['canale']) ? $data['canale'] : null;
$this->container['codice_bambino'] = isset($data['codice_bambino']) ? $data['codice_bambino'] : null;
$this->container['progetto'] = isset($data['progetto']) ? $data['progetto'] : null;
$this->container['tema'] = isset($data['tema']) ? $data['tema'] : null;
$this->container['stato'] = isset($data['stato']) ? $data['stato'] : null;
$this->container['importo'] = isset($data['importo']) ? $data['importo'] : null;
$this->container['frequenza'] = isset($data['frequenza']) ? $data['frequenza'] : null;
$this->container['metodo_pagamento'] = isset($data['metodo_pagamento']) ? $data['metodo_pagamento'] : null;
$this->container['data_richiesta'] = isset($data['data_richiesta']) ? $data['data_richiesta'] : null;
$this->container['ora_richiesta'] = isset($data['ora_richiesta']) ? $data['ora_richiesta'] : null;
$this->container['data_delega'] = isset($data['data_delega']) ? $data['data_delega'] : null;
$this->container['data_promessa'] = isset($data['data_promessa']) ? $data['data_promessa'] : null;
$this->container['data_prossima_richiesta'] = isset($data['data_prossima_richiesta']) ? $data['data_prossima_richiesta'] : null;
$this->container['codice_dialogatore_interno'] = isset($data['codice_dialogatore_interno']) ? $data['codice_dialogatore_interno'] : null;
$this->container['codice_dialogatore_esterno'] = isset($data['codice_dialogatore_esterno']) ? $data['codice_dialogatore_esterno'] : null;
$this->container['nome_dialogatore_esterno'] = isset($data['nome_dialogatore_esterno']) ? $data['nome_dialogatore_esterno'] : null;
$this->container['urn'] = isset($data['urn']) ? $data['urn'] : null;
$this->container['url'] = isset($data['url']) ? $data['url'] : null;
$this->container['lotto'] = isset($data['lotto']) ? $data['lotto'] : null;
$this->container['locazione'] = isset($data['locazione']) ? $data['locazione'] : null;
$this->container['citta_locazione'] = isset($data['citta_locazione']) ? $data['citta_locazione'] : null;
$this->container['nome_titolare'] = isset($data['nome_titolare']) ? $data['nome_titolare'] : null;
$this->container['codice_titolare'] = isset($data['codice_titolare']) ? $data['codice_titolare'] : null;
$this->container['iban'] = isset($data['iban']) ? $data['iban'] : null;
$this->container['bic'] = isset($data['bic']) ? $data['bic'] : null;
$this->container['token'] = isset($data['token']) ? $data['token'] : null;
$this->container['mese_token'] = isset($data['mese_token']) ? $data['mese_token'] : null;
$this->container['anno_token'] = isset($data['anno_token']) ? $data['anno_token'] : null;
$this->container['provider_incasso'] = isset($data['provider_incasso']) ? $data['provider_incasso'] : null;
$this->container['carta_prepagata'] = isset($data['carta_prepagata']) ? $data['carta_prepagata'] : null;
$this->container['note'] = isset($data['note']) ? $data['note'] : null;
$this->container['id_capogruppo'] = isset($data['id_capogruppo']) ? $data['id_capogruppo'] : null;
$this->container['tipo_lead'] = isset($data['tipo_lead']) ? $data['tipo_lead'] : null;
$this->container['genera_sostegno'] = isset($data['genera_sostegno']) ? $data['genera_sostegno'] : null;
$this->container['preferenza_continente'] = isset($data['preferenza_continente']) ? $data['preferenza_continente'] : null;
$this->container['preferenza_nazione'] = isset($data['preferenza_nazione']) ? $data['preferenza_nazione'] : null;
$this->container['preferenza_eta_minima'] = isset($data['preferenza_eta_minima']) ? $data['preferenza_eta_minima'] : null;
$this->container['preferenza_eta_massima'] = isset($data['preferenza_eta_massima']) ? $data['preferenza_eta_massima'] : null;
$this->container['preferenza_genere'] = isset($data['preferenza_genere']) ? $data['preferenza_genere'] : null;
$this->container['id_campagna'] = isset($data['id_campagna']) ? $data['id_campagna'] : null;
$this->container['id_centro'] = isset($data['id_centro']) ? $data['id_centro'] : null;
$this->container['gruppo_incassi'] = isset($data['gruppo_incassi']) ? $data['gruppo_incassi'] : null;
$this->container['codice_nazione'] = isset($data['codice_nazione']) ? $data['codice_nazione'] : null;
$this->container['cin_iban'] = isset($data['cin_iban']) ? $data['cin_iban'] : null;
$this->container['cin_bban'] = isset($data['cin_bban']) ? $data['cin_bban'] : null;
$this->container['abi'] = isset($data['abi']) ? $data['abi'] : null;
$this->container['cab'] = isset($data['cab']) ? $data['cab'] : null;
$this->container['conto'] = isset($data['conto']) ? $data['conto'] : null;
$this->container['flag_one_off'] = isset($data['flag_one_off']) ? $data['flag_one_off'] : null;
$this->container['masked_pan'] = isset($data['masked_pan']) ? $data['masked_pan'] : null;
$this->container['numero_carta'] = isset($data['numero_carta']) ? $data['numero_carta'] : null;
$this->container['anno_carta'] = isset($data['anno_carta']) ? $data['anno_carta'] : null;
$this->container['mese_carta'] = isset($data['mese_carta']) ? $data['mese_carta'] : null;
$this->container['data_inizio_sospensione'] = isset($data['data_inizio_sospensione']) ? $data['data_inizio_sospensione'] : null;
$this->container['data_fine_sospensione'] = isset($data['data_fine_sospensione']) ? $data['data_fine_sospensione'] : null;
$this->container['id_motivo_rinuncia'] = isset($data['id_motivo_rinuncia']) ? $data['id_motivo_rinuncia'] : null;
$this->container['data_rinuncia'] = isset($data['data_rinuncia']) ? $data['data_rinuncia'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets id
*
* @return int
*/
public function getId()
{
return $this->container['id'];
}
/**
* Sets id
*
* @param int $id id
*
* @return $this
*/
public function setId($id)
{
$this->container['id'] = $id;
return $this;
}
/**
* Gets codice_donatore
*
* @return string
*/
public function getCodiceDonatore()
{
return $this->container['codice_donatore'];
}
/**
* Sets codice_donatore
*
* @param string $codice_donatore codice_donatore
*
* @return $this
*/
public function setCodiceDonatore($codice_donatore)
{
$this->container['codice_donatore'] = $codice_donatore;
return $this;
}
/**
* Gets codice_soggetto_versante
*
* @return string
*/
public function getCodiceSoggettoVersante()
{
return $this->container['codice_soggetto_versante'];
}
/**
* Sets codice_soggetto_versante
*
* @param string $codice_soggetto_versante codice_soggetto_versante
*
* @return $this
*/
public function setCodiceSoggettoVersante($codice_soggetto_versante)
{
$this->container['codice_soggetto_versante'] = $codice_soggetto_versante;
return $this;
}
/**
* Gets campagna
*
* @return object
*/
public function getCampagna()
{
return $this->container['campagna'];
}
/**
* Sets campagna
*
* @param object $campagna campagna
*
* @return $this
*/
public function setCampagna($campagna)
{
$this->container['campagna'] = $campagna;
return $this;
}
/**
* Gets centro
*
* @return object
*/
public function getCentro()
{
return $this->container['centro'];
}
/**
* Sets centro
*
* @param object $centro centro
*
* @return $this
*/
public function setCentro($centro)
{
$this->container['centro'] = $centro;
return $this;
}
/**
* Gets canale
*
* @return object
*/
public function getCanale()
{
return $this->container['canale'];
}
/**
* Sets canale
*
* @param object $canale canale
*
* @return $this
*/
public function setCanale($canale)
{
$this->container['canale'] = $canale;
return $this;
}
/**
* Gets codice_bambino
*
* @return string
*/
public function getCodiceBambino()
{
return $this->container['codice_bambino'];
}
/**
* Sets codice_bambino
*
* @param string $codice_bambino codice_bambino
*
* @return $this
*/
public function setCodiceBambino($codice_bambino)
{
$this->container['codice_bambino'] = $codice_bambino;
return $this;
}
/**
* Gets progetto
*
* @return object
*/
public function getProgetto()
{
return $this->container['progetto'];
}
/**
* Sets progetto
*
* @param object $progetto progetto
*
* @return $this
*/
public function setProgetto($progetto)
{
$this->container['progetto'] = $progetto;
return $this;
}
/**
* Gets tema
*
* @return object
*/
public function getTema()
{
return $this->container['tema'];
}
/**
* Sets tema
*
* @param object $tema tema
*
* @return $this
*/
public function setTema($tema)
{
$this->container['tema'] = $tema;
return $this;
}
/**
* Gets stato
*
* @return object
*/
public function getStato()
{
return $this->container['stato'];
}
/**
* Sets stato
*
* @param object $stato stato
*
* @return $this
*/
public function setStato($stato)
{
$this->container['stato'] = $stato;
return $this;
}
/**
* Gets importo
*
* @return float
*/
public function getImporto()
{
return $this->container['importo'];
}
/**
* Sets importo
*
* @param float $importo importo
*
* @return $this
*/
public function setImporto($importo)
{
$this->container['importo'] = $importo;
return $this;
}
/**
* Gets frequenza
*
* @return int
*/
public function getFrequenza()
{
return $this->container['frequenza'];
}
/**
* Sets frequenza
*
* @param int $frequenza frequenza
*
* @return $this
*/
public function setFrequenza($frequenza)
{
$this->container['frequenza'] = $frequenza;
return $this;
}
/**
* Gets metodo_pagamento
*
* @return object
*/
public function getMetodoPagamento()
{
return $this->container['metodo_pagamento'];
}
/**
* Sets metodo_pagamento
*
* @param object $metodo_pagamento metodo_pagamento
*
* @return $this
*/
public function setMetodoPagamento($metodo_pagamento)
{
$this->container['metodo_pagamento'] = $metodo_pagamento;
return $this;
}
/**
* Gets data_richiesta
*
* @return string
*/
public function getDataRichiesta()
{
return $this->container['data_richiesta'];
}
/**
* Sets data_richiesta
*
* @param string $data_richiesta data_richiesta
*
* @return $this
*/
public function setDataRichiesta($data_richiesta)
{
$this->container['data_richiesta'] = $data_richiesta;
return $this;
}
/**
* Gets ora_richiesta
*
* @return string
*/
public function getOraRichiesta()
{
return $this->container['ora_richiesta'];
}
/**
* Sets ora_richiesta
*
* @param string $ora_richiesta ora_richiesta
*
* @return $this
*/
public function setOraRichiesta($ora_richiesta)
{
$this->container['ora_richiesta'] = $ora_richiesta;
return $this;
}
/**
* Gets data_delega
*
* @return string
*/
public function getDataDelega()
{
return $this->container['data_delega'];
}
/**
* Sets data_delega
*
* @param string $data_delega data_delega
*
* @return $this
*/
public function setDataDelega($data_delega)
{
$this->container['data_delega'] = $data_delega;
return $this;
}
/**
* Gets data_promessa
*
* @return string
*/
public function getDataPromessa()
{
return $this->container['data_promessa'];
}
/**
* Sets data_promessa
*
* @param string $data_promessa data_promessa
*
* @return $this
*/
public function setDataPromessa($data_promessa)
{
$this->container['data_promessa'] = $data_promessa;
return $this;
}
/**
* Gets data_prossima_richiesta
*
* @return string
*/
public function getDataProssimaRichiesta()
{
return $this->container['data_prossima_richiesta'];
}
/**
* Sets data_prossima_richiesta
*
* @param string $data_prossima_richiesta data_prossima_richiesta
*
* @return $this
*/
public function setDataProssimaRichiesta($data_prossima_richiesta)
{
$this->container['data_prossima_richiesta'] = $data_prossima_richiesta;
return $this;
}
/**
* Gets codice_dialogatore_interno
*
* @return string
*/
public function getCodiceDialogatoreInterno()
{
return $this->container['codice_dialogatore_interno'];
}
/**
* Sets codice_dialogatore_interno
*
* @param string $codice_dialogatore_interno codice_dialogatore_interno
*
* @return $this
*/
public function setCodiceDialogatoreInterno($codice_dialogatore_interno)
{
$this->container['codice_dialogatore_interno'] = $codice_dialogatore_interno;
return $this;
}
/**
* Gets codice_dialogatore_esterno
*
* @return string
*/
public function getCodiceDialogatoreEsterno()
{
return $this->container['codice_dialogatore_esterno'];
}
/**
* Sets codice_dialogatore_esterno
*
* @param string $codice_dialogatore_esterno codice_dialogatore_esterno
*
* @return $this
*/
public function setCodiceDialogatoreEsterno($codice_dialogatore_esterno)
{
$this->container['codice_dialogatore_esterno'] = $codice_dialogatore_esterno;
return $this;
}
/**
* Gets nome_dialogatore_esterno
*
* @return string
*/
public function getNomeDialogatoreEsterno()
{
return $this->container['nome_dialogatore_esterno'];
}
/**
* Sets nome_dialogatore_esterno
*
* @param string $nome_dialogatore_esterno nome_dialogatore_esterno
*
* @return $this
*/
public function setNomeDialogatoreEsterno($nome_dialogatore_esterno)
{
$this->container['nome_dialogatore_esterno'] = $nome_dialogatore_esterno;
return $this;
}
/**
* Gets urn
*
* @return string
*/
public function getUrn()
{
return $this->container['urn'];
}
/**
* Sets urn
*
* @param string $urn urn
*
* @return $this
*/
public function setUrn($urn)
{
$this->container['urn'] = $urn;
return $this;
}
/**
* Gets url
*
* @return string
*/
public function getUrl()
{
return $this->container['url'];
}
/**
* Sets url
*
* @param string $url url
*
* @return $this
*/
public function setUrl($url)
{
$this->container['url'] = $url;
return $this;
}
/**
* Gets lotto
*
* @return string
*/
public function getLotto()
{
return $this->container['lotto'];
}
/**
* Sets lotto
*
* @param string $lotto lotto
*
* @return $this
*/
public function setLotto($lotto)
{
$this->container['lotto'] = $lotto;
return $this;
}
/**
* Gets locazione
*
* @return string
*/
public function getLocazione()
{
return $this->container['locazione'];
}
/**
* Sets locazione
*
* @param string $locazione locazione
*
* @return $this
*/
public function setLocazione($locazione)
{
$this->container['locazione'] = $locazione;
return $this;
}
/**
* Gets citta_locazione
*
* @return string
*/
public function getCittaLocazione()
{
return $this->container['citta_locazione'];
}
/**
* Sets citta_locazione
*
* @param string $citta_locazione citta_locazione
*
* @return $this
*/
public function setCittaLocazione($citta_locazione)
{
$this->container['citta_locazione'] = $citta_locazione;
return $this;
}
/**
* Gets nome_titolare
*
* @return string
*/
public function getNomeTitolare()
{
return $this->container['nome_titolare'];
}
/**
* Sets nome_titolare
*
* @param string $nome_titolare nome_titolare
*
* @return $this
*/
public function setNomeTitolare($nome_titolare)
{
$this->container['nome_titolare'] = $nome_titolare;
return $this;
}
/**
* Gets codice_titolare
*
* @return string
*/
public function getCodiceTitolare()
{
return $this->container['codice_titolare'];
}
/**
* Sets codice_titolare
*
* @param string $codice_titolare codice_titolare
*
* @return $this
*/
public function setCodiceTitolare($codice_titolare)
{
$this->container['codice_titolare'] = $codice_titolare;
return $this;
}
/**
* Gets iban
*
* @return string
*/
public function getIban()
{
return $this->container['iban'];
}
/**
* Sets iban
*
* @param string $iban iban
*
* @return $this
*/
public function setIban($iban)
{
$this->container['iban'] = $iban;
return $this;
}
/**
* Gets bic
*
* @return string
*/
public function getBic()
{
return $this->container['bic'];
}
/**
* Sets bic
*
* @param string $bic bic
*
* @return $this
*/
public function setBic($bic)
{
$this->container['bic'] = $bic;
return $this;
}
/**
* Gets token
*
* @return string
*/
public function getToken()
{
return $this->container['token'];
}
/**
* Sets token
*
* @param string $token token
*
* @return $this
*/
public function setToken($token)
{
$this->container['token'] = $token;
return $this;
}
/**
* Gets mese_token
*
* @return string
*/
public function getMeseToken()
{
return $this->container['mese_token'];
}
/**
* Sets mese_token
*
* @param string $mese_token mese_token
*
* @return $this
*/
public function setMeseToken($mese_token)
{
$this->container['mese_token'] = $mese_token;
return $this;
}
/**
* Gets anno_token
*
* @return string
*/
public function getAnnoToken()
{
return $this->container['anno_token'];
}
/**
* Sets anno_token
*
* @param string $anno_token anno_token
*
* @return $this
*/
public function setAnnoToken($anno_token)
{
$this->container['anno_token'] = $anno_token;
return $this;
}
/**
* Gets provider_incasso
*
* @return string
*/
public function getProviderIncasso()
{
return $this->container['provider_incasso'];
}
/**
* Sets provider_incasso
*
* @param string $provider_incasso provider_incasso
*
* @return $this
*/
public function setProviderIncasso($provider_incasso)
{
$this->container['provider_incasso'] = $provider_incasso;
return $this;
}
/**
* Gets carta_prepagata
*
* @return bool
*/
public function getCartaPrepagata()
{
return $this->container['carta_prepagata'];
}
/**
* Sets carta_prepagata
*
* @param bool $carta_prepagata carta_prepagata
*
* @return $this
*/
public function setCartaPrepagata($carta_prepagata)
{
$this->container['carta_prepagata'] = $carta_prepagata;
return $this;
}
/**
* Gets note
*
* @return string
*/
public function getNote()
{
return $this->container['note'];
}
/**
* Sets note
*
* @param string $note note
*
* @return $this
*/
public function setNote($note)
{
$this->container['note'] = $note;
return $this;
}
/**
* Gets id_capogruppo
*
* @return int
*/
public function getIdCapogruppo()
{
return $this->container['id_capogruppo'];
}
/**
* Sets id_capogruppo
*
* @param int $id_capogruppo id_capogruppo
*
* @return $this
*/
public function setIdCapogruppo($id_capogruppo)
{
$this->container['id_capogruppo'] = $id_capogruppo;
return $this;
}
/**
* Gets tipo_lead
*
* @return string
*/
public function getTipoLead()
{
return $this->container['tipo_lead'];
}
/**
* Sets tipo_lead
*
* @param string $tipo_lead tipo_lead
*
* @return $this
*/
public function setTipoLead($tipo_lead)
{
$this->container['tipo_lead'] = $tipo_lead;
return $this;
}
/**
* Gets genera_sostegno
*
* @return bool
*/
public function getGeneraSostegno()
{
return $this->container['genera_sostegno'];
}
/**
* Sets genera_sostegno
*
* @param bool $genera_sostegno genera_sostegno
*
* @return $this
*/
public function setGeneraSostegno($genera_sostegno)
{
$this->container['genera_sostegno'] = $genera_sostegno;
return $this;
}
/**
* Gets preferenza_continente
*
* @return string
*/
public function getPreferenzaContinente()
{
return $this->container['preferenza_continente'];
}
/**
* Sets preferenza_continente
*
* @param string $preferenza_continente preferenza_continente
*
* @return $this
*/
public function setPreferenzaContinente($preferenza_continente)
{
$this->container['preferenza_continente'] = $preferenza_continente;
return $this;
}
/**
* Gets preferenza_nazione
*
* @return string
*/
public function getPreferenzaNazione()
{
return $this->container['preferenza_nazione'];
}
/**
* Sets preferenza_nazione
*
* @param string $preferenza_nazione preferenza_nazione
*
* @return $this
*/
public function setPreferenzaNazione($preferenza_nazione)
{
$this->container['preferenza_nazione'] = $preferenza_nazione;
return $this;
}
/**
* Gets preferenza_eta_minima
*
* @return string
*/
public function getPreferenzaEtaMinima()
{
return $this->container['preferenza_eta_minima'];
}
/**
* Sets preferenza_eta_minima
*
* @param string $preferenza_eta_minima preferenza_eta_minima
*
* @return $this
*/
public function setPreferenzaEtaMinima($preferenza_eta_minima)
{
$this->container['preferenza_eta_minima'] = $preferenza_eta_minima;
return $this;
}
/**
* Gets preferenza_eta_massima
*
* @return string
*/
public function getPreferenzaEtaMassima()
{
return $this->container['preferenza_eta_massima'];
}
/**
* Sets preferenza_eta_massima
*
* @param string $preferenza_eta_massima preferenza_eta_massima
*
* @return $this
*/
public function setPreferenzaEtaMassima($preferenza_eta_massima)
{
$this->container['preferenza_eta_massima'] = $preferenza_eta_massima;
return $this;
}
/**
* Gets preferenza_genere
*
* @return string
*/
public function getPreferenzaGenere()
{
return $this->container['preferenza_genere'];
}
/**
* Sets preferenza_genere
*
* @param string $preferenza_genere preferenza_genere
*
* @return $this
*/
public function setPreferenzaGenere($preferenza_genere)
{
$this->container['preferenza_genere'] = $preferenza_genere;
return $this;
}
/**
* Gets id_campagna
*
* @return int
*/
public function getIdCampagna()
{
return $this->container['id_campagna'];
}
/**
* Sets id_campagna
*
* @param int $id_campagna id_campagna
*
* @return $this
*/
public function setIdCampagna($id_campagna)
{
$this->container['id_campagna'] = $id_campagna;
return $this;
}
/**
* Gets id_centro
*
* @return int
*/
public function getIdCentro()
{
return $this->container['id_centro'];
}
/**
* Sets id_centro
*
* @param int $id_centro id_centro
*
* @return $this
*/
public function setIdCentro($id_centro)
{
$this->container['id_centro'] = $id_centro;
return $this;
}
/**
* Gets gruppo_incassi
*
* @return int
*/
public function getGruppoIncassi()
{
return $this->container['gruppo_incassi'];
}
/**
* Sets gruppo_incassi
*
* @param int $gruppo_incassi gruppo_incassi
*
* @return $this
*/
public function setGruppoIncassi($gruppo_incassi)
{
$this->container['gruppo_incassi'] = $gruppo_incassi;
return $this;
}
/**
* Gets codice_nazione
*
* @return string
*/
public function getCodiceNazione()
{
return $this->container['codice_nazione'];
}
/**
* Sets codice_nazione
*
* @param string $codice_nazione codice_nazione
*
* @return $this
*/
public function setCodiceNazione($codice_nazione)
{
$this->container['codice_nazione'] = $codice_nazione;
return $this;
}
/**
* Gets cin_iban
*
* @return string
*/
public function getCinIban()
{
return $this->container['cin_iban'];
}
/**
* Sets cin_iban
*
* @param string $cin_iban cin_iban
*
* @return $this
*/
public function setCinIban($cin_iban)
{
$this->container['cin_iban'] = $cin_iban;
return $this;
}
/**
* Gets cin_bban
*
* @return string
*/
public function getCinBban()
{
return $this->container['cin_bban'];
}
/**
* Sets cin_bban
*
* @param string $cin_bban cin_bban
*
* @return $this
*/
public function setCinBban($cin_bban)
{
$this->container['cin_bban'] = $cin_bban;
return $this;
}
/**
* Gets abi
*
* @return string
*/
public function getAbi()
{
return $this->container['abi'];
}
/**
* Sets abi
*
* @param string $abi abi
*
* @return $this
*/
public function setAbi($abi)
{
$this->container['abi'] = $abi;
return $this;
}
/**
* Gets cab
*
* @return string
*/
public function getCab()
{
return $this->container['cab'];
}
/**
* Sets cab
*
* @param string $cab cab
*
* @return $this
*/
public function setCab($cab)
{
$this->container['cab'] = $cab;
return $this;
}
/**
* Gets conto
*
* @return string
*/
public function getConto()
{
return $this->container['conto'];
}
/**
* Sets conto
*
* @param string $conto conto
*
* @return $this
*/
public function setConto($conto)
{
$this->container['conto'] = $conto;
return $this;
}
/**
* Gets flag_one_off
*
* @return string
*/
public function getFlagOneOff()
{
return $this->container['flag_one_off'];
}
/**
* Sets flag_one_off
*
* @param string $flag_one_off flag_one_off
*
* @return $this
*/
public function setFlagOneOff($flag_one_off)
{
$this->container['flag_one_off'] = $flag_one_off;
return $this;
}
/**
* Gets masked_pan
*
* @return string
*/
public function getMaskedPan()
{
return $this->container['masked_pan'];
}
/**
* Sets masked_pan
*
* @param string $masked_pan masked_pan
*
* @return $this
*/
public function setMaskedPan($masked_pan)
{
$this->container['masked_pan'] = $masked_pan;
return $this;
}
/**
* Gets numero_carta
*
* @return string
*/
public function getNumeroCarta()
{
return $this->container['numero_carta'];
}
/**
* Sets numero_carta
*
* @param string $numero_carta numero_carta
*
* @return $this
*/
public function setNumeroCarta($numero_carta)
{
$this->container['numero_carta'] = $numero_carta;
return $this;
}
/**
* Gets anno_carta
*
* @return int
*/
public function getAnnoCarta()
{
return $this->container['anno_carta'];
}
/**
* Sets anno_carta
*
* @param int $anno_carta anno_carta
*
* @return $this
*/
public function setAnnoCarta($anno_carta)
{
$this->container['anno_carta'] = $anno_carta;
return $this;
}
/**
* Gets mese_carta
*
* @return int
*/
public function getMeseCarta()
{
return $this->container['mese_carta'];
}
/**
* Sets mese_carta
*
* @param int $mese_carta mese_carta
*
* @return $this
*/
public function setMeseCarta($mese_carta)
{
$this->container['mese_carta'] = $mese_carta;
return $this;
}
/**
* Gets data_inizio_sospensione
*
* @return string
*/
public function getDataInizioSospensione()
{
return $this->container['data_inizio_sospensione'];
}
/**
* Sets data_inizio_sospensione
*
* @param string $data_inizio_sospensione data_inizio_sospensione
*
* @return $this
*/
public function setDataInizioSospensione($data_inizio_sospensione)
{
$this->container['data_inizio_sospensione'] = $data_inizio_sospensione;
return $this;
}
/**
* Gets data_fine_sospensione
*
* @return string
*/
public function getDataFineSospensione()
{
return $this->container['data_fine_sospensione'];
}
/**
* Sets data_fine_sospensione
*
* @param string $data_fine_sospensione data_fine_sospensione
*
* @return $this
*/
public function setDataFineSospensione($data_fine_sospensione)
{
$this->container['data_fine_sospensione'] = $data_fine_sospensione;
return $this;
}
/**
* Gets id_motivo_rinuncia
*
* @return int
*/
public function getIdMotivoRinuncia()
{
return $this->container['id_motivo_rinuncia'];
}
/**
* Sets id_motivo_rinuncia
*
* @param int $id_motivo_rinuncia id_motivo_rinuncia
*
* @return $this
*/
public function setIdMotivoRinuncia($id_motivo_rinuncia)
{
$this->container['id_motivo_rinuncia'] = $id_motivo_rinuncia;
return $this;
}
/**
* Gets data_rinuncia
*
* @return string
*/
public function getDataRinuncia()
{
return $this->container['data_rinuncia'];
}
/**
* Sets data_rinuncia
*
* @param string $data_rinuncia data_rinuncia
*
* @return $this
*/
public function setDataRinuncia($data_rinuncia)
{
$this->container['data_rinuncia'] = $data_rinuncia;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep># Swagger\Client\AnagraficaApi
All URIs are relative to *https://dc.directchannel.it/ApiRest*
Method | HTTP request | Description
------------- | ------------- | -------------
[**anagraficaGet**](AnagraficaApi.md#anagraficaGet) | **GET** /v1/api/Anagrafica/Get |
[**anagraficaInsertCliente**](AnagraficaApi.md#anagraficaInsertCliente) | **POST** /v1/api/Anagrafica/InsertCliente |
[**anagraficaUpdateCliente**](AnagraficaApi.md#anagraficaUpdateCliente) | **POST** /v1/api/Anagrafica/UpdateCliente |
# **anagraficaGet**
> \Swagger\Client\Model\Clienti anagraficaGet($cl_codice)
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new Swagger\Client\Api\AnagraficaApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$cl_codice = "cl_codice_example"; // string |
try {
$result = $apiInstance->anagraficaGet($cl_codice);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling AnagraficaApi->anagraficaGet: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**cl_codice** | **string**| |
### Return type
[**\Swagger\Client\Model\Clienti**](../Model/Clienti.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json, text/json, application/xml, text/xml
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **anagraficaInsertCliente**
> \Swagger\Client\Model\Clienti[] anagraficaInsertCliente($raw_string, $controllo, $ambiente)
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new Swagger\Client\Api\AnagraficaApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$raw_string = array(new \Swagger\Client\Model\Clienti()); // \Swagger\Client\Model\Clienti[] |
$controllo = true; // bool |
$ambiente = "ambiente_example"; // string |
try {
$result = $apiInstance->anagraficaInsertCliente($raw_string, $controllo, $ambiente);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling AnagraficaApi->anagraficaInsertCliente: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**raw_string** | [**\Swagger\Client\Model\Clienti[]**](../Model/Clienti.md)| |
**controllo** | **bool**| | [optional]
**ambiente** | **string**| | [optional]
### Return type
[**\Swagger\Client\Model\Clienti[]**](../Model/Clienti.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json, text/json, application/xml, text/xml, application/x-www-form-urlencoded
- **Accept**: application/json, text/json, application/xml, text/xml
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **anagraficaUpdateCliente**
> \Swagger\Client\Model\Clienti[] anagraficaUpdateCliente($raw_string, $ambiente)
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new Swagger\Client\Api\AnagraficaApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$raw_string = array(new \Swagger\Client\Model\Clienti()); // \Swagger\Client\Model\Clienti[] |
$ambiente = "ambiente_example"; // string |
try {
$result = $apiInstance->anagraficaUpdateCliente($raw_string, $ambiente);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling AnagraficaApi->anagraficaUpdateCliente: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**raw_string** | [**\Swagger\Client\Model\Clienti[]**](../Model/Clienti.md)| |
**ambiente** | **string**| | [optional]
### Return type
[**\Swagger\Client\Model\Clienti[]**](../Model/Clienti.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json, text/json, application/xml, text/xml, application/x-www-form-urlencoded
- **Accept**: application/json, text/json, application/xml, text/xml
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
<file_sep># Clienti
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**codice** | **string** | | [optional]
**codice_origine** | **string** | | [optional]
**tipo_master** | **object** | | [optional]
**codice_master** | **string** | | [optional]
**codice_web** | **string** | | [optional]
**codice_presentatore** | **string** | | [optional]
**tipo** | **object** | | [optional]
**sottotipo** | **object** | | [optional]
**fonte** | **object** | | [optional]
**lista_origine** | **object** | | [optional]
**codice_manifestazione** | **string** | | [optional]
**id_appellativo** | **int** | | [optional]
**titolo** | **string** | | [optional]
**data_raccolta** | **string** | | [optional]
**lotto** | **string** | | [optional]
**nome** | **string** | | [optional]
**cognome** | **string** | | [optional]
**ragione_sociale** | **string** | | [optional]
**genere** | **string** | | [optional]
**data_nascita** | **string** | | [optional]
**luogo_nascita** | **string** | | [optional]
**codice_fiscale** | **string** | | [optional]
**partita_iva** | **string** | | [optional]
**email1** | **string** | | [optional]
**email2** | **string** | | [optional]
**telefono1** | **string** | | [optional]
**telefono2** | **string** | | [optional]
**cellulare1** | **string** | | [optional]
**cellulare2** | **string** | | [optional]
**presso** | **string** | | [optional]
**dug** | **string** | | [optional]
**duf** | **string** | | [optional]
**civico** | **string** | | [optional]
**altro_civico** | **string** | | [optional]
**frazione** | **string** | | [optional]
**localita** | **string** | | [optional]
**provincia** | **string** | | [optional]
**cap** | **string** | | [optional]
**codice_nazione** | **string** | | [optional]
**indirizzi** | [**\Swagger\Client\Model\ClientiIndirizzi[]**](ClientiIndirizzi.md) | | [optional]
**recapiti** | [**\Swagger\Client\Model\ClientiRecapiti[]**](ClientiRecapiti.md) | | [optional]
**campagna** | **object** | | [optional]
**id_campagna** | **int** | | [optional]
**professione** | **object** | | [optional]
**titolo_studio** | **object** | | [optional]
**figli** | **string** | | [optional]
**codice_tessera** | **string** | | [optional]
**evento** | **string** | | [optional]
**data_scadenza_tessera** | **string** | | [optional]
**data_emissione_tessera** | **string** | | [optional]
**flag_emissione_tessera** | **bool** | | [optional]
**privacy** | [**\Swagger\Client\Model\ClientiPrivacy[]**](ClientiPrivacy.md) | | [optional]
**specifiche** | [**\Swagger\Client\Model\ClientiSpecifiche[]**](ClientiSpecifiche.md) | | [optional]
**profilazioni** | [**\Swagger\Client\Model\ClientiProfilazioni[]**](ClientiProfilazioni.md) | | [optional]
**subscriptions** | [**\Swagger\Client\Model\ClientiSubscription[]**](ClientiSubscription.md) | | [optional]
**gruppi** | [**\Swagger\Client\Model\ClientiGruppi[]**](ClientiGruppi.md) | | [optional]
**flag_deceduto** | **bool** | | [optional]
**_data_decesso** | **int** | | [optional]
**data_decesso** | **string** | | [optional]
**utente** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep><?php
/**
* AttivitaTest
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace Swagger\Client;
/**
* AttivitaTest Class Doc Comment
*
* @category Class
* @description Attivita
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class AttivitaTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "Attivita"
*/
public function testAttivita()
{
}
/**
* Test attribute "id_attivita"
*/
public function testPropertyIdAttivita()
{
}
/**
* Test attribute "id_regolare"
*/
public function testPropertyIdRegolare()
{
}
/**
* Test attribute "id_versamenti"
*/
public function testPropertyIdVersamenti()
{
}
/**
* Test attribute "codice_donatore"
*/
public function testPropertyCodiceDonatore()
{
}
/**
* Test attribute "campagna"
*/
public function testPropertyCampagna()
{
}
/**
* Test attribute "canale"
*/
public function testPropertyCanale()
{
}
/**
* Test attribute "pagamento"
*/
public function testPropertyPagamento()
{
}
/**
* Test attribute "bambino"
*/
public function testPropertyBambino()
{
}
/**
* Test attribute "progetto"
*/
public function testPropertyProgetto()
{
}
/**
* Test attribute "esito"
*/
public function testPropertyEsito()
{
}
/**
* Test attribute "id_lascito"
*/
public function testPropertyIdLascito()
{
}
/**
* Test attribute "data_attivita"
*/
public function testPropertyDataAttivita()
{
}
/**
* Test attribute "ora_attivita"
*/
public function testPropertyOraAttivita()
{
}
/**
* Test attribute "utente_assegnatario"
*/
public function testPropertyUtenteAssegnatario()
{
}
/**
* Test attribute "gruppo_utenti_assegnatario"
*/
public function testPropertyGruppoUtentiAssegnatario()
{
}
/**
* Test attribute "id_gruppo"
*/
public function testPropertyIdGruppo()
{
}
/**
* Test attribute "evento"
*/
public function testPropertyEvento()
{
}
/**
* Test attribute "sollecito"
*/
public function testPropertySollecito()
{
}
/**
* Test attribute "motivo_rifiuto_ask"
*/
public function testPropertyMotivoRifiutoAsk()
{
}
/**
* Test attribute "tipo_incidenza"
*/
public function testPropertyTipoIncidenza()
{
}
/**
* Test attribute "tipo"
*/
public function testPropertyTipo()
{
}
/**
* Test attribute "sottotipo"
*/
public function testPropertySottotipo()
{
}
/**
* Test attribute "stato"
*/
public function testPropertyStato()
{
}
/**
* Test attribute "importo"
*/
public function testPropertyImporto()
{
}
/**
* Test attribute "oggetto"
*/
public function testPropertyOggetto()
{
}
/**
* Test attribute "note"
*/
public function testPropertyNote()
{
}
/**
* Test attribute "data_chiusura"
*/
public function testPropertyDataChiusura()
{
}
/**
* Test attribute "link"
*/
public function testPropertyLink()
{
}
/**
* Test attribute "lotto"
*/
public function testPropertyLotto()
{
}
/**
* Test attribute "template"
*/
public function testPropertyTemplate()
{
}
}
<file_sep><?php
/**
* CallRegolare
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace Swagger\Client\Model;
use \ArrayAccess;
use \Swagger\Client\ObjectSerializer;
/**
* CallRegolare Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class CallRegolare implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'CallRegolare';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'id_regolare' => 'string',
'codice_esito' => 'string',
'codice_motivo_rinuncia' => 'string',
'data_rinuncia' => 'string',
'codice_campagna' => 'string',
'importo' => 'string',
'frequenza' => 'string',
'stato' => 'string'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'id_regolare' => null,
'codice_esito' => null,
'codice_motivo_rinuncia' => null,
'data_rinuncia' => null,
'codice_campagna' => null,
'importo' => null,
'frequenza' => null,
'stato' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'id_regolare' => 'idRegolare',
'codice_esito' => 'codiceEsito',
'codice_motivo_rinuncia' => 'codiceMotivoRinuncia',
'data_rinuncia' => 'dataRinuncia',
'codice_campagna' => 'codiceCampagna',
'importo' => 'importo',
'frequenza' => 'frequenza',
'stato' => 'stato'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'id_regolare' => 'setIdRegolare',
'codice_esito' => 'setCodiceEsito',
'codice_motivo_rinuncia' => 'setCodiceMotivoRinuncia',
'data_rinuncia' => 'setDataRinuncia',
'codice_campagna' => 'setCodiceCampagna',
'importo' => 'setImporto',
'frequenza' => 'setFrequenza',
'stato' => 'setStato'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'id_regolare' => 'getIdRegolare',
'codice_esito' => 'getCodiceEsito',
'codice_motivo_rinuncia' => 'getCodiceMotivoRinuncia',
'data_rinuncia' => 'getDataRinuncia',
'codice_campagna' => 'getCodiceCampagna',
'importo' => 'getImporto',
'frequenza' => 'getFrequenza',
'stato' => 'getStato'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['id_regolare'] = isset($data['id_regolare']) ? $data['id_regolare'] : null;
$this->container['codice_esito'] = isset($data['codice_esito']) ? $data['codice_esito'] : null;
$this->container['codice_motivo_rinuncia'] = isset($data['codice_motivo_rinuncia']) ? $data['codice_motivo_rinuncia'] : null;
$this->container['data_rinuncia'] = isset($data['data_rinuncia']) ? $data['data_rinuncia'] : null;
$this->container['codice_campagna'] = isset($data['codice_campagna']) ? $data['codice_campagna'] : null;
$this->container['importo'] = isset($data['importo']) ? $data['importo'] : null;
$this->container['frequenza'] = isset($data['frequenza']) ? $data['frequenza'] : null;
$this->container['stato'] = isset($data['stato']) ? $data['stato'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets id_regolare
*
* @return string
*/
public function getIdRegolare()
{
return $this->container['id_regolare'];
}
/**
* Sets id_regolare
*
* @param string $id_regolare id_regolare
*
* @return $this
*/
public function setIdRegolare($id_regolare)
{
$this->container['id_regolare'] = $id_regolare;
return $this;
}
/**
* Gets codice_esito
*
* @return string
*/
public function getCodiceEsito()
{
return $this->container['codice_esito'];
}
/**
* Sets codice_esito
*
* @param string $codice_esito codice_esito
*
* @return $this
*/
public function setCodiceEsito($codice_esito)
{
$this->container['codice_esito'] = $codice_esito;
return $this;
}
/**
* Gets codice_motivo_rinuncia
*
* @return string
*/
public function getCodiceMotivoRinuncia()
{
return $this->container['codice_motivo_rinuncia'];
}
/**
* Sets codice_motivo_rinuncia
*
* @param string $codice_motivo_rinuncia codice_motivo_rinuncia
*
* @return $this
*/
public function setCodiceMotivoRinuncia($codice_motivo_rinuncia)
{
$this->container['codice_motivo_rinuncia'] = $codice_motivo_rinuncia;
return $this;
}
/**
* Gets data_rinuncia
*
* @return string
*/
public function getDataRinuncia()
{
return $this->container['data_rinuncia'];
}
/**
* Sets data_rinuncia
*
* @param string $data_rinuncia data_rinuncia
*
* @return $this
*/
public function setDataRinuncia($data_rinuncia)
{
$this->container['data_rinuncia'] = $data_rinuncia;
return $this;
}
/**
* Gets codice_campagna
*
* @return string
*/
public function getCodiceCampagna()
{
return $this->container['codice_campagna'];
}
/**
* Sets codice_campagna
*
* @param string $codice_campagna codice_campagna
*
* @return $this
*/
public function setCodiceCampagna($codice_campagna)
{
$this->container['codice_campagna'] = $codice_campagna;
return $this;
}
/**
* Gets importo
*
* @return string
*/
public function getImporto()
{
return $this->container['importo'];
}
/**
* Sets importo
*
* @param string $importo importo
*
* @return $this
*/
public function setImporto($importo)
{
$this->container['importo'] = $importo;
return $this;
}
/**
* Gets frequenza
*
* @return string
*/
public function getFrequenza()
{
return $this->container['frequenza'];
}
/**
* Sets frequenza
*
* @param string $frequenza frequenza
*
* @return $this
*/
public function setFrequenza($frequenza)
{
$this->container['frequenza'] = $frequenza;
return $this;
}
/**
* Gets stato
*
* @return string
*/
public function getStato()
{
return $this->container['stato'];
}
/**
* Sets stato
*
* @param string $stato stato
*
* @return $this
*/
public function setStato($stato)
{
$this->container['stato'] = $stato;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep># Swagger\Client\TokenApi
All URIs are relative to *https://dc.directchannel.it/ApiRest*
Method | HTTP request | Description
------------- | ------------- | -------------
[**tokenAutenticationGet**](TokenApi.md#tokenAutenticationGet) | **GET** /v1/api/Token/autentication |
[**tokenGet**](TokenApi.md#tokenGet) | **GET** /v1/api/Token |
[**tokenVerifiToken**](TokenApi.md#tokenVerifiToken) | **GET** /v1/api/Token/verify |
# **tokenAutenticationGet**
> string tokenAutenticationGet($utente, $chiave, $ambiente)
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new Swagger\Client\Api\TokenApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
$utente = "utente_example"; // string |
$chiave = "chiave_example"; // string |
$ambiente = "ambiente_example"; // string |
try {
$result = $apiInstance->tokenAutenticationGet($utente, $chiave, $ambiente);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling TokenApi->tokenAutenticationGet: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**utente** | **string**| |
**chiave** | **string**| |
**ambiente** | **string**| |
### Return type
**string**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json, text/json, application/xml, text/xml
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **tokenGet**
> object tokenGet()
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new Swagger\Client\Api\TokenApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
try {
$result = $apiInstance->tokenGet();
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling TokenApi->tokenGet: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
This endpoint does not need any parameter.
### Return type
**object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json, text/json, application/xml, text/xml
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
# **tokenVerifiToken**
> object tokenVerifiToken()
### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$apiInstance = new Swagger\Client\Api\TokenApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client()
);
try {
$result = $apiInstance->tokenVerifiToken();
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling TokenApi->tokenVerifiToken: ', $e->getMessage(), PHP_EOL;
}
?>
```
### Parameters
This endpoint does not need any parameter.
### Return type
**object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json, text/json, application/xml, text/xml
[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
<file_sep># ClientiProfilazioni
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id_cliente** | **int** | | [optional]
**codice** | **string** | | [optional]
**campagna** | **string** | | [optional]
**descrizione** | **string** | | [optional]
**dalla_data** | **string** | | [optional]
**alla_data** | **string** | | [optional]
**id_ranking** | **int** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep># Versamento
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id_versamento** | **int** | | [optional]
**id_regolare** | **int** | | [optional]
**id_web** | **string** | | [optional]
**codice_cliente** | **string** | | [optional]
**codice_soggetto_versante** | **string** | | [optional]
**codice_centro_ricavo** | **string** | | [optional]
**codice_partner** | **string** | | [optional]
**codice_riferimento** | **string** | | [optional]
**campagna** | **object** | | [optional]
**centro** | **object** | | [optional]
**canale** | **object** | | [optional]
**bambino** | **object** | | [optional]
**progetto** | **object** | | [optional]
**conto** | **object** | | [optional]
**evento** | **object** | | [optional]
**codice_transazione** | **string** | | [optional]
**importo** | **float** | | [optional]
**metodo** | **string** | | [optional]
**descrizione_metodo** | **string** | | [optional]
**data_operazione** | **string** | | [optional]
**data_valuta** | **string** | | [optional]
**note** | **string** | | [optional]
**tipo** | **object** | | [optional]
**sotto_tipo** | **object** | | [optional]
**lotto** | **string** | | [optional]
**escludi_attestato** | **string** | | [optional]
**flag_one_off** | **bool** | | [optional]
**prodotti** | [**\Swagger\Client\Model\VersamentoProdotti[]**](VersamentoProdotti.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep># Periodici
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **int** | | [optional]
**codice_donatore** | **string** | | [optional]
**codice_soggetto_versante** | **string** | | [optional]
**campagna** | **object** | | [optional]
**centro** | **object** | | [optional]
**canale** | **object** | | [optional]
**codice_bambino** | **string** | | [optional]
**progetto** | **object** | | [optional]
**tema** | **object** | | [optional]
**stato** | **object** | | [optional]
**importo** | **float** | | [optional]
**frequenza** | **int** | | [optional]
**metodo_pagamento** | **object** | | [optional]
**data_richiesta** | **string** | | [optional]
**ora_richiesta** | **string** | | [optional]
**data_delega** | **string** | | [optional]
**data_promessa** | **string** | | [optional]
**data_prossima_richiesta** | **string** | | [optional]
**codice_dialogatore_interno** | **string** | | [optional]
**codice_dialogatore_esterno** | **string** | | [optional]
**nome_dialogatore_esterno** | **string** | | [optional]
**urn** | **string** | | [optional]
**url** | **string** | | [optional]
**lotto** | **string** | | [optional]
**locazione** | **string** | | [optional]
**citta_locazione** | **string** | | [optional]
**nome_titolare** | **string** | | [optional]
**codice_titolare** | **string** | | [optional]
**iban** | **string** | | [optional]
**bic** | **string** | | [optional]
**token** | **string** | | [optional]
**mese_token** | **string** | | [optional]
**anno_token** | **string** | | [optional]
**provider_incasso** | **string** | | [optional]
**carta_prepagata** | **bool** | | [optional]
**note** | **string** | | [optional]
**id_capogruppo** | **int** | | [optional]
**tipo_lead** | **string** | | [optional]
**genera_sostegno** | **bool** | | [optional]
**preferenza_continente** | **string** | | [optional]
**preferenza_nazione** | **string** | | [optional]
**preferenza_eta_minima** | **string** | | [optional]
**preferenza_eta_massima** | **string** | | [optional]
**preferenza_genere** | **string** | | [optional]
**id_campagna** | **int** | | [optional]
**id_centro** | **int** | | [optional]
**gruppo_incassi** | **int** | | [optional]
**codice_nazione** | **string** | | [optional]
**cin_iban** | **string** | | [optional]
**cin_bban** | **string** | | [optional]
**abi** | **string** | | [optional]
**cab** | **string** | | [optional]
**conto** | **string** | | [optional]
**flag_one_off** | **string** | | [optional]
**masked_pan** | **string** | | [optional]
**numero_carta** | **string** | | [optional]
**anno_carta** | **int** | | [optional]
**mese_carta** | **int** | | [optional]
**data_inizio_sospensione** | **string** | | [optional]
**data_fine_sospensione** | **string** | | [optional]
**id_motivo_rinuncia** | **int** | | [optional]
**data_rinuncia** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep><?php
/**
* AdozioniTest
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace Swagger\Client;
/**
* AdozioniTest Class Doc Comment
*
* @category Class
* @description Adozioni
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class AdozioniTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "Adozioni"
*/
public function testAdozioni()
{
}
/**
* Test attribute "id_adozione"
*/
public function testPropertyIdAdozione()
{
}
/**
* Test attribute "codice"
*/
public function testPropertyCodice()
{
}
/**
* Test attribute "nome"
*/
public function testPropertyNome()
{
}
/**
* Test attribute "cognome"
*/
public function testPropertyCognome()
{
}
/**
* Test attribute "sesso"
*/
public function testPropertySesso()
{
}
/**
* Test attribute "data_nascita"
*/
public function testPropertyDataNascita()
{
}
/**
* Test attribute "location"
*/
public function testPropertyLocation()
{
}
/**
* Test attribute "url_foto"
*/
public function testPropertyUrlFoto()
{
}
/**
* Test attribute "nazione"
*/
public function testPropertyNazione()
{
}
/**
* Test attribute "programma"
*/
public function testPropertyProgramma()
{
}
}
<file_sep># ClientiIndirizzi
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id_cliente** | **int** | | [optional]
**tipo_indirizzo** | **string** | | [optional]
**descrizione_tipo_indirizzo** | **string** | | [optional]
**nome** | **string** | | [optional]
**dug** | **string** | | [optional]
**indirizzo** | **string** | | [optional]
**civico** | **string** | | [optional]
**altro_civico** | **string** | | [optional]
**frazione** | **string** | | [optional]
**presso** | **string** | | [optional]
**codice_nazione** | **string** | | [optional]
**cap** | **string** | | [optional]
**localita** | **string** | | [optional]
**provincia** | **string** | | [optional]
**telefono** | **string** | | [optional]
**telefono2** | **string** | | [optional]
**note** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep><?php
/**
* ClientiIndirizzi
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace Swagger\Client\Model;
use \ArrayAccess;
use \Swagger\Client\ObjectSerializer;
/**
* ClientiIndirizzi Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class ClientiIndirizzi implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'ClientiIndirizzi';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'id_cliente' => 'int',
'tipo_indirizzo' => 'string',
'descrizione_tipo_indirizzo' => 'string',
'nome' => 'string',
'dug' => 'string',
'indirizzo' => 'string',
'civico' => 'string',
'altro_civico' => 'string',
'frazione' => 'string',
'presso' => 'string',
'codice_nazione' => 'string',
'cap' => 'string',
'localita' => 'string',
'provincia' => 'string',
'telefono' => 'string',
'telefono2' => 'string',
'note' => 'string'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'id_cliente' => 'int32',
'tipo_indirizzo' => null,
'descrizione_tipo_indirizzo' => null,
'nome' => null,
'dug' => null,
'indirizzo' => null,
'civico' => null,
'altro_civico' => null,
'frazione' => null,
'presso' => null,
'codice_nazione' => null,
'cap' => null,
'localita' => null,
'provincia' => null,
'telefono' => null,
'telefono2' => null,
'note' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'id_cliente' => 'IdCliente',
'tipo_indirizzo' => 'TipoIndirizzo',
'descrizione_tipo_indirizzo' => 'DescrizioneTipoIndirizzo',
'nome' => 'Nome',
'dug' => 'Dug',
'indirizzo' => 'Indirizzo',
'civico' => 'Civico',
'altro_civico' => 'AltroCivico',
'frazione' => 'Frazione',
'presso' => 'Presso',
'codice_nazione' => 'CodiceNazione',
'cap' => 'Cap',
'localita' => 'Localita',
'provincia' => 'Provincia',
'telefono' => 'Telefono',
'telefono2' => 'Telefono2',
'note' => 'Note'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'id_cliente' => 'setIdCliente',
'tipo_indirizzo' => 'setTipoIndirizzo',
'descrizione_tipo_indirizzo' => 'setDescrizioneTipoIndirizzo',
'nome' => 'setNome',
'dug' => 'setDug',
'indirizzo' => 'setIndirizzo',
'civico' => 'setCivico',
'altro_civico' => 'setAltroCivico',
'frazione' => 'setFrazione',
'presso' => 'setPresso',
'codice_nazione' => 'setCodiceNazione',
'cap' => 'setCap',
'localita' => 'setLocalita',
'provincia' => 'setProvincia',
'telefono' => 'setTelefono',
'telefono2' => 'setTelefono2',
'note' => 'setNote'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'id_cliente' => 'getIdCliente',
'tipo_indirizzo' => 'getTipoIndirizzo',
'descrizione_tipo_indirizzo' => 'getDescrizioneTipoIndirizzo',
'nome' => 'getNome',
'dug' => 'getDug',
'indirizzo' => 'getIndirizzo',
'civico' => 'getCivico',
'altro_civico' => 'getAltroCivico',
'frazione' => 'getFrazione',
'presso' => 'getPresso',
'codice_nazione' => 'getCodiceNazione',
'cap' => 'getCap',
'localita' => 'getLocalita',
'provincia' => 'getProvincia',
'telefono' => 'getTelefono',
'telefono2' => 'getTelefono2',
'note' => 'getNote'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['id_cliente'] = isset($data['id_cliente']) ? $data['id_cliente'] : null;
$this->container['tipo_indirizzo'] = isset($data['tipo_indirizzo']) ? $data['tipo_indirizzo'] : null;
$this->container['descrizione_tipo_indirizzo'] = isset($data['descrizione_tipo_indirizzo']) ? $data['descrizione_tipo_indirizzo'] : null;
$this->container['nome'] = isset($data['nome']) ? $data['nome'] : null;
$this->container['dug'] = isset($data['dug']) ? $data['dug'] : null;
$this->container['indirizzo'] = isset($data['indirizzo']) ? $data['indirizzo'] : null;
$this->container['civico'] = isset($data['civico']) ? $data['civico'] : null;
$this->container['altro_civico'] = isset($data['altro_civico']) ? $data['altro_civico'] : null;
$this->container['frazione'] = isset($data['frazione']) ? $data['frazione'] : null;
$this->container['presso'] = isset($data['presso']) ? $data['presso'] : null;
$this->container['codice_nazione'] = isset($data['codice_nazione']) ? $data['codice_nazione'] : null;
$this->container['cap'] = isset($data['cap']) ? $data['cap'] : null;
$this->container['localita'] = isset($data['localita']) ? $data['localita'] : null;
$this->container['provincia'] = isset($data['provincia']) ? $data['provincia'] : null;
$this->container['telefono'] = isset($data['telefono']) ? $data['telefono'] : null;
$this->container['telefono2'] = isset($data['telefono2']) ? $data['telefono2'] : null;
$this->container['note'] = isset($data['note']) ? $data['note'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets id_cliente
*
* @return int
*/
public function getIdCliente()
{
return $this->container['id_cliente'];
}
/**
* Sets id_cliente
*
* @param int $id_cliente id_cliente
*
* @return $this
*/
public function setIdCliente($id_cliente)
{
$this->container['id_cliente'] = $id_cliente;
return $this;
}
/**
* Gets tipo_indirizzo
*
* @return string
*/
public function getTipoIndirizzo()
{
return $this->container['tipo_indirizzo'];
}
/**
* Sets tipo_indirizzo
*
* @param string $tipo_indirizzo tipo_indirizzo
*
* @return $this
*/
public function setTipoIndirizzo($tipo_indirizzo)
{
$this->container['tipo_indirizzo'] = $tipo_indirizzo;
return $this;
}
/**
* Gets descrizione_tipo_indirizzo
*
* @return string
*/
public function getDescrizioneTipoIndirizzo()
{
return $this->container['descrizione_tipo_indirizzo'];
}
/**
* Sets descrizione_tipo_indirizzo
*
* @param string $descrizione_tipo_indirizzo descrizione_tipo_indirizzo
*
* @return $this
*/
public function setDescrizioneTipoIndirizzo($descrizione_tipo_indirizzo)
{
$this->container['descrizione_tipo_indirizzo'] = $descrizione_tipo_indirizzo;
return $this;
}
/**
* Gets nome
*
* @return string
*/
public function getNome()
{
return $this->container['nome'];
}
/**
* Sets nome
*
* @param string $nome nome
*
* @return $this
*/
public function setNome($nome)
{
$this->container['nome'] = $nome;
return $this;
}
/**
* Gets dug
*
* @return string
*/
public function getDug()
{
return $this->container['dug'];
}
/**
* Sets dug
*
* @param string $dug dug
*
* @return $this
*/
public function setDug($dug)
{
$this->container['dug'] = $dug;
return $this;
}
/**
* Gets indirizzo
*
* @return string
*/
public function getIndirizzo()
{
return $this->container['indirizzo'];
}
/**
* Sets indirizzo
*
* @param string $indirizzo indirizzo
*
* @return $this
*/
public function setIndirizzo($indirizzo)
{
$this->container['indirizzo'] = $indirizzo;
return $this;
}
/**
* Gets civico
*
* @return string
*/
public function getCivico()
{
return $this->container['civico'];
}
/**
* Sets civico
*
* @param string $civico civico
*
* @return $this
*/
public function setCivico($civico)
{
$this->container['civico'] = $civico;
return $this;
}
/**
* Gets altro_civico
*
* @return string
*/
public function getAltroCivico()
{
return $this->container['altro_civico'];
}
/**
* Sets altro_civico
*
* @param string $altro_civico altro_civico
*
* @return $this
*/
public function setAltroCivico($altro_civico)
{
$this->container['altro_civico'] = $altro_civico;
return $this;
}
/**
* Gets frazione
*
* @return string
*/
public function getFrazione()
{
return $this->container['frazione'];
}
/**
* Sets frazione
*
* @param string $frazione frazione
*
* @return $this
*/
public function setFrazione($frazione)
{
$this->container['frazione'] = $frazione;
return $this;
}
/**
* Gets presso
*
* @return string
*/
public function getPresso()
{
return $this->container['presso'];
}
/**
* Sets presso
*
* @param string $presso presso
*
* @return $this
*/
public function setPresso($presso)
{
$this->container['presso'] = $presso;
return $this;
}
/**
* Gets codice_nazione
*
* @return string
*/
public function getCodiceNazione()
{
return $this->container['codice_nazione'];
}
/**
* Sets codice_nazione
*
* @param string $codice_nazione codice_nazione
*
* @return $this
*/
public function setCodiceNazione($codice_nazione)
{
$this->container['codice_nazione'] = $codice_nazione;
return $this;
}
/**
* Gets cap
*
* @return string
*/
public function getCap()
{
return $this->container['cap'];
}
/**
* Sets cap
*
* @param string $cap cap
*
* @return $this
*/
public function setCap($cap)
{
$this->container['cap'] = $cap;
return $this;
}
/**
* Gets localita
*
* @return string
*/
public function getLocalita()
{
return $this->container['localita'];
}
/**
* Sets localita
*
* @param string $localita localita
*
* @return $this
*/
public function setLocalita($localita)
{
$this->container['localita'] = $localita;
return $this;
}
/**
* Gets provincia
*
* @return string
*/
public function getProvincia()
{
return $this->container['provincia'];
}
/**
* Sets provincia
*
* @param string $provincia provincia
*
* @return $this
*/
public function setProvincia($provincia)
{
$this->container['provincia'] = $provincia;
return $this;
}
/**
* Gets telefono
*
* @return string
*/
public function getTelefono()
{
return $this->container['telefono'];
}
/**
* Sets telefono
*
* @param string $telefono telefono
*
* @return $this
*/
public function setTelefono($telefono)
{
$this->container['telefono'] = $telefono;
return $this;
}
/**
* Gets telefono2
*
* @return string
*/
public function getTelefono2()
{
return $this->container['telefono2'];
}
/**
* Sets telefono2
*
* @param string $telefono2 telefono2
*
* @return $this
*/
public function setTelefono2($telefono2)
{
$this->container['telefono2'] = $telefono2;
return $this;
}
/**
* Gets note
*
* @return string
*/
public function getNote()
{
return $this->container['note'];
}
/**
* Sets note
*
* @param string $note note
*
* @return $this
*/
public function setNote($note)
{
$this->container['note'] = $note;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep><?php
/**
* ClientiIndirizziTest
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace Swagger\Client;
/**
* ClientiIndirizziTest Class Doc Comment
*
* @category Class
* @description ClientiIndirizzi
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class ClientiIndirizziTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "ClientiIndirizzi"
*/
public function testClientiIndirizzi()
{
}
/**
* Test attribute "id_cliente"
*/
public function testPropertyIdCliente()
{
}
/**
* Test attribute "tipo_indirizzo"
*/
public function testPropertyTipoIndirizzo()
{
}
/**
* Test attribute "descrizione_tipo_indirizzo"
*/
public function testPropertyDescrizioneTipoIndirizzo()
{
}
/**
* Test attribute "nome"
*/
public function testPropertyNome()
{
}
/**
* Test attribute "dug"
*/
public function testPropertyDug()
{
}
/**
* Test attribute "indirizzo"
*/
public function testPropertyIndirizzo()
{
}
/**
* Test attribute "civico"
*/
public function testPropertyCivico()
{
}
/**
* Test attribute "altro_civico"
*/
public function testPropertyAltroCivico()
{
}
/**
* Test attribute "frazione"
*/
public function testPropertyFrazione()
{
}
/**
* Test attribute "presso"
*/
public function testPropertyPresso()
{
}
/**
* Test attribute "codice_nazione"
*/
public function testPropertyCodiceNazione()
{
}
/**
* Test attribute "cap"
*/
public function testPropertyCap()
{
}
/**
* Test attribute "localita"
*/
public function testPropertyLocalita()
{
}
/**
* Test attribute "provincia"
*/
public function testPropertyProvincia()
{
}
/**
* Test attribute "telefono"
*/
public function testPropertyTelefono()
{
}
/**
* Test attribute "telefono2"
*/
public function testPropertyTelefono2()
{
}
/**
* Test attribute "note"
*/
public function testPropertyNote()
{
}
}
<file_sep><?php
/**
* VersamentoApi
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace Swagger\Client\Api;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use Swagger\Client\ApiException;
use Swagger\Client\Configuration;
use Swagger\Client\HeaderSelector;
use Swagger\Client\ObjectSerializer;
/**
* VersamentoApi Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class VersamentoApi
{
/**
* @var ClientInterface
*/
protected $client;
/**
* @var Configuration
*/
protected $config;
/**
* @var HeaderSelector
*/
protected $headerSelector;
/**
* @param ClientInterface $client
* @param Configuration $config
* @param HeaderSelector $selector
*/
public function __construct(
ClientInterface $client = null,
Configuration $config = null,
HeaderSelector $selector = null
) {
$this->client = $client ?: new Client();
$this->config = $config ?: new Configuration();
$this->headerSelector = $selector ?: new HeaderSelector();
}
/**
* @return Configuration
*/
public function getConfig()
{
return $this->config;
}
/**
* Operation versamentoGet
*
* @param string $codice_cliente codice_cliente (required)
* @param string $data_inizio data_inizio (optional)
* @param string $data_fine data_fine (optional)
* @param string $id_regolare id_regolare (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Versamento[]
*/
public function versamentoGet($codice_cliente, $data_inizio = null, $data_fine = null, $id_regolare = null)
{
list($response) = $this->versamentoGetWithHttpInfo($codice_cliente, $data_inizio, $data_fine, $id_regolare);
return $response;
}
/**
* Operation versamentoGetWithHttpInfo
*
* @param string $codice_cliente (required)
* @param string $data_inizio (optional)
* @param string $data_fine (optional)
* @param string $id_regolare (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of \Swagger\Client\Model\Versamento[], HTTP status code, HTTP response headers (array of strings)
*/
public function versamentoGetWithHttpInfo($codice_cliente, $data_inizio = null, $data_fine = null, $id_regolare = null)
{
$returnType = '\Swagger\Client\Model\Versamento[]';
$request = $this->versamentoGetRequest($codice_cliente, $data_inizio, $data_fine, $id_regolare);
try {
$options = $this->createHttpClientOption();
try {
$response = $this->client->send($request, $options);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$request->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\Swagger\Client\Model\Versamento[]',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
}
throw $e;
}
}
/**
* Operation versamentoGetAsync
*
*
*
* @param string $codice_cliente (required)
* @param string $data_inizio (optional)
* @param string $data_fine (optional)
* @param string $id_regolare (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function versamentoGetAsync($codice_cliente, $data_inizio = null, $data_fine = null, $id_regolare = null)
{
return $this->versamentoGetAsyncWithHttpInfo($codice_cliente, $data_inizio, $data_fine, $id_regolare)
->then(
function ($response) {
return $response[0];
}
);
}
/**
* Operation versamentoGetAsyncWithHttpInfo
*
*
*
* @param string $codice_cliente (required)
* @param string $data_inizio (optional)
* @param string $data_fine (optional)
* @param string $id_regolare (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function versamentoGetAsyncWithHttpInfo($codice_cliente, $data_inizio = null, $data_fine = null, $id_regolare = null)
{
$returnType = '\Swagger\Client\Model\Versamento[]';
$request = $this->versamentoGetRequest($codice_cliente, $data_inizio, $data_fine, $id_regolare);
return $this->client
->sendAsync($request, $this->createHttpClientOption())
->then(
function ($response) use ($returnType) {
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
},
function ($exception) {
$response = $exception->getResponse();
$statusCode = $response->getStatusCode();
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$exception->getRequest()->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
);
}
/**
* Create request for operation 'versamentoGet'
*
* @param string $codice_cliente (required)
* @param string $data_inizio (optional)
* @param string $data_fine (optional)
* @param string $id_regolare (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Psr7\Request
*/
protected function versamentoGetRequest($codice_cliente, $data_inizio = null, $data_fine = null, $id_regolare = null)
{
// verify the required parameter 'codice_cliente' is set
if ($codice_cliente === null || (is_array($codice_cliente) && count($codice_cliente) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $codice_cliente when calling versamentoGet'
);
}
$resourcePath = '/v1/api/Versamento/Get';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// query params
if ($codice_cliente !== null) {
$queryParams['CodiceCliente'] = ObjectSerializer::toQueryValue($codice_cliente);
}
// query params
if ($data_inizio !== null) {
$queryParams['DataInizio'] = ObjectSerializer::toQueryValue($data_inizio);
}
// query params
if ($data_fine !== null) {
$queryParams['DataFine'] = ObjectSerializer::toQueryValue($data_fine);
}
// query params
if ($id_regolare !== null) {
$queryParams['id_regolare'] = ObjectSerializer::toQueryValue($id_regolare);
}
// body params
$_tempBody = null;
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json', 'text/json', 'application/xml', 'text/xml']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json', 'text/json', 'application/xml', 'text/xml'],
[]
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
if($headers['Content-Type'] === 'application/json') {
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass) {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
// array has no __toString(), so we should encode it manually
if(is_array($httpBody)) {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody));
}
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'GET',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
/**
* Operation versamentoInsertVersamento
*
* @param \Swagger\Client\Model\Versamento[] $raw_string raw_string (required)
* @param string $ambiente ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Versamento[]
*/
public function versamentoInsertVersamento($raw_string, $ambiente = null)
{
list($response) = $this->versamentoInsertVersamentoWithHttpInfo($raw_string, $ambiente);
return $response;
}
/**
* Operation versamentoInsertVersamentoWithHttpInfo
*
* @param \Swagger\Client\Model\Versamento[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of \Swagger\Client\Model\Versamento[], HTTP status code, HTTP response headers (array of strings)
*/
public function versamentoInsertVersamentoWithHttpInfo($raw_string, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Versamento[]';
$request = $this->versamentoInsertVersamentoRequest($raw_string, $ambiente);
try {
$options = $this->createHttpClientOption();
try {
$response = $this->client->send($request, $options);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$request->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\Swagger\Client\Model\Versamento[]',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
}
throw $e;
}
}
/**
* Operation versamentoInsertVersamentoAsync
*
*
*
* @param \Swagger\Client\Model\Versamento[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function versamentoInsertVersamentoAsync($raw_string, $ambiente = null)
{
return $this->versamentoInsertVersamentoAsyncWithHttpInfo($raw_string, $ambiente)
->then(
function ($response) {
return $response[0];
}
);
}
/**
* Operation versamentoInsertVersamentoAsyncWithHttpInfo
*
*
*
* @param \Swagger\Client\Model\Versamento[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function versamentoInsertVersamentoAsyncWithHttpInfo($raw_string, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Versamento[]';
$request = $this->versamentoInsertVersamentoRequest($raw_string, $ambiente);
return $this->client
->sendAsync($request, $this->createHttpClientOption())
->then(
function ($response) use ($returnType) {
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
},
function ($exception) {
$response = $exception->getResponse();
$statusCode = $response->getStatusCode();
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$exception->getRequest()->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
);
}
/**
* Create request for operation 'versamentoInsertVersamento'
*
* @param \Swagger\Client\Model\Versamento[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Psr7\Request
*/
protected function versamentoInsertVersamentoRequest($raw_string, $ambiente = null)
{
// verify the required parameter 'raw_string' is set
if ($raw_string === null || (is_array($raw_string) && count($raw_string) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $raw_string when calling versamentoInsertVersamento'
);
}
$resourcePath = '/v1/api/Versamento/InsertVersamento';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// query params
if ($ambiente !== null) {
$queryParams['Ambiente'] = ObjectSerializer::toQueryValue($ambiente);
}
// body params
$_tempBody = null;
if (isset($raw_string)) {
$_tempBody = $raw_string;
}
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json', 'text/json', 'application/xml', 'text/xml']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json', 'text/json', 'application/xml', 'text/xml'],
['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded']
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
if($headers['Content-Type'] === 'application/json') {
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass) {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
// array has no __toString(), so we should encode it manually
if(is_array($httpBody)) {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody));
}
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'POST',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
/**
* Operation versamentoUpdateAttivita
*
* @param \Swagger\Client\Model\Versamento[] $raw_string raw_string (required)
* @param string $ambiente ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Versamento[]
*/
public function versamentoUpdateAttivita($raw_string, $ambiente = null)
{
list($response) = $this->versamentoUpdateAttivitaWithHttpInfo($raw_string, $ambiente);
return $response;
}
/**
* Operation versamentoUpdateAttivitaWithHttpInfo
*
* @param \Swagger\Client\Model\Versamento[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of \Swagger\Client\Model\Versamento[], HTTP status code, HTTP response headers (array of strings)
*/
public function versamentoUpdateAttivitaWithHttpInfo($raw_string, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Versamento[]';
$request = $this->versamentoUpdateAttivitaRequest($raw_string, $ambiente);
try {
$options = $this->createHttpClientOption();
try {
$response = $this->client->send($request, $options);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$request->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\Swagger\Client\Model\Versamento[]',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
}
throw $e;
}
}
/**
* Operation versamentoUpdateAttivitaAsync
*
*
*
* @param \Swagger\Client\Model\Versamento[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function versamentoUpdateAttivitaAsync($raw_string, $ambiente = null)
{
return $this->versamentoUpdateAttivitaAsyncWithHttpInfo($raw_string, $ambiente)
->then(
function ($response) {
return $response[0];
}
);
}
/**
* Operation versamentoUpdateAttivitaAsyncWithHttpInfo
*
*
*
* @param \Swagger\Client\Model\Versamento[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function versamentoUpdateAttivitaAsyncWithHttpInfo($raw_string, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Versamento[]';
$request = $this->versamentoUpdateAttivitaRequest($raw_string, $ambiente);
return $this->client
->sendAsync($request, $this->createHttpClientOption())
->then(
function ($response) use ($returnType) {
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
},
function ($exception) {
$response = $exception->getResponse();
$statusCode = $response->getStatusCode();
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$exception->getRequest()->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
);
}
/**
* Create request for operation 'versamentoUpdateAttivita'
*
* @param \Swagger\Client\Model\Versamento[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Psr7\Request
*/
protected function versamentoUpdateAttivitaRequest($raw_string, $ambiente = null)
{
// verify the required parameter 'raw_string' is set
if ($raw_string === null || (is_array($raw_string) && count($raw_string) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $raw_string when calling versamentoUpdateAttivita'
);
}
$resourcePath = '/v1/api/Versamento/UpdateAttivita';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// query params
if ($ambiente !== null) {
$queryParams['Ambiente'] = ObjectSerializer::toQueryValue($ambiente);
}
// body params
$_tempBody = null;
if (isset($raw_string)) {
$_tempBody = $raw_string;
}
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json', 'text/json', 'application/xml', 'text/xml']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json', 'text/json', 'application/xml', 'text/xml'],
['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded']
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
if($headers['Content-Type'] === 'application/json') {
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass) {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
// array has no __toString(), so we should encode it manually
if(is_array($httpBody)) {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody));
}
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'POST',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
/**
* Create http client option
*
* @throws \RuntimeException on file opening failure
* @return array of http client options
*/
protected function createHttpClientOption()
{
$options = [];
if ($this->config->getDebug()) {
$options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
if (!$options[RequestOptions::DEBUG]) {
throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
}
}
return $options;
}
}
<file_sep><?php
/**
* ClientiTest
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace Swagger\Client;
/**
* ClientiTest Class Doc Comment
*
* @category Class
* @description Clienti
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class ClientiTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "Clienti"
*/
public function testClienti()
{
}
/**
* Test attribute "codice"
*/
public function testPropertyCodice()
{
}
/**
* Test attribute "codice_origine"
*/
public function testPropertyCodiceOrigine()
{
}
/**
* Test attribute "tipo_master"
*/
public function testPropertyTipoMaster()
{
}
/**
* Test attribute "codice_master"
*/
public function testPropertyCodiceMaster()
{
}
/**
* Test attribute "codice_web"
*/
public function testPropertyCodiceWeb()
{
}
/**
* Test attribute "codice_presentatore"
*/
public function testPropertyCodicePresentatore()
{
}
/**
* Test attribute "tipo"
*/
public function testPropertyTipo()
{
}
/**
* Test attribute "sottotipo"
*/
public function testPropertySottotipo()
{
}
/**
* Test attribute "fonte"
*/
public function testPropertyFonte()
{
}
/**
* Test attribute "lista_origine"
*/
public function testPropertyListaOrigine()
{
}
/**
* Test attribute "codice_manifestazione"
*/
public function testPropertyCodiceManifestazione()
{
}
/**
* Test attribute "id_appellativo"
*/
public function testPropertyIdAppellativo()
{
}
/**
* Test attribute "titolo"
*/
public function testPropertyTitolo()
{
}
/**
* Test attribute "data_raccolta"
*/
public function testPropertyDataRaccolta()
{
}
/**
* Test attribute "lotto"
*/
public function testPropertyLotto()
{
}
/**
* Test attribute "nome"
*/
public function testPropertyNome()
{
}
/**
* Test attribute "cognome"
*/
public function testPropertyCognome()
{
}
/**
* Test attribute "ragione_sociale"
*/
public function testPropertyRagioneSociale()
{
}
/**
* Test attribute "genere"
*/
public function testPropertyGenere()
{
}
/**
* Test attribute "data_nascita"
*/
public function testPropertyDataNascita()
{
}
/**
* Test attribute "luogo_nascita"
*/
public function testPropertyLuogoNascita()
{
}
/**
* Test attribute "codice_fiscale"
*/
public function testPropertyCodiceFiscale()
{
}
/**
* Test attribute "partita_iva"
*/
public function testPropertyPartitaIva()
{
}
/**
* Test attribute "email1"
*/
public function testPropertyEmail1()
{
}
/**
* Test attribute "email2"
*/
public function testPropertyEmail2()
{
}
/**
* Test attribute "telefono1"
*/
public function testPropertyTelefono1()
{
}
/**
* Test attribute "telefono2"
*/
public function testPropertyTelefono2()
{
}
/**
* Test attribute "cellulare1"
*/
public function testPropertyCellulare1()
{
}
/**
* Test attribute "cellulare2"
*/
public function testPropertyCellulare2()
{
}
/**
* Test attribute "presso"
*/
public function testPropertyPresso()
{
}
/**
* Test attribute "dug"
*/
public function testPropertyDug()
{
}
/**
* Test attribute "duf"
*/
public function testPropertyDuf()
{
}
/**
* Test attribute "civico"
*/
public function testPropertyCivico()
{
}
/**
* Test attribute "altro_civico"
*/
public function testPropertyAltroCivico()
{
}
/**
* Test attribute "frazione"
*/
public function testPropertyFrazione()
{
}
/**
* Test attribute "localita"
*/
public function testPropertyLocalita()
{
}
/**
* Test attribute "provincia"
*/
public function testPropertyProvincia()
{
}
/**
* Test attribute "cap"
*/
public function testPropertyCap()
{
}
/**
* Test attribute "codice_nazione"
*/
public function testPropertyCodiceNazione()
{
}
/**
* Test attribute "indirizzi"
*/
public function testPropertyIndirizzi()
{
}
/**
* Test attribute "recapiti"
*/
public function testPropertyRecapiti()
{
}
/**
* Test attribute "campagna"
*/
public function testPropertyCampagna()
{
}
/**
* Test attribute "id_campagna"
*/
public function testPropertyIdCampagna()
{
}
/**
* Test attribute "professione"
*/
public function testPropertyProfessione()
{
}
/**
* Test attribute "titolo_studio"
*/
public function testPropertyTitoloStudio()
{
}
/**
* Test attribute "figli"
*/
public function testPropertyFigli()
{
}
/**
* Test attribute "codice_tessera"
*/
public function testPropertyCodiceTessera()
{
}
/**
* Test attribute "evento"
*/
public function testPropertyEvento()
{
}
/**
* Test attribute "data_scadenza_tessera"
*/
public function testPropertyDataScadenzaTessera()
{
}
/**
* Test attribute "data_emissione_tessera"
*/
public function testPropertyDataEmissioneTessera()
{
}
/**
* Test attribute "flag_emissione_tessera"
*/
public function testPropertyFlagEmissioneTessera()
{
}
/**
* Test attribute "privacy"
*/
public function testPropertyPrivacy()
{
}
/**
* Test attribute "specifiche"
*/
public function testPropertySpecifiche()
{
}
/**
* Test attribute "profilazioni"
*/
public function testPropertyProfilazioni()
{
}
/**
* Test attribute "subscriptions"
*/
public function testPropertySubscriptions()
{
}
/**
* Test attribute "gruppi"
*/
public function testPropertyGruppi()
{
}
/**
* Test attribute "flag_deceduto"
*/
public function testPropertyFlagDeceduto()
{
}
/**
* Test attribute "_data_decesso"
*/
public function testPropertyDataDecesso()
{
}
/**
* Test attribute "data_decesso"
*/
public function testPropertyDataDecesso()
{
}
/**
* Test attribute "utente"
*/
public function testPropertyUtente()
{
}
}
<file_sep># CallRegolare
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id_regolare** | **string** | | [optional]
**codice_esito** | **string** | | [optional]
**codice_motivo_rinuncia** | **string** | | [optional]
**data_rinuncia** | **string** | | [optional]
**codice_campagna** | **string** | | [optional]
**importo** | **string** | | [optional]
**frequenza** | **string** | | [optional]
**stato** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep><?php
/**
* AttivitaApi
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace Swagger\Client\Api;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use Swagger\Client\ApiException;
use Swagger\Client\Configuration;
use Swagger\Client\HeaderSelector;
use Swagger\Client\ObjectSerializer;
/**
* AttivitaApi Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class AttivitaApi
{
/**
* @var ClientInterface
*/
protected $client;
/**
* @var Configuration
*/
protected $config;
/**
* @var HeaderSelector
*/
protected $headerSelector;
/**
* @param ClientInterface $client
* @param Configuration $config
* @param HeaderSelector $selector
*/
public function __construct(
ClientInterface $client = null,
Configuration $config = null,
HeaderSelector $selector = null
) {
$this->client = $client ?: new Client();
$this->config = $config ?: new Configuration();
$this->headerSelector = $selector ?: new HeaderSelector();
}
/**
* @return Configuration
*/
public function getConfig()
{
return $this->config;
}
/**
* Operation attivitaGet
*
* @param string $id_attivita id_attivita (required)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Attivita
*/
public function attivitaGet($id_attivita)
{
list($response) = $this->attivitaGetWithHttpInfo($id_attivita);
return $response;
}
/**
* Operation attivitaGetWithHttpInfo
*
* @param string $id_attivita (required)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of \Swagger\Client\Model\Attivita, HTTP status code, HTTP response headers (array of strings)
*/
public function attivitaGetWithHttpInfo($id_attivita)
{
$returnType = '\Swagger\Client\Model\Attivita';
$request = $this->attivitaGetRequest($id_attivita);
try {
$options = $this->createHttpClientOption();
try {
$response = $this->client->send($request, $options);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$request->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\Swagger\Client\Model\Attivita',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
}
throw $e;
}
}
/**
* Operation attivitaGetAsync
*
*
*
* @param string $id_attivita (required)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function attivitaGetAsync($id_attivita)
{
return $this->attivitaGetAsyncWithHttpInfo($id_attivita)
->then(
function ($response) {
return $response[0];
}
);
}
/**
* Operation attivitaGetAsyncWithHttpInfo
*
*
*
* @param string $id_attivita (required)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function attivitaGetAsyncWithHttpInfo($id_attivita)
{
$returnType = '\Swagger\Client\Model\Attivita';
$request = $this->attivitaGetRequest($id_attivita);
return $this->client
->sendAsync($request, $this->createHttpClientOption())
->then(
function ($response) use ($returnType) {
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
},
function ($exception) {
$response = $exception->getResponse();
$statusCode = $response->getStatusCode();
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$exception->getRequest()->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
);
}
/**
* Create request for operation 'attivitaGet'
*
* @param string $id_attivita (required)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Psr7\Request
*/
protected function attivitaGetRequest($id_attivita)
{
// verify the required parameter 'id_attivita' is set
if ($id_attivita === null || (is_array($id_attivita) && count($id_attivita) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $id_attivita when calling attivitaGet'
);
}
$resourcePath = '/v1/api/Attivita/Get';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// query params
if ($id_attivita !== null) {
$queryParams['id_attivita'] = ObjectSerializer::toQueryValue($id_attivita);
}
// body params
$_tempBody = null;
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json', 'text/json', 'application/xml', 'text/xml']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json', 'text/json', 'application/xml', 'text/xml'],
[]
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
if($headers['Content-Type'] === 'application/json') {
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass) {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
// array has no __toString(), so we should encode it manually
if(is_array($httpBody)) {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody));
}
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'GET',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
/**
* Operation attivitaInsertAttivita
*
* @param \Swagger\Client\Model\Attivita[] $raw_string raw_string (required)
* @param string $ambiente ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Attivita[]
*/
public function attivitaInsertAttivita($raw_string, $ambiente = null)
{
list($response) = $this->attivitaInsertAttivitaWithHttpInfo($raw_string, $ambiente);
return $response;
}
/**
* Operation attivitaInsertAttivitaWithHttpInfo
*
* @param \Swagger\Client\Model\Attivita[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of \Swagger\Client\Model\Attivita[], HTTP status code, HTTP response headers (array of strings)
*/
public function attivitaInsertAttivitaWithHttpInfo($raw_string, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Attivita[]';
$request = $this->attivitaInsertAttivitaRequest($raw_string, $ambiente);
try {
$options = $this->createHttpClientOption();
try {
$response = $this->client->send($request, $options);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$request->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\Swagger\Client\Model\Attivita[]',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
}
throw $e;
}
}
/**
* Operation attivitaInsertAttivitaAsync
*
*
*
* @param \Swagger\Client\Model\Attivita[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function attivitaInsertAttivitaAsync($raw_string, $ambiente = null)
{
return $this->attivitaInsertAttivitaAsyncWithHttpInfo($raw_string, $ambiente)
->then(
function ($response) {
return $response[0];
}
);
}
/**
* Operation attivitaInsertAttivitaAsyncWithHttpInfo
*
*
*
* @param \Swagger\Client\Model\Attivita[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function attivitaInsertAttivitaAsyncWithHttpInfo($raw_string, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Attivita[]';
$request = $this->attivitaInsertAttivitaRequest($raw_string, $ambiente);
return $this->client
->sendAsync($request, $this->createHttpClientOption())
->then(
function ($response) use ($returnType) {
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
},
function ($exception) {
$response = $exception->getResponse();
$statusCode = $response->getStatusCode();
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$exception->getRequest()->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
);
}
/**
* Create request for operation 'attivitaInsertAttivita'
*
* @param \Swagger\Client\Model\Attivita[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Psr7\Request
*/
protected function attivitaInsertAttivitaRequest($raw_string, $ambiente = null)
{
// verify the required parameter 'raw_string' is set
if ($raw_string === null || (is_array($raw_string) && count($raw_string) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $raw_string when calling attivitaInsertAttivita'
);
}
$resourcePath = '/v1/api/Attivita/InsertAttivita';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// query params
if ($ambiente !== null) {
$queryParams['Ambiente'] = ObjectSerializer::toQueryValue($ambiente);
}
// body params
$_tempBody = null;
if (isset($raw_string)) {
$_tempBody = $raw_string;
}
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json', 'text/json', 'application/xml', 'text/xml']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json', 'text/json', 'application/xml', 'text/xml'],
['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded']
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
if($headers['Content-Type'] === 'application/json') {
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass) {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
// array has no __toString(), so we should encode it manually
if(is_array($httpBody)) {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody));
}
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'POST',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
/**
* Operation attivitaUpdateAttivita
*
* @param \Swagger\Client\Model\Attivita[] $raw_string raw_string (required)
* @param string $ambiente ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Attivita[]
*/
public function attivitaUpdateAttivita($raw_string, $ambiente = null)
{
list($response) = $this->attivitaUpdateAttivitaWithHttpInfo($raw_string, $ambiente);
return $response;
}
/**
* Operation attivitaUpdateAttivitaWithHttpInfo
*
* @param \Swagger\Client\Model\Attivita[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of \Swagger\Client\Model\Attivita[], HTTP status code, HTTP response headers (array of strings)
*/
public function attivitaUpdateAttivitaWithHttpInfo($raw_string, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Attivita[]';
$request = $this->attivitaUpdateAttivitaRequest($raw_string, $ambiente);
try {
$options = $this->createHttpClientOption();
try {
$response = $this->client->send($request, $options);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null,
$e->getResponse() ? $e->getResponse()->getBody()->getContents() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$request->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = ObjectSerializer::deserialize(
$e->getResponseBody(),
'\Swagger\Client\Model\Attivita[]',
$e->getResponseHeaders()
);
$e->setResponseObject($data);
break;
}
throw $e;
}
}
/**
* Operation attivitaUpdateAttivitaAsync
*
*
*
* @param \Swagger\Client\Model\Attivita[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function attivitaUpdateAttivitaAsync($raw_string, $ambiente = null)
{
return $this->attivitaUpdateAttivitaAsyncWithHttpInfo($raw_string, $ambiente)
->then(
function ($response) {
return $response[0];
}
);
}
/**
* Operation attivitaUpdateAttivitaAsyncWithHttpInfo
*
*
*
* @param \Swagger\Client\Model\Attivita[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function attivitaUpdateAttivitaAsyncWithHttpInfo($raw_string, $ambiente = null)
{
$returnType = '\Swagger\Client\Model\Attivita[]';
$request = $this->attivitaUpdateAttivitaRequest($raw_string, $ambiente);
return $this->client
->sendAsync($request, $this->createHttpClientOption())
->then(
function ($response) use ($returnType) {
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
},
function ($exception) {
$response = $exception->getResponse();
$statusCode = $response->getStatusCode();
throw new ApiException(
sprintf(
'[%d] Error connecting to the API (%s)',
$statusCode,
$exception->getRequest()->getUri()
),
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
);
}
/**
* Create request for operation 'attivitaUpdateAttivita'
*
* @param \Swagger\Client\Model\Attivita[] $raw_string (required)
* @param string $ambiente (optional)
*
* @throws \InvalidArgumentException
* @return \GuzzleHttp\Psr7\Request
*/
protected function attivitaUpdateAttivitaRequest($raw_string, $ambiente = null)
{
// verify the required parameter 'raw_string' is set
if ($raw_string === null || (is_array($raw_string) && count($raw_string) === 0)) {
throw new \InvalidArgumentException(
'Missing the required parameter $raw_string when calling attivitaUpdateAttivita'
);
}
$resourcePath = '/v1/api/Attivita/UpdateAttivita';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// query params
if ($ambiente !== null) {
$queryParams['Ambiente'] = ObjectSerializer::toQueryValue($ambiente);
}
// body params
$_tempBody = null;
if (isset($raw_string)) {
$_tempBody = $raw_string;
}
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json', 'text/json', 'application/xml', 'text/xml']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json', 'text/json', 'application/xml', 'text/xml'],
['application/json', 'text/json', 'application/xml', 'text/xml', 'application/x-www-form-urlencoded']
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
if($headers['Content-Type'] === 'application/json') {
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass) {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
// array has no __toString(), so we should encode it manually
if(is_array($httpBody)) {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody));
}
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'POST',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
/**
* Create http client option
*
* @throws \RuntimeException on file opening failure
* @return array of http client options
*/
protected function createHttpClientOption()
{
$options = [];
if ($this->config->getDebug()) {
$options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
if (!$options[RequestOptions::DEBUG]) {
throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
}
}
return $options;
}
}
<file_sep><?php
/**
* VersamentoTest
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace Swagger\Client;
/**
* VersamentoTest Class Doc Comment
*
* @category Class
* @description Versamento
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class VersamentoTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "Versamento"
*/
public function testVersamento()
{
}
/**
* Test attribute "id_versamento"
*/
public function testPropertyIdVersamento()
{
}
/**
* Test attribute "id_regolare"
*/
public function testPropertyIdRegolare()
{
}
/**
* Test attribute "id_web"
*/
public function testPropertyIdWeb()
{
}
/**
* Test attribute "codice_cliente"
*/
public function testPropertyCodiceCliente()
{
}
/**
* Test attribute "codice_soggetto_versante"
*/
public function testPropertyCodiceSoggettoVersante()
{
}
/**
* Test attribute "codice_centro_ricavo"
*/
public function testPropertyCodiceCentroRicavo()
{
}
/**
* Test attribute "codice_partner"
*/
public function testPropertyCodicePartner()
{
}
/**
* Test attribute "codice_riferimento"
*/
public function testPropertyCodiceRiferimento()
{
}
/**
* Test attribute "campagna"
*/
public function testPropertyCampagna()
{
}
/**
* Test attribute "centro"
*/
public function testPropertyCentro()
{
}
/**
* Test attribute "canale"
*/
public function testPropertyCanale()
{
}
/**
* Test attribute "bambino"
*/
public function testPropertyBambino()
{
}
/**
* Test attribute "progetto"
*/
public function testPropertyProgetto()
{
}
/**
* Test attribute "conto"
*/
public function testPropertyConto()
{
}
/**
* Test attribute "evento"
*/
public function testPropertyEvento()
{
}
/**
* Test attribute "codice_transazione"
*/
public function testPropertyCodiceTransazione()
{
}
/**
* Test attribute "importo"
*/
public function testPropertyImporto()
{
}
/**
* Test attribute "metodo"
*/
public function testPropertyMetodo()
{
}
/**
* Test attribute "descrizione_metodo"
*/
public function testPropertyDescrizioneMetodo()
{
}
/**
* Test attribute "data_operazione"
*/
public function testPropertyDataOperazione()
{
}
/**
* Test attribute "data_valuta"
*/
public function testPropertyDataValuta()
{
}
/**
* Test attribute "note"
*/
public function testPropertyNote()
{
}
/**
* Test attribute "tipo"
*/
public function testPropertyTipo()
{
}
/**
* Test attribute "sotto_tipo"
*/
public function testPropertySottoTipo()
{
}
/**
* Test attribute "lotto"
*/
public function testPropertyLotto()
{
}
/**
* Test attribute "escludi_attestato"
*/
public function testPropertyEscludiAttestato()
{
}
/**
* Test attribute "flag_one_off"
*/
public function testPropertyFlagOneOff()
{
}
/**
* Test attribute "prodotti"
*/
public function testPropertyProdotti()
{
}
}
<file_sep># Attivita
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id_attivita** | **int** | | [optional]
**id_regolare** | **int** | | [optional]
**id_versamenti** | **int** | | [optional]
**codice_donatore** | **string** | | [optional]
**campagna** | **object** | | [optional]
**canale** | **object** | | [optional]
**pagamento** | **object** | | [optional]
**bambino** | **object** | | [optional]
**progetto** | **object** | | [optional]
**esito** | **object** | | [optional]
**id_lascito** | **int** | | [optional]
**data_attivita** | **string** | | [optional]
**ora_attivita** | **string** | | [optional]
**utente_assegnatario** | **string** | | [optional]
**gruppo_utenti_assegnatario** | **object** | | [optional]
**id_gruppo** | **int** | | [optional]
**evento** | **object** | | [optional]
**sollecito** | **object** | | [optional]
**motivo_rifiuto_ask** | **object** | | [optional]
**tipo_incidenza** | **object** | | [optional]
**tipo** | **object** | | [optional]
**sottotipo** | **object** | | [optional]
**stato** | **object** | | [optional]
**importo** | **float** | | [optional]
**oggetto** | **string** | | [optional]
**note** | **string** | | [optional]
**data_chiusura** | **string** | | [optional]
**link** | **string** | | [optional]
**lotto** | **string** | | [optional]
**template** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep><?php
/**
* Clienti
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace Swagger\Client\Model;
use \ArrayAccess;
use \Swagger\Client\ObjectSerializer;
/**
* Clienti Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class Clienti implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'Clienti';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'codice' => 'string',
'codice_origine' => 'string',
'tipo_master' => 'object',
'codice_master' => 'string',
'codice_web' => 'string',
'codice_presentatore' => 'string',
'tipo' => 'object',
'sottotipo' => 'object',
'fonte' => 'object',
'lista_origine' => 'object',
'codice_manifestazione' => 'string',
'id_appellativo' => 'int',
'titolo' => 'string',
'data_raccolta' => 'string',
'lotto' => 'string',
'nome' => 'string',
'cognome' => 'string',
'ragione_sociale' => 'string',
'genere' => 'string',
'data_nascita' => 'string',
'luogo_nascita' => 'string',
'codice_fiscale' => 'string',
'partita_iva' => 'string',
'email1' => 'string',
'email2' => 'string',
'telefono1' => 'string',
'telefono2' => 'string',
'cellulare1' => 'string',
'cellulare2' => 'string',
'presso' => 'string',
'dug' => 'string',
'duf' => 'string',
'civico' => 'string',
'altro_civico' => 'string',
'frazione' => 'string',
'localita' => 'string',
'provincia' => 'string',
'cap' => 'string',
'codice_nazione' => 'string',
'indirizzi' => '\Swagger\Client\Model\ClientiIndirizzi[]',
'recapiti' => '\Swagger\Client\Model\ClientiRecapiti[]',
'campagna' => 'object',
'id_campagna' => 'int',
'professione' => 'object',
'titolo_studio' => 'object',
'figli' => 'string',
'codice_tessera' => 'string',
'evento' => 'string',
'data_scadenza_tessera' => 'string',
'data_emissione_tessera' => 'string',
'flag_emissione_tessera' => 'bool',
'privacy' => '\Swagger\Client\Model\ClientiPrivacy[]',
'specifiche' => '\Swagger\Client\Model\ClientiSpecifiche[]',
'profilazioni' => '\Swagger\Client\Model\ClientiProfilazioni[]',
'subscriptions' => '\Swagger\Client\Model\ClientiSubscription[]',
'gruppi' => '\Swagger\Client\Model\ClientiGruppi[]',
'flag_deceduto' => 'bool',
'_data_decesso' => 'int',
'data_decesso' => 'string',
'utente' => 'string'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'codice' => null,
'codice_origine' => null,
'tipo_master' => null,
'codice_master' => null,
'codice_web' => null,
'codice_presentatore' => null,
'tipo' => null,
'sottotipo' => null,
'fonte' => null,
'lista_origine' => null,
'codice_manifestazione' => null,
'id_appellativo' => 'int32',
'titolo' => null,
'data_raccolta' => null,
'lotto' => null,
'nome' => null,
'cognome' => null,
'ragione_sociale' => null,
'genere' => null,
'data_nascita' => null,
'luogo_nascita' => null,
'codice_fiscale' => null,
'partita_iva' => null,
'email1' => null,
'email2' => null,
'telefono1' => null,
'telefono2' => null,
'cellulare1' => null,
'cellulare2' => null,
'presso' => null,
'dug' => null,
'duf' => null,
'civico' => null,
'altro_civico' => null,
'frazione' => null,
'localita' => null,
'provincia' => null,
'cap' => null,
'codice_nazione' => null,
'indirizzi' => null,
'recapiti' => null,
'campagna' => null,
'id_campagna' => 'int32',
'professione' => null,
'titolo_studio' => null,
'figli' => null,
'codice_tessera' => null,
'evento' => null,
'data_scadenza_tessera' => null,
'data_emissione_tessera' => null,
'flag_emissione_tessera' => null,
'privacy' => null,
'specifiche' => null,
'profilazioni' => null,
'subscriptions' => null,
'gruppi' => null,
'flag_deceduto' => null,
'_data_decesso' => 'int32',
'data_decesso' => null,
'utente' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'codice' => 'Codice',
'codice_origine' => 'CodiceOrigine',
'tipo_master' => 'TipoMaster',
'codice_master' => 'CodiceMaster',
'codice_web' => 'CodiceWeb',
'codice_presentatore' => 'codicePresentatore',
'tipo' => 'Tipo',
'sottotipo' => 'Sottotipo',
'fonte' => 'Fonte',
'lista_origine' => 'ListaOrigine',
'codice_manifestazione' => 'CodiceManifestazione',
'id_appellativo' => 'IdAppellativo',
'titolo' => 'Titolo',
'data_raccolta' => 'DataRaccolta',
'lotto' => 'Lotto',
'nome' => 'Nome',
'cognome' => 'Cognome',
'ragione_sociale' => 'RagioneSociale',
'genere' => 'Genere',
'data_nascita' => 'DataNascita',
'luogo_nascita' => 'LuogoNascita',
'codice_fiscale' => 'CodiceFiscale',
'partita_iva' => 'PartitaIva',
'email1' => 'Email1',
'email2' => 'Email2',
'telefono1' => 'Telefono1',
'telefono2' => 'Telefono2',
'cellulare1' => 'Cellulare1',
'cellulare2' => 'Cellulare2',
'presso' => 'Presso',
'dug' => 'Dug',
'duf' => 'Duf',
'civico' => 'Civico',
'altro_civico' => 'AltroCivico',
'frazione' => 'Frazione',
'localita' => 'Localita',
'provincia' => 'Provincia',
'cap' => 'Cap',
'codice_nazione' => 'CodiceNazione',
'indirizzi' => 'Indirizzi',
'recapiti' => 'Recapiti',
'campagna' => 'Campagna',
'id_campagna' => 'IdCampagna',
'professione' => 'Professione',
'titolo_studio' => 'TitoloStudio',
'figli' => 'Figli',
'codice_tessera' => 'codiceTessera',
'evento' => 'Evento',
'data_scadenza_tessera' => 'dataScadenzaTessera',
'data_emissione_tessera' => 'dataEmissioneTessera',
'flag_emissione_tessera' => 'flagEmissioneTessera',
'privacy' => 'Privacy',
'specifiche' => 'Specifiche',
'profilazioni' => 'Profilazioni',
'subscriptions' => 'Subscriptions',
'gruppi' => 'Gruppi',
'flag_deceduto' => 'flagDeceduto',
'_data_decesso' => '_dataDecesso',
'data_decesso' => 'dataDecesso',
'utente' => 'Utente'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'codice' => 'setCodice',
'codice_origine' => 'setCodiceOrigine',
'tipo_master' => 'setTipoMaster',
'codice_master' => 'setCodiceMaster',
'codice_web' => 'setCodiceWeb',
'codice_presentatore' => 'setCodicePresentatore',
'tipo' => 'setTipo',
'sottotipo' => 'setSottotipo',
'fonte' => 'setFonte',
'lista_origine' => 'setListaOrigine',
'codice_manifestazione' => 'setCodiceManifestazione',
'id_appellativo' => 'setIdAppellativo',
'titolo' => 'setTitolo',
'data_raccolta' => 'setDataRaccolta',
'lotto' => 'setLotto',
'nome' => 'setNome',
'cognome' => 'setCognome',
'ragione_sociale' => 'setRagioneSociale',
'genere' => 'setGenere',
'data_nascita' => 'setDataNascita',
'luogo_nascita' => 'setLuogoNascita',
'codice_fiscale' => 'setCodiceFiscale',
'partita_iva' => 'setPartitaIva',
'email1' => 'setEmail1',
'email2' => 'setEmail2',
'telefono1' => 'setTelefono1',
'telefono2' => 'setTelefono2',
'cellulare1' => 'setCellulare1',
'cellulare2' => 'setCellulare2',
'presso' => 'setPresso',
'dug' => 'setDug',
'duf' => 'setDuf',
'civico' => 'setCivico',
'altro_civico' => 'setAltroCivico',
'frazione' => 'setFrazione',
'localita' => 'setLocalita',
'provincia' => 'setProvincia',
'cap' => 'setCap',
'codice_nazione' => 'setCodiceNazione',
'indirizzi' => 'setIndirizzi',
'recapiti' => 'setRecapiti',
'campagna' => 'setCampagna',
'id_campagna' => 'setIdCampagna',
'professione' => 'setProfessione',
'titolo_studio' => 'setTitoloStudio',
'figli' => 'setFigli',
'codice_tessera' => 'setCodiceTessera',
'evento' => 'setEvento',
'data_scadenza_tessera' => 'setDataScadenzaTessera',
'data_emissione_tessera' => 'setDataEmissioneTessera',
'flag_emissione_tessera' => 'setFlagEmissioneTessera',
'privacy' => 'setPrivacy',
'specifiche' => 'setSpecifiche',
'profilazioni' => 'setProfilazioni',
'subscriptions' => 'setSubscriptions',
'gruppi' => 'setGruppi',
'flag_deceduto' => 'setFlagDeceduto',
'_data_decesso' => 'setDataDecesso',
'data_decesso' => 'setDataDecesso',
'utente' => 'setUtente'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'codice' => 'getCodice',
'codice_origine' => 'getCodiceOrigine',
'tipo_master' => 'getTipoMaster',
'codice_master' => 'getCodiceMaster',
'codice_web' => 'getCodiceWeb',
'codice_presentatore' => 'getCodicePresentatore',
'tipo' => 'getTipo',
'sottotipo' => 'getSottotipo',
'fonte' => 'getFonte',
'lista_origine' => 'getListaOrigine',
'codice_manifestazione' => 'getCodiceManifestazione',
'id_appellativo' => 'getIdAppellativo',
'titolo' => 'getTitolo',
'data_raccolta' => 'getDataRaccolta',
'lotto' => 'getLotto',
'nome' => 'getNome',
'cognome' => 'getCognome',
'ragione_sociale' => 'getRagioneSociale',
'genere' => 'getGenere',
'data_nascita' => 'getDataNascita',
'luogo_nascita' => 'getLuogoNascita',
'codice_fiscale' => 'getCodiceFiscale',
'partita_iva' => 'getPartitaIva',
'email1' => 'getEmail1',
'email2' => 'getEmail2',
'telefono1' => 'getTelefono1',
'telefono2' => 'getTelefono2',
'cellulare1' => 'getCellulare1',
'cellulare2' => 'getCellulare2',
'presso' => 'getPresso',
'dug' => 'getDug',
'duf' => 'getDuf',
'civico' => 'getCivico',
'altro_civico' => 'getAltroCivico',
'frazione' => 'getFrazione',
'localita' => 'getLocalita',
'provincia' => 'getProvincia',
'cap' => 'getCap',
'codice_nazione' => 'getCodiceNazione',
'indirizzi' => 'getIndirizzi',
'recapiti' => 'getRecapiti',
'campagna' => 'getCampagna',
'id_campagna' => 'getIdCampagna',
'professione' => 'getProfessione',
'titolo_studio' => 'getTitoloStudio',
'figli' => 'getFigli',
'codice_tessera' => 'getCodiceTessera',
'evento' => 'getEvento',
'data_scadenza_tessera' => 'getDataScadenzaTessera',
'data_emissione_tessera' => 'getDataEmissioneTessera',
'flag_emissione_tessera' => 'getFlagEmissioneTessera',
'privacy' => 'getPrivacy',
'specifiche' => 'getSpecifiche',
'profilazioni' => 'getProfilazioni',
'subscriptions' => 'getSubscriptions',
'gruppi' => 'getGruppi',
'flag_deceduto' => 'getFlagDeceduto',
'_data_decesso' => 'getDataDecesso',
'data_decesso' => 'getDataDecesso',
'utente' => 'getUtente'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['codice'] = isset($data['codice']) ? $data['codice'] : null;
$this->container['codice_origine'] = isset($data['codice_origine']) ? $data['codice_origine'] : null;
$this->container['tipo_master'] = isset($data['tipo_master']) ? $data['tipo_master'] : null;
$this->container['codice_master'] = isset($data['codice_master']) ? $data['codice_master'] : null;
$this->container['codice_web'] = isset($data['codice_web']) ? $data['codice_web'] : null;
$this->container['codice_presentatore'] = isset($data['codice_presentatore']) ? $data['codice_presentatore'] : null;
$this->container['tipo'] = isset($data['tipo']) ? $data['tipo'] : null;
$this->container['sottotipo'] = isset($data['sottotipo']) ? $data['sottotipo'] : null;
$this->container['fonte'] = isset($data['fonte']) ? $data['fonte'] : null;
$this->container['lista_origine'] = isset($data['lista_origine']) ? $data['lista_origine'] : null;
$this->container['codice_manifestazione'] = isset($data['codice_manifestazione']) ? $data['codice_manifestazione'] : null;
$this->container['id_appellativo'] = isset($data['id_appellativo']) ? $data['id_appellativo'] : null;
$this->container['titolo'] = isset($data['titolo']) ? $data['titolo'] : null;
$this->container['data_raccolta'] = isset($data['data_raccolta']) ? $data['data_raccolta'] : null;
$this->container['lotto'] = isset($data['lotto']) ? $data['lotto'] : null;
$this->container['nome'] = isset($data['nome']) ? $data['nome'] : null;
$this->container['cognome'] = isset($data['cognome']) ? $data['cognome'] : null;
$this->container['ragione_sociale'] = isset($data['ragione_sociale']) ? $data['ragione_sociale'] : null;
$this->container['genere'] = isset($data['genere']) ? $data['genere'] : null;
$this->container['data_nascita'] = isset($data['data_nascita']) ? $data['data_nascita'] : null;
$this->container['luogo_nascita'] = isset($data['luogo_nascita']) ? $data['luogo_nascita'] : null;
$this->container['codice_fiscale'] = isset($data['codice_fiscale']) ? $data['codice_fiscale'] : null;
$this->container['partita_iva'] = isset($data['partita_iva']) ? $data['partita_iva'] : null;
$this->container['email1'] = isset($data['email1']) ? $data['email1'] : null;
$this->container['email2'] = isset($data['email2']) ? $data['email2'] : null;
$this->container['telefono1'] = isset($data['telefono1']) ? $data['telefono1'] : null;
$this->container['telefono2'] = isset($data['telefono2']) ? $data['telefono2'] : null;
$this->container['cellulare1'] = isset($data['cellulare1']) ? $data['cellulare1'] : null;
$this->container['cellulare2'] = isset($data['cellulare2']) ? $data['cellulare2'] : null;
$this->container['presso'] = isset($data['presso']) ? $data['presso'] : null;
$this->container['dug'] = isset($data['dug']) ? $data['dug'] : null;
$this->container['duf'] = isset($data['duf']) ? $data['duf'] : null;
$this->container['civico'] = isset($data['civico']) ? $data['civico'] : null;
$this->container['altro_civico'] = isset($data['altro_civico']) ? $data['altro_civico'] : null;
$this->container['frazione'] = isset($data['frazione']) ? $data['frazione'] : null;
$this->container['localita'] = isset($data['localita']) ? $data['localita'] : null;
$this->container['provincia'] = isset($data['provincia']) ? $data['provincia'] : null;
$this->container['cap'] = isset($data['cap']) ? $data['cap'] : null;
$this->container['codice_nazione'] = isset($data['codice_nazione']) ? $data['codice_nazione'] : null;
$this->container['indirizzi'] = isset($data['indirizzi']) ? $data['indirizzi'] : null;
$this->container['recapiti'] = isset($data['recapiti']) ? $data['recapiti'] : null;
$this->container['campagna'] = isset($data['campagna']) ? $data['campagna'] : null;
$this->container['id_campagna'] = isset($data['id_campagna']) ? $data['id_campagna'] : null;
$this->container['professione'] = isset($data['professione']) ? $data['professione'] : null;
$this->container['titolo_studio'] = isset($data['titolo_studio']) ? $data['titolo_studio'] : null;
$this->container['figli'] = isset($data['figli']) ? $data['figli'] : null;
$this->container['codice_tessera'] = isset($data['codice_tessera']) ? $data['codice_tessera'] : null;
$this->container['evento'] = isset($data['evento']) ? $data['evento'] : null;
$this->container['data_scadenza_tessera'] = isset($data['data_scadenza_tessera']) ? $data['data_scadenza_tessera'] : null;
$this->container['data_emissione_tessera'] = isset($data['data_emissione_tessera']) ? $data['data_emissione_tessera'] : null;
$this->container['flag_emissione_tessera'] = isset($data['flag_emissione_tessera']) ? $data['flag_emissione_tessera'] : null;
$this->container['privacy'] = isset($data['privacy']) ? $data['privacy'] : null;
$this->container['specifiche'] = isset($data['specifiche']) ? $data['specifiche'] : null;
$this->container['profilazioni'] = isset($data['profilazioni']) ? $data['profilazioni'] : null;
$this->container['subscriptions'] = isset($data['subscriptions']) ? $data['subscriptions'] : null;
$this->container['gruppi'] = isset($data['gruppi']) ? $data['gruppi'] : null;
$this->container['flag_deceduto'] = isset($data['flag_deceduto']) ? $data['flag_deceduto'] : null;
$this->container['_data_decesso'] = isset($data['_data_decesso']) ? $data['_data_decesso'] : null;
$this->container['data_decesso'] = isset($data['data_decesso']) ? $data['data_decesso'] : null;
$this->container['utente'] = isset($data['utente']) ? $data['utente'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets codice
*
* @return string
*/
public function getCodice()
{
return $this->container['codice'];
}
/**
* Sets codice
*
* @param string $codice codice
*
* @return $this
*/
public function setCodice($codice)
{
$this->container['codice'] = $codice;
return $this;
}
/**
* Gets codice_origine
*
* @return string
*/
public function getCodiceOrigine()
{
return $this->container['codice_origine'];
}
/**
* Sets codice_origine
*
* @param string $codice_origine codice_origine
*
* @return $this
*/
public function setCodiceOrigine($codice_origine)
{
$this->container['codice_origine'] = $codice_origine;
return $this;
}
/**
* Gets tipo_master
*
* @return object
*/
public function getTipoMaster()
{
return $this->container['tipo_master'];
}
/**
* Sets tipo_master
*
* @param object $tipo_master tipo_master
*
* @return $this
*/
public function setTipoMaster($tipo_master)
{
$this->container['tipo_master'] = $tipo_master;
return $this;
}
/**
* Gets codice_master
*
* @return string
*/
public function getCodiceMaster()
{
return $this->container['codice_master'];
}
/**
* Sets codice_master
*
* @param string $codice_master codice_master
*
* @return $this
*/
public function setCodiceMaster($codice_master)
{
$this->container['codice_master'] = $codice_master;
return $this;
}
/**
* Gets codice_web
*
* @return string
*/
public function getCodiceWeb()
{
return $this->container['codice_web'];
}
/**
* Sets codice_web
*
* @param string $codice_web codice_web
*
* @return $this
*/
public function setCodiceWeb($codice_web)
{
$this->container['codice_web'] = $codice_web;
return $this;
}
/**
* Gets codice_presentatore
*
* @return string
*/
public function getCodicePresentatore()
{
return $this->container['codice_presentatore'];
}
/**
* Sets codice_presentatore
*
* @param string $codice_presentatore codice_presentatore
*
* @return $this
*/
public function setCodicePresentatore($codice_presentatore)
{
$this->container['codice_presentatore'] = $codice_presentatore;
return $this;
}
/**
* Gets tipo
*
* @return object
*/
public function getTipo()
{
return $this->container['tipo'];
}
/**
* Sets tipo
*
* @param object $tipo tipo
*
* @return $this
*/
public function setTipo($tipo)
{
$this->container['tipo'] = $tipo;
return $this;
}
/**
* Gets sottotipo
*
* @return object
*/
public function getSottotipo()
{
return $this->container['sottotipo'];
}
/**
* Sets sottotipo
*
* @param object $sottotipo sottotipo
*
* @return $this
*/
public function setSottotipo($sottotipo)
{
$this->container['sottotipo'] = $sottotipo;
return $this;
}
/**
* Gets fonte
*
* @return object
*/
public function getFonte()
{
return $this->container['fonte'];
}
/**
* Sets fonte
*
* @param object $fonte fonte
*
* @return $this
*/
public function setFonte($fonte)
{
$this->container['fonte'] = $fonte;
return $this;
}
/**
* Gets lista_origine
*
* @return object
*/
public function getListaOrigine()
{
return $this->container['lista_origine'];
}
/**
* Sets lista_origine
*
* @param object $lista_origine lista_origine
*
* @return $this
*/
public function setListaOrigine($lista_origine)
{
$this->container['lista_origine'] = $lista_origine;
return $this;
}
/**
* Gets codice_manifestazione
*
* @return string
*/
public function getCodiceManifestazione()
{
return $this->container['codice_manifestazione'];
}
/**
* Sets codice_manifestazione
*
* @param string $codice_manifestazione codice_manifestazione
*
* @return $this
*/
public function setCodiceManifestazione($codice_manifestazione)
{
$this->container['codice_manifestazione'] = $codice_manifestazione;
return $this;
}
/**
* Gets id_appellativo
*
* @return int
*/
public function getIdAppellativo()
{
return $this->container['id_appellativo'];
}
/**
* Sets id_appellativo
*
* @param int $id_appellativo id_appellativo
*
* @return $this
*/
public function setIdAppellativo($id_appellativo)
{
$this->container['id_appellativo'] = $id_appellativo;
return $this;
}
/**
* Gets titolo
*
* @return string
*/
public function getTitolo()
{
return $this->container['titolo'];
}
/**
* Sets titolo
*
* @param string $titolo titolo
*
* @return $this
*/
public function setTitolo($titolo)
{
$this->container['titolo'] = $titolo;
return $this;
}
/**
* Gets data_raccolta
*
* @return string
*/
public function getDataRaccolta()
{
return $this->container['data_raccolta'];
}
/**
* Sets data_raccolta
*
* @param string $data_raccolta data_raccolta
*
* @return $this
*/
public function setDataRaccolta($data_raccolta)
{
$this->container['data_raccolta'] = $data_raccolta;
return $this;
}
/**
* Gets lotto
*
* @return string
*/
public function getLotto()
{
return $this->container['lotto'];
}
/**
* Sets lotto
*
* @param string $lotto lotto
*
* @return $this
*/
public function setLotto($lotto)
{
$this->container['lotto'] = $lotto;
return $this;
}
/**
* Gets nome
*
* @return string
*/
public function getNome()
{
return $this->container['nome'];
}
/**
* Sets nome
*
* @param string $nome nome
*
* @return $this
*/
public function setNome($nome)
{
$this->container['nome'] = $nome;
return $this;
}
/**
* Gets cognome
*
* @return string
*/
public function getCognome()
{
return $this->container['cognome'];
}
/**
* Sets cognome
*
* @param string $cognome cognome
*
* @return $this
*/
public function setCognome($cognome)
{
$this->container['cognome'] = $cognome;
return $this;
}
/**
* Gets ragione_sociale
*
* @return string
*/
public function getRagioneSociale()
{
return $this->container['ragione_sociale'];
}
/**
* Sets ragione_sociale
*
* @param string $ragione_sociale ragione_sociale
*
* @return $this
*/
public function setRagioneSociale($ragione_sociale)
{
$this->container['ragione_sociale'] = $ragione_sociale;
return $this;
}
/**
* Gets genere
*
* @return string
*/
public function getGenere()
{
return $this->container['genere'];
}
/**
* Sets genere
*
* @param string $genere genere
*
* @return $this
*/
public function setGenere($genere)
{
$this->container['genere'] = $genere;
return $this;
}
/**
* Gets data_nascita
*
* @return string
*/
public function getDataNascita()
{
return $this->container['data_nascita'];
}
/**
* Sets data_nascita
*
* @param string $data_nascita data_nascita
*
* @return $this
*/
public function setDataNascita($data_nascita)
{
$this->container['data_nascita'] = $data_nascita;
return $this;
}
/**
* Gets luogo_nascita
*
* @return string
*/
public function getLuogoNascita()
{
return $this->container['luogo_nascita'];
}
/**
* Sets luogo_nascita
*
* @param string $luogo_nascita luogo_nascita
*
* @return $this
*/
public function setLuogoNascita($luogo_nascita)
{
$this->container['luogo_nascita'] = $luogo_nascita;
return $this;
}
/**
* Gets codice_fiscale
*
* @return string
*/
public function getCodiceFiscale()
{
return $this->container['codice_fiscale'];
}
/**
* Sets codice_fiscale
*
* @param string $codice_fiscale codice_fiscale
*
* @return $this
*/
public function setCodiceFiscale($codice_fiscale)
{
$this->container['codice_fiscale'] = $codice_fiscale;
return $this;
}
/**
* Gets partita_iva
*
* @return string
*/
public function getPartitaIva()
{
return $this->container['partita_iva'];
}
/**
* Sets partita_iva
*
* @param string $partita_iva partita_iva
*
* @return $this
*/
public function setPartitaIva($partita_iva)
{
$this->container['partita_iva'] = $partita_iva;
return $this;
}
/**
* Gets email1
*
* @return string
*/
public function getEmail1()
{
return $this->container['email1'];
}
/**
* Sets email1
*
* @param string $email1 email1
*
* @return $this
*/
public function setEmail1($email1)
{
$this->container['email1'] = $email1;
return $this;
}
/**
* Gets email2
*
* @return string
*/
public function getEmail2()
{
return $this->container['email2'];
}
/**
* Sets email2
*
* @param string $email2 email2
*
* @return $this
*/
public function setEmail2($email2)
{
$this->container['email2'] = $email2;
return $this;
}
/**
* Gets telefono1
*
* @return string
*/
public function getTelefono1()
{
return $this->container['telefono1'];
}
/**
* Sets telefono1
*
* @param string $telefono1 telefono1
*
* @return $this
*/
public function setTelefono1($telefono1)
{
$this->container['telefono1'] = $telefono1;
return $this;
}
/**
* Gets telefono2
*
* @return string
*/
public function getTelefono2()
{
return $this->container['telefono2'];
}
/**
* Sets telefono2
*
* @param string $telefono2 telefono2
*
* @return $this
*/
public function setTelefono2($telefono2)
{
$this->container['telefono2'] = $telefono2;
return $this;
}
/**
* Gets cellulare1
*
* @return string
*/
public function getCellulare1()
{
return $this->container['cellulare1'];
}
/**
* Sets cellulare1
*
* @param string $cellulare1 cellulare1
*
* @return $this
*/
public function setCellulare1($cellulare1)
{
$this->container['cellulare1'] = $cellulare1;
return $this;
}
/**
* Gets cellulare2
*
* @return string
*/
public function getCellulare2()
{
return $this->container['cellulare2'];
}
/**
* Sets cellulare2
*
* @param string $cellulare2 cellulare2
*
* @return $this
*/
public function setCellulare2($cellulare2)
{
$this->container['cellulare2'] = $cellulare2;
return $this;
}
/**
* Gets presso
*
* @return string
*/
public function getPresso()
{
return $this->container['presso'];
}
/**
* Sets presso
*
* @param string $presso presso
*
* @return $this
*/
public function setPresso($presso)
{
$this->container['presso'] = $presso;
return $this;
}
/**
* Gets dug
*
* @return string
*/
public function getDug()
{
return $this->container['dug'];
}
/**
* Sets dug
*
* @param string $dug dug
*
* @return $this
*/
public function setDug($dug)
{
$this->container['dug'] = $dug;
return $this;
}
/**
* Gets duf
*
* @return string
*/
public function getDuf()
{
return $this->container['duf'];
}
/**
* Sets duf
*
* @param string $duf duf
*
* @return $this
*/
public function setDuf($duf)
{
$this->container['duf'] = $duf;
return $this;
}
/**
* Gets civico
*
* @return string
*/
public function getCivico()
{
return $this->container['civico'];
}
/**
* Sets civico
*
* @param string $civico civico
*
* @return $this
*/
public function setCivico($civico)
{
$this->container['civico'] = $civico;
return $this;
}
/**
* Gets altro_civico
*
* @return string
*/
public function getAltroCivico()
{
return $this->container['altro_civico'];
}
/**
* Sets altro_civico
*
* @param string $altro_civico altro_civico
*
* @return $this
*/
public function setAltroCivico($altro_civico)
{
$this->container['altro_civico'] = $altro_civico;
return $this;
}
/**
* Gets frazione
*
* @return string
*/
public function getFrazione()
{
return $this->container['frazione'];
}
/**
* Sets frazione
*
* @param string $frazione frazione
*
* @return $this
*/
public function setFrazione($frazione)
{
$this->container['frazione'] = $frazione;
return $this;
}
/**
* Gets localita
*
* @return string
*/
public function getLocalita()
{
return $this->container['localita'];
}
/**
* Sets localita
*
* @param string $localita localita
*
* @return $this
*/
public function setLocalita($localita)
{
$this->container['localita'] = $localita;
return $this;
}
/**
* Gets provincia
*
* @return string
*/
public function getProvincia()
{
return $this->container['provincia'];
}
/**
* Sets provincia
*
* @param string $provincia provincia
*
* @return $this
*/
public function setProvincia($provincia)
{
$this->container['provincia'] = $provincia;
return $this;
}
/**
* Gets cap
*
* @return string
*/
public function getCap()
{
return $this->container['cap'];
}
/**
* Sets cap
*
* @param string $cap cap
*
* @return $this
*/
public function setCap($cap)
{
$this->container['cap'] = $cap;
return $this;
}
/**
* Gets codice_nazione
*
* @return string
*/
public function getCodiceNazione()
{
return $this->container['codice_nazione'];
}
/**
* Sets codice_nazione
*
* @param string $codice_nazione codice_nazione
*
* @return $this
*/
public function setCodiceNazione($codice_nazione)
{
$this->container['codice_nazione'] = $codice_nazione;
return $this;
}
/**
* Gets indirizzi
*
* @return \Swagger\Client\Model\ClientiIndirizzi[]
*/
public function getIndirizzi()
{
return $this->container['indirizzi'];
}
/**
* Sets indirizzi
*
* @param \Swagger\Client\Model\ClientiIndirizzi[] $indirizzi indirizzi
*
* @return $this
*/
public function setIndirizzi($indirizzi)
{
$this->container['indirizzi'] = $indirizzi;
return $this;
}
/**
* Gets recapiti
*
* @return \Swagger\Client\Model\ClientiRecapiti[]
*/
public function getRecapiti()
{
return $this->container['recapiti'];
}
/**
* Sets recapiti
*
* @param \Swagger\Client\Model\ClientiRecapiti[] $recapiti recapiti
*
* @return $this
*/
public function setRecapiti($recapiti)
{
$this->container['recapiti'] = $recapiti;
return $this;
}
/**
* Gets campagna
*
* @return object
*/
public function getCampagna()
{
return $this->container['campagna'];
}
/**
* Sets campagna
*
* @param object $campagna campagna
*
* @return $this
*/
public function setCampagna($campagna)
{
$this->container['campagna'] = $campagna;
return $this;
}
/**
* Gets id_campagna
*
* @return int
*/
public function getIdCampagna()
{
return $this->container['id_campagna'];
}
/**
* Sets id_campagna
*
* @param int $id_campagna id_campagna
*
* @return $this
*/
public function setIdCampagna($id_campagna)
{
$this->container['id_campagna'] = $id_campagna;
return $this;
}
/**
* Gets professione
*
* @return object
*/
public function getProfessione()
{
return $this->container['professione'];
}
/**
* Sets professione
*
* @param object $professione professione
*
* @return $this
*/
public function setProfessione($professione)
{
$this->container['professione'] = $professione;
return $this;
}
/**
* Gets titolo_studio
*
* @return object
*/
public function getTitoloStudio()
{
return $this->container['titolo_studio'];
}
/**
* Sets titolo_studio
*
* @param object $titolo_studio titolo_studio
*
* @return $this
*/
public function setTitoloStudio($titolo_studio)
{
$this->container['titolo_studio'] = $titolo_studio;
return $this;
}
/**
* Gets figli
*
* @return string
*/
public function getFigli()
{
return $this->container['figli'];
}
/**
* Sets figli
*
* @param string $figli figli
*
* @return $this
*/
public function setFigli($figli)
{
$this->container['figli'] = $figli;
return $this;
}
/**
* Gets codice_tessera
*
* @return string
*/
public function getCodiceTessera()
{
return $this->container['codice_tessera'];
}
/**
* Sets codice_tessera
*
* @param string $codice_tessera codice_tessera
*
* @return $this
*/
public function setCodiceTessera($codice_tessera)
{
$this->container['codice_tessera'] = $codice_tessera;
return $this;
}
/**
* Gets evento
*
* @return string
*/
public function getEvento()
{
return $this->container['evento'];
}
/**
* Sets evento
*
* @param string $evento evento
*
* @return $this
*/
public function setEvento($evento)
{
$this->container['evento'] = $evento;
return $this;
}
/**
* Gets data_scadenza_tessera
*
* @return string
*/
public function getDataScadenzaTessera()
{
return $this->container['data_scadenza_tessera'];
}
/**
* Sets data_scadenza_tessera
*
* @param string $data_scadenza_tessera data_scadenza_tessera
*
* @return $this
*/
public function setDataScadenzaTessera($data_scadenza_tessera)
{
$this->container['data_scadenza_tessera'] = $data_scadenza_tessera;
return $this;
}
/**
* Gets data_emissione_tessera
*
* @return string
*/
public function getDataEmissioneTessera()
{
return $this->container['data_emissione_tessera'];
}
/**
* Sets data_emissione_tessera
*
* @param string $data_emissione_tessera data_emissione_tessera
*
* @return $this
*/
public function setDataEmissioneTessera($data_emissione_tessera)
{
$this->container['data_emissione_tessera'] = $data_emissione_tessera;
return $this;
}
/**
* Gets flag_emissione_tessera
*
* @return bool
*/
public function getFlagEmissioneTessera()
{
return $this->container['flag_emissione_tessera'];
}
/**
* Sets flag_emissione_tessera
*
* @param bool $flag_emissione_tessera flag_emissione_tessera
*
* @return $this
*/
public function setFlagEmissioneTessera($flag_emissione_tessera)
{
$this->container['flag_emissione_tessera'] = $flag_emissione_tessera;
return $this;
}
/**
* Gets privacy
*
* @return \Swagger\Client\Model\ClientiPrivacy[]
*/
public function getPrivacy()
{
return $this->container['privacy'];
}
/**
* Sets privacy
*
* @param \Swagger\Client\Model\ClientiPrivacy[] $privacy privacy
*
* @return $this
*/
public function setPrivacy($privacy)
{
$this->container['privacy'] = $privacy;
return $this;
}
/**
* Gets specifiche
*
* @return \Swagger\Client\Model\ClientiSpecifiche[]
*/
public function getSpecifiche()
{
return $this->container['specifiche'];
}
/**
* Sets specifiche
*
* @param \Swagger\Client\Model\ClientiSpecifiche[] $specifiche specifiche
*
* @return $this
*/
public function setSpecifiche($specifiche)
{
$this->container['specifiche'] = $specifiche;
return $this;
}
/**
* Gets profilazioni
*
* @return \Swagger\Client\Model\ClientiProfilazioni[]
*/
public function getProfilazioni()
{
return $this->container['profilazioni'];
}
/**
* Sets profilazioni
*
* @param \Swagger\Client\Model\ClientiProfilazioni[] $profilazioni profilazioni
*
* @return $this
*/
public function setProfilazioni($profilazioni)
{
$this->container['profilazioni'] = $profilazioni;
return $this;
}
/**
* Gets subscriptions
*
* @return \Swagger\Client\Model\ClientiSubscription[]
*/
public function getSubscriptions()
{
return $this->container['subscriptions'];
}
/**
* Sets subscriptions
*
* @param \Swagger\Client\Model\ClientiSubscription[] $subscriptions subscriptions
*
* @return $this
*/
public function setSubscriptions($subscriptions)
{
$this->container['subscriptions'] = $subscriptions;
return $this;
}
/**
* Gets gruppi
*
* @return \Swagger\Client\Model\ClientiGruppi[]
*/
public function getGruppi()
{
return $this->container['gruppi'];
}
/**
* Sets gruppi
*
* @param \Swagger\Client\Model\ClientiGruppi[] $gruppi gruppi
*
* @return $this
*/
public function setGruppi($gruppi)
{
$this->container['gruppi'] = $gruppi;
return $this;
}
/**
* Gets flag_deceduto
*
* @return bool
*/
public function getFlagDeceduto()
{
return $this->container['flag_deceduto'];
}
/**
* Sets flag_deceduto
*
* @param bool $flag_deceduto flag_deceduto
*
* @return $this
*/
public function setFlagDeceduto($flag_deceduto)
{
$this->container['flag_deceduto'] = $flag_deceduto;
return $this;
}
/**
* Gets _data_decesso
*
* @return int
*/
public function getDataDecesso()
{
return $this->container['_data_decesso'];
}
/**
* Sets _data_decesso
*
* @param int $_data_decesso _data_decesso
*
* @return $this
*/
public function setDataDecesso($_data_decesso)
{
$this->container['_data_decesso'] = $_data_decesso;
return $this;
}
/**
* Gets data_decesso
*
* @return string
*/
public function getDataDecesso()
{
return $this->container['data_decesso'];
}
/**
* Sets data_decesso
*
* @param string $data_decesso data_decesso
*
* @return $this
*/
public function setDataDecesso($data_decesso)
{
$this->container['data_decesso'] = $data_decesso;
return $this;
}
/**
* Gets utente
*
* @return string
*/
public function getUtente()
{
return $this->container['utente'];
}
/**
* Sets utente
*
* @param string $utente utente
*
* @return $this
*/
public function setUtente($utente)
{
$this->container['utente'] = $utente;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep><?php
/**
* Attivita
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace Swagger\Client\Model;
use \ArrayAccess;
use \Swagger\Client\ObjectSerializer;
/**
* Attivita Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class Attivita implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'Attivita';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'id_attivita' => 'int',
'id_regolare' => 'int',
'id_versamenti' => 'int',
'codice_donatore' => 'string',
'campagna' => 'object',
'canale' => 'object',
'pagamento' => 'object',
'bambino' => 'object',
'progetto' => 'object',
'esito' => 'object',
'id_lascito' => 'int',
'data_attivita' => 'string',
'ora_attivita' => 'string',
'utente_assegnatario' => 'string',
'gruppo_utenti_assegnatario' => 'object',
'id_gruppo' => 'int',
'evento' => 'object',
'sollecito' => 'object',
'motivo_rifiuto_ask' => 'object',
'tipo_incidenza' => 'object',
'tipo' => 'object',
'sottotipo' => 'object',
'stato' => 'object',
'importo' => 'float',
'oggetto' => 'string',
'note' => 'string',
'data_chiusura' => 'string',
'link' => 'string',
'lotto' => 'string',
'template' => 'string'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'id_attivita' => 'int32',
'id_regolare' => 'int32',
'id_versamenti' => 'int32',
'codice_donatore' => null,
'campagna' => null,
'canale' => null,
'pagamento' => null,
'bambino' => null,
'progetto' => null,
'esito' => null,
'id_lascito' => 'int32',
'data_attivita' => null,
'ora_attivita' => null,
'utente_assegnatario' => null,
'gruppo_utenti_assegnatario' => null,
'id_gruppo' => 'int32',
'evento' => null,
'sollecito' => null,
'motivo_rifiuto_ask' => null,
'tipo_incidenza' => null,
'tipo' => null,
'sottotipo' => null,
'stato' => null,
'importo' => 'float',
'oggetto' => null,
'note' => null,
'data_chiusura' => null,
'link' => null,
'lotto' => null,
'template' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'id_attivita' => 'IdAttivita',
'id_regolare' => 'IdRegolare',
'id_versamenti' => 'IdVersamenti',
'codice_donatore' => 'CodiceDonatore',
'campagna' => 'Campagna',
'canale' => 'Canale',
'pagamento' => 'Pagamento',
'bambino' => 'Bambino',
'progetto' => 'Progetto',
'esito' => 'Esito',
'id_lascito' => 'IdLascito',
'data_attivita' => 'DataAttivita',
'ora_attivita' => 'OraAttivita',
'utente_assegnatario' => 'UtenteAssegnatario',
'gruppo_utenti_assegnatario' => 'GruppoUtentiAssegnatario',
'id_gruppo' => 'IdGruppo',
'evento' => 'Evento',
'sollecito' => 'Sollecito',
'motivo_rifiuto_ask' => 'MotivoRifiutoASK',
'tipo_incidenza' => 'TipoIncidenza',
'tipo' => 'Tipo',
'sottotipo' => 'Sottotipo',
'stato' => 'Stato',
'importo' => 'importo',
'oggetto' => 'Oggetto',
'note' => 'Note',
'data_chiusura' => 'DataChiusura',
'link' => 'Link',
'lotto' => 'Lotto',
'template' => 'Template'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'id_attivita' => 'setIdAttivita',
'id_regolare' => 'setIdRegolare',
'id_versamenti' => 'setIdVersamenti',
'codice_donatore' => 'setCodiceDonatore',
'campagna' => 'setCampagna',
'canale' => 'setCanale',
'pagamento' => 'setPagamento',
'bambino' => 'setBambino',
'progetto' => 'setProgetto',
'esito' => 'setEsito',
'id_lascito' => 'setIdLascito',
'data_attivita' => 'setDataAttivita',
'ora_attivita' => 'setOraAttivita',
'utente_assegnatario' => 'setUtenteAssegnatario',
'gruppo_utenti_assegnatario' => 'setGruppoUtentiAssegnatario',
'id_gruppo' => 'setIdGruppo',
'evento' => 'setEvento',
'sollecito' => 'setSollecito',
'motivo_rifiuto_ask' => 'setMotivoRifiutoAsk',
'tipo_incidenza' => 'setTipoIncidenza',
'tipo' => 'setTipo',
'sottotipo' => 'setSottotipo',
'stato' => 'setStato',
'importo' => 'setImporto',
'oggetto' => 'setOggetto',
'note' => 'setNote',
'data_chiusura' => 'setDataChiusura',
'link' => 'setLink',
'lotto' => 'setLotto',
'template' => 'setTemplate'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'id_attivita' => 'getIdAttivita',
'id_regolare' => 'getIdRegolare',
'id_versamenti' => 'getIdVersamenti',
'codice_donatore' => 'getCodiceDonatore',
'campagna' => 'getCampagna',
'canale' => 'getCanale',
'pagamento' => 'getPagamento',
'bambino' => 'getBambino',
'progetto' => 'getProgetto',
'esito' => 'getEsito',
'id_lascito' => 'getIdLascito',
'data_attivita' => 'getDataAttivita',
'ora_attivita' => 'getOraAttivita',
'utente_assegnatario' => 'getUtenteAssegnatario',
'gruppo_utenti_assegnatario' => 'getGruppoUtentiAssegnatario',
'id_gruppo' => 'getIdGruppo',
'evento' => 'getEvento',
'sollecito' => 'getSollecito',
'motivo_rifiuto_ask' => 'getMotivoRifiutoAsk',
'tipo_incidenza' => 'getTipoIncidenza',
'tipo' => 'getTipo',
'sottotipo' => 'getSottotipo',
'stato' => 'getStato',
'importo' => 'getImporto',
'oggetto' => 'getOggetto',
'note' => 'getNote',
'data_chiusura' => 'getDataChiusura',
'link' => 'getLink',
'lotto' => 'getLotto',
'template' => 'getTemplate'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['id_attivita'] = isset($data['id_attivita']) ? $data['id_attivita'] : null;
$this->container['id_regolare'] = isset($data['id_regolare']) ? $data['id_regolare'] : null;
$this->container['id_versamenti'] = isset($data['id_versamenti']) ? $data['id_versamenti'] : null;
$this->container['codice_donatore'] = isset($data['codice_donatore']) ? $data['codice_donatore'] : null;
$this->container['campagna'] = isset($data['campagna']) ? $data['campagna'] : null;
$this->container['canale'] = isset($data['canale']) ? $data['canale'] : null;
$this->container['pagamento'] = isset($data['pagamento']) ? $data['pagamento'] : null;
$this->container['bambino'] = isset($data['bambino']) ? $data['bambino'] : null;
$this->container['progetto'] = isset($data['progetto']) ? $data['progetto'] : null;
$this->container['esito'] = isset($data['esito']) ? $data['esito'] : null;
$this->container['id_lascito'] = isset($data['id_lascito']) ? $data['id_lascito'] : null;
$this->container['data_attivita'] = isset($data['data_attivita']) ? $data['data_attivita'] : null;
$this->container['ora_attivita'] = isset($data['ora_attivita']) ? $data['ora_attivita'] : null;
$this->container['utente_assegnatario'] = isset($data['utente_assegnatario']) ? $data['utente_assegnatario'] : null;
$this->container['gruppo_utenti_assegnatario'] = isset($data['gruppo_utenti_assegnatario']) ? $data['gruppo_utenti_assegnatario'] : null;
$this->container['id_gruppo'] = isset($data['id_gruppo']) ? $data['id_gruppo'] : null;
$this->container['evento'] = isset($data['evento']) ? $data['evento'] : null;
$this->container['sollecito'] = isset($data['sollecito']) ? $data['sollecito'] : null;
$this->container['motivo_rifiuto_ask'] = isset($data['motivo_rifiuto_ask']) ? $data['motivo_rifiuto_ask'] : null;
$this->container['tipo_incidenza'] = isset($data['tipo_incidenza']) ? $data['tipo_incidenza'] : null;
$this->container['tipo'] = isset($data['tipo']) ? $data['tipo'] : null;
$this->container['sottotipo'] = isset($data['sottotipo']) ? $data['sottotipo'] : null;
$this->container['stato'] = isset($data['stato']) ? $data['stato'] : null;
$this->container['importo'] = isset($data['importo']) ? $data['importo'] : null;
$this->container['oggetto'] = isset($data['oggetto']) ? $data['oggetto'] : null;
$this->container['note'] = isset($data['note']) ? $data['note'] : null;
$this->container['data_chiusura'] = isset($data['data_chiusura']) ? $data['data_chiusura'] : null;
$this->container['link'] = isset($data['link']) ? $data['link'] : null;
$this->container['lotto'] = isset($data['lotto']) ? $data['lotto'] : null;
$this->container['template'] = isset($data['template']) ? $data['template'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets id_attivita
*
* @return int
*/
public function getIdAttivita()
{
return $this->container['id_attivita'];
}
/**
* Sets id_attivita
*
* @param int $id_attivita id_attivita
*
* @return $this
*/
public function setIdAttivita($id_attivita)
{
$this->container['id_attivita'] = $id_attivita;
return $this;
}
/**
* Gets id_regolare
*
* @return int
*/
public function getIdRegolare()
{
return $this->container['id_regolare'];
}
/**
* Sets id_regolare
*
* @param int $id_regolare id_regolare
*
* @return $this
*/
public function setIdRegolare($id_regolare)
{
$this->container['id_regolare'] = $id_regolare;
return $this;
}
/**
* Gets id_versamenti
*
* @return int
*/
public function getIdVersamenti()
{
return $this->container['id_versamenti'];
}
/**
* Sets id_versamenti
*
* @param int $id_versamenti id_versamenti
*
* @return $this
*/
public function setIdVersamenti($id_versamenti)
{
$this->container['id_versamenti'] = $id_versamenti;
return $this;
}
/**
* Gets codice_donatore
*
* @return string
*/
public function getCodiceDonatore()
{
return $this->container['codice_donatore'];
}
/**
* Sets codice_donatore
*
* @param string $codice_donatore codice_donatore
*
* @return $this
*/
public function setCodiceDonatore($codice_donatore)
{
$this->container['codice_donatore'] = $codice_donatore;
return $this;
}
/**
* Gets campagna
*
* @return object
*/
public function getCampagna()
{
return $this->container['campagna'];
}
/**
* Sets campagna
*
* @param object $campagna campagna
*
* @return $this
*/
public function setCampagna($campagna)
{
$this->container['campagna'] = $campagna;
return $this;
}
/**
* Gets canale
*
* @return object
*/
public function getCanale()
{
return $this->container['canale'];
}
/**
* Sets canale
*
* @param object $canale canale
*
* @return $this
*/
public function setCanale($canale)
{
$this->container['canale'] = $canale;
return $this;
}
/**
* Gets pagamento
*
* @return object
*/
public function getPagamento()
{
return $this->container['pagamento'];
}
/**
* Sets pagamento
*
* @param object $pagamento pagamento
*
* @return $this
*/
public function setPagamento($pagamento)
{
$this->container['pagamento'] = $pagamento;
return $this;
}
/**
* Gets bambino
*
* @return object
*/
public function getBambino()
{
return $this->container['bambino'];
}
/**
* Sets bambino
*
* @param object $bambino bambino
*
* @return $this
*/
public function setBambino($bambino)
{
$this->container['bambino'] = $bambino;
return $this;
}
/**
* Gets progetto
*
* @return object
*/
public function getProgetto()
{
return $this->container['progetto'];
}
/**
* Sets progetto
*
* @param object $progetto progetto
*
* @return $this
*/
public function setProgetto($progetto)
{
$this->container['progetto'] = $progetto;
return $this;
}
/**
* Gets esito
*
* @return object
*/
public function getEsito()
{
return $this->container['esito'];
}
/**
* Sets esito
*
* @param object $esito esito
*
* @return $this
*/
public function setEsito($esito)
{
$this->container['esito'] = $esito;
return $this;
}
/**
* Gets id_lascito
*
* @return int
*/
public function getIdLascito()
{
return $this->container['id_lascito'];
}
/**
* Sets id_lascito
*
* @param int $id_lascito id_lascito
*
* @return $this
*/
public function setIdLascito($id_lascito)
{
$this->container['id_lascito'] = $id_lascito;
return $this;
}
/**
* Gets data_attivita
*
* @return string
*/
public function getDataAttivita()
{
return $this->container['data_attivita'];
}
/**
* Sets data_attivita
*
* @param string $data_attivita data_attivita
*
* @return $this
*/
public function setDataAttivita($data_attivita)
{
$this->container['data_attivita'] = $data_attivita;
return $this;
}
/**
* Gets ora_attivita
*
* @return string
*/
public function getOraAttivita()
{
return $this->container['ora_attivita'];
}
/**
* Sets ora_attivita
*
* @param string $ora_attivita ora_attivita
*
* @return $this
*/
public function setOraAttivita($ora_attivita)
{
$this->container['ora_attivita'] = $ora_attivita;
return $this;
}
/**
* Gets utente_assegnatario
*
* @return string
*/
public function getUtenteAssegnatario()
{
return $this->container['utente_assegnatario'];
}
/**
* Sets utente_assegnatario
*
* @param string $utente_assegnatario utente_assegnatario
*
* @return $this
*/
public function setUtenteAssegnatario($utente_assegnatario)
{
$this->container['utente_assegnatario'] = $utente_assegnatario;
return $this;
}
/**
* Gets gruppo_utenti_assegnatario
*
* @return object
*/
public function getGruppoUtentiAssegnatario()
{
return $this->container['gruppo_utenti_assegnatario'];
}
/**
* Sets gruppo_utenti_assegnatario
*
* @param object $gruppo_utenti_assegnatario gruppo_utenti_assegnatario
*
* @return $this
*/
public function setGruppoUtentiAssegnatario($gruppo_utenti_assegnatario)
{
$this->container['gruppo_utenti_assegnatario'] = $gruppo_utenti_assegnatario;
return $this;
}
/**
* Gets id_gruppo
*
* @return int
*/
public function getIdGruppo()
{
return $this->container['id_gruppo'];
}
/**
* Sets id_gruppo
*
* @param int $id_gruppo id_gruppo
*
* @return $this
*/
public function setIdGruppo($id_gruppo)
{
$this->container['id_gruppo'] = $id_gruppo;
return $this;
}
/**
* Gets evento
*
* @return object
*/
public function getEvento()
{
return $this->container['evento'];
}
/**
* Sets evento
*
* @param object $evento evento
*
* @return $this
*/
public function setEvento($evento)
{
$this->container['evento'] = $evento;
return $this;
}
/**
* Gets sollecito
*
* @return object
*/
public function getSollecito()
{
return $this->container['sollecito'];
}
/**
* Sets sollecito
*
* @param object $sollecito sollecito
*
* @return $this
*/
public function setSollecito($sollecito)
{
$this->container['sollecito'] = $sollecito;
return $this;
}
/**
* Gets motivo_rifiuto_ask
*
* @return object
*/
public function getMotivoRifiutoAsk()
{
return $this->container['motivo_rifiuto_ask'];
}
/**
* Sets motivo_rifiuto_ask
*
* @param object $motivo_rifiuto_ask motivo_rifiuto_ask
*
* @return $this
*/
public function setMotivoRifiutoAsk($motivo_rifiuto_ask)
{
$this->container['motivo_rifiuto_ask'] = $motivo_rifiuto_ask;
return $this;
}
/**
* Gets tipo_incidenza
*
* @return object
*/
public function getTipoIncidenza()
{
return $this->container['tipo_incidenza'];
}
/**
* Sets tipo_incidenza
*
* @param object $tipo_incidenza tipo_incidenza
*
* @return $this
*/
public function setTipoIncidenza($tipo_incidenza)
{
$this->container['tipo_incidenza'] = $tipo_incidenza;
return $this;
}
/**
* Gets tipo
*
* @return object
*/
public function getTipo()
{
return $this->container['tipo'];
}
/**
* Sets tipo
*
* @param object $tipo tipo
*
* @return $this
*/
public function setTipo($tipo)
{
$this->container['tipo'] = $tipo;
return $this;
}
/**
* Gets sottotipo
*
* @return object
*/
public function getSottotipo()
{
return $this->container['sottotipo'];
}
/**
* Sets sottotipo
*
* @param object $sottotipo sottotipo
*
* @return $this
*/
public function setSottotipo($sottotipo)
{
$this->container['sottotipo'] = $sottotipo;
return $this;
}
/**
* Gets stato
*
* @return object
*/
public function getStato()
{
return $this->container['stato'];
}
/**
* Sets stato
*
* @param object $stato stato
*
* @return $this
*/
public function setStato($stato)
{
$this->container['stato'] = $stato;
return $this;
}
/**
* Gets importo
*
* @return float
*/
public function getImporto()
{
return $this->container['importo'];
}
/**
* Sets importo
*
* @param float $importo importo
*
* @return $this
*/
public function setImporto($importo)
{
$this->container['importo'] = $importo;
return $this;
}
/**
* Gets oggetto
*
* @return string
*/
public function getOggetto()
{
return $this->container['oggetto'];
}
/**
* Sets oggetto
*
* @param string $oggetto oggetto
*
* @return $this
*/
public function setOggetto($oggetto)
{
$this->container['oggetto'] = $oggetto;
return $this;
}
/**
* Gets note
*
* @return string
*/
public function getNote()
{
return $this->container['note'];
}
/**
* Sets note
*
* @param string $note note
*
* @return $this
*/
public function setNote($note)
{
$this->container['note'] = $note;
return $this;
}
/**
* Gets data_chiusura
*
* @return string
*/
public function getDataChiusura()
{
return $this->container['data_chiusura'];
}
/**
* Sets data_chiusura
*
* @param string $data_chiusura data_chiusura
*
* @return $this
*/
public function setDataChiusura($data_chiusura)
{
$this->container['data_chiusura'] = $data_chiusura;
return $this;
}
/**
* Gets link
*
* @return string
*/
public function getLink()
{
return $this->container['link'];
}
/**
* Sets link
*
* @param string $link link
*
* @return $this
*/
public function setLink($link)
{
$this->container['link'] = $link;
return $this;
}
/**
* Gets lotto
*
* @return string
*/
public function getLotto()
{
return $this->container['lotto'];
}
/**
* Sets lotto
*
* @param string $lotto lotto
*
* @return $this
*/
public function setLotto($lotto)
{
$this->container['lotto'] = $lotto;
return $this;
}
/**
* Gets template
*
* @return string
*/
public function getTemplate()
{
return $this->container['template'];
}
/**
* Sets template
*
* @param string $template template
*
* @return $this
*/
public function setTemplate($template)
{
$this->container['template'] = $template;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
<file_sep># Adozioni
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id_adozione** | **int** | | [optional]
**codice** | **string** | | [optional]
**nome** | **string** | | [optional]
**cognome** | **string** | | [optional]
**sesso** | **string** | | [optional]
**data_nascita** | **string** | | [optional]
**location** | **string** | | [optional]
**url_foto** | **string** | | [optional]
**nazione** | [**\Swagger\Client\Model\DefaultTable**](DefaultTable.md) | | [optional]
**programma** | [**\Swagger\Client\Model\DefaultTable**](DefaultTable.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
<file_sep><?php
/**
* PeriodiciTest
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Mentor.ApiRest
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.17
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace Swagger\Client;
/**
* PeriodiciTest Class Doc Comment
*
* @category Class
* @description Periodici
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class PeriodiciTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "Periodici"
*/
public function testPeriodici()
{
}
/**
* Test attribute "id"
*/
public function testPropertyId()
{
}
/**
* Test attribute "codice_donatore"
*/
public function testPropertyCodiceDonatore()
{
}
/**
* Test attribute "codice_soggetto_versante"
*/
public function testPropertyCodiceSoggettoVersante()
{
}
/**
* Test attribute "campagna"
*/
public function testPropertyCampagna()
{
}
/**
* Test attribute "centro"
*/
public function testPropertyCentro()
{
}
/**
* Test attribute "canale"
*/
public function testPropertyCanale()
{
}
/**
* Test attribute "codice_bambino"
*/
public function testPropertyCodiceBambino()
{
}
/**
* Test attribute "progetto"
*/
public function testPropertyProgetto()
{
}
/**
* Test attribute "tema"
*/
public function testPropertyTema()
{
}
/**
* Test attribute "stato"
*/
public function testPropertyStato()
{
}
/**
* Test attribute "importo"
*/
public function testPropertyImporto()
{
}
/**
* Test attribute "frequenza"
*/
public function testPropertyFrequenza()
{
}
/**
* Test attribute "metodo_pagamento"
*/
public function testPropertyMetodoPagamento()
{
}
/**
* Test attribute "data_richiesta"
*/
public function testPropertyDataRichiesta()
{
}
/**
* Test attribute "ora_richiesta"
*/
public function testPropertyOraRichiesta()
{
}
/**
* Test attribute "data_delega"
*/
public function testPropertyDataDelega()
{
}
/**
* Test attribute "data_promessa"
*/
public function testPropertyDataPromessa()
{
}
/**
* Test attribute "data_prossima_richiesta"
*/
public function testPropertyDataProssimaRichiesta()
{
}
/**
* Test attribute "codice_dialogatore_interno"
*/
public function testPropertyCodiceDialogatoreInterno()
{
}
/**
* Test attribute "codice_dialogatore_esterno"
*/
public function testPropertyCodiceDialogatoreEsterno()
{
}
/**
* Test attribute "nome_dialogatore_esterno"
*/
public function testPropertyNomeDialogatoreEsterno()
{
}
/**
* Test attribute "urn"
*/
public function testPropertyUrn()
{
}
/**
* Test attribute "url"
*/
public function testPropertyUrl()
{
}
/**
* Test attribute "lotto"
*/
public function testPropertyLotto()
{
}
/**
* Test attribute "locazione"
*/
public function testPropertyLocazione()
{
}
/**
* Test attribute "citta_locazione"
*/
public function testPropertyCittaLocazione()
{
}
/**
* Test attribute "nome_titolare"
*/
public function testPropertyNomeTitolare()
{
}
/**
* Test attribute "codice_titolare"
*/
public function testPropertyCodiceTitolare()
{
}
/**
* Test attribute "iban"
*/
public function testPropertyIban()
{
}
/**
* Test attribute "bic"
*/
public function testPropertyBic()
{
}
/**
* Test attribute "token"
*/
public function testPropertyToken()
{
}
/**
* Test attribute "mese_token"
*/
public function testPropertyMeseToken()
{
}
/**
* Test attribute "anno_token"
*/
public function testPropertyAnnoToken()
{
}
/**
* Test attribute "provider_incasso"
*/
public function testPropertyProviderIncasso()
{
}
/**
* Test attribute "carta_prepagata"
*/
public function testPropertyCartaPrepagata()
{
}
/**
* Test attribute "note"
*/
public function testPropertyNote()
{
}
/**
* Test attribute "id_capogruppo"
*/
public function testPropertyIdCapogruppo()
{
}
/**
* Test attribute "tipo_lead"
*/
public function testPropertyTipoLead()
{
}
/**
* Test attribute "genera_sostegno"
*/
public function testPropertyGeneraSostegno()
{
}
/**
* Test attribute "preferenza_continente"
*/
public function testPropertyPreferenzaContinente()
{
}
/**
* Test attribute "preferenza_nazione"
*/
public function testPropertyPreferenzaNazione()
{
}
/**
* Test attribute "preferenza_eta_minima"
*/
public function testPropertyPreferenzaEtaMinima()
{
}
/**
* Test attribute "preferenza_eta_massima"
*/
public function testPropertyPreferenzaEtaMassima()
{
}
/**
* Test attribute "preferenza_genere"
*/
public function testPropertyPreferenzaGenere()
{
}
/**
* Test attribute "id_campagna"
*/
public function testPropertyIdCampagna()
{
}
/**
* Test attribute "id_centro"
*/
public function testPropertyIdCentro()
{
}
/**
* Test attribute "gruppo_incassi"
*/
public function testPropertyGruppoIncassi()
{
}
/**
* Test attribute "codice_nazione"
*/
public function testPropertyCodiceNazione()
{
}
/**
* Test attribute "cin_iban"
*/
public function testPropertyCinIban()
{
}
/**
* Test attribute "cin_bban"
*/
public function testPropertyCinBban()
{
}
/**
* Test attribute "abi"
*/
public function testPropertyAbi()
{
}
/**
* Test attribute "cab"
*/
public function testPropertyCab()
{
}
/**
* Test attribute "conto"
*/
public function testPropertyConto()
{
}
/**
* Test attribute "flag_one_off"
*/
public function testPropertyFlagOneOff()
{
}
/**
* Test attribute "masked_pan"
*/
public function testPropertyMaskedPan()
{
}
/**
* Test attribute "numero_carta"
*/
public function testPropertyNumeroCarta()
{
}
/**
* Test attribute "anno_carta"
*/
public function testPropertyAnnoCarta()
{
}
/**
* Test attribute "mese_carta"
*/
public function testPropertyMeseCarta()
{
}
/**
* Test attribute "data_inizio_sospensione"
*/
public function testPropertyDataInizioSospensione()
{
}
/**
* Test attribute "data_fine_sospensione"
*/
public function testPropertyDataFineSospensione()
{
}
/**
* Test attribute "id_motivo_rinuncia"
*/
public function testPropertyIdMotivoRinuncia()
{
}
/**
* Test attribute "data_rinuncia"
*/
public function testPropertyDataRinuncia()
{
}
}
| aa7cb8900438161bb3bd54b39b1d776646e1d3e8 | [
"Markdown",
"PHP"
] | 30 | Markdown | DirectChannel/MentroApiRest | bd62ad6d5ee96b216753f97b7afdc82bea4d2f4f | b193f2ce75bca952dc2831caa730e1a3ea8ef832 |
refs/heads/master | <file_sep>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//Package checkinparse contains functions to parse checkin report into batterystats proto.
package checkinparse
import (
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/golang/protobuf/proto"
"github.com/google/battery-historian/build"
"github.com/google/battery-historian/checkinutil"
"github.com/google/battery-historian/packageutils"
"github.com/google/battery-historian/sliceparse"
bspb "github.com/google/battery-historian/pb/batterystats_proto"
sessionpb "github.com/google/battery-historian/pb/session_proto"
usagepb "github.com/google/battery-historian/pb/usagestats_proto"
)
const (
// number of fields charge and discharge step data have
numStepFields = 8
// minimum number of fields any type of battery stats have
minNumFields = 4
// Current range of supported/expected versions
minParseReportVersion = 11
maxParseReportVersion = 14
)
// Possible battery stats categories generated by on device java code.
const (
packageInfo = "i"
sinceCharged = "l" // SINCE_CHARGED: Since last charged: The only reliable value.
current = "c" // Deprecated
unplugged = "u" // Deprecated: SINCE_UNPLUGGED: Very unreliable and soon to be removed.
)
// String representations of categories the parsing code handles. Contains all
// categories defined in frameworks/base/core/java/android/os/BatteryStats.java
// unless explicitly stated.
const (
versionData = "vers"
uidData = "uid"
apkData = "apk"
processData = "pr"
sensorData = "sr"
vibratorData = "vib"
foregroundData = "fg"
stateTimeData = "st"
wakelockData = "wl"
syncData = "sy"
jobData = "jb"
kernelWakelockData = "kwl"
wakeupReasonData = "wr"
networkData = "nt"
userActivityData = "ua"
batteryData = "bt"
batteryDischargeData = "dc"
batteryLevelData = "lv"
GlobalWifiData = "gwfl"
wifiData = "wfl"
GlobalBluetoothData = "gble"
miscData = "m"
globalNetworkData = "gn"
// HISTORY_STRING_POOL (hsp) is not included in the checkin log.
// HISTORY_DATA (h) is not included in the checkin log.
screenBrightnessData = "br"
signalStrengthTimeData = "sgt"
signalScanningTimeData = "sst"
signalStrengthCountData = "sgc"
dataConnectionTimeData = "dct"
dataConnectionCountData = "dcc"
wifiStateTimeData = "wst"
wifiStateCountData = "wsc"
wifiSupplStateTimeData = "wsst"
wifiSupplStateCountData = "wssc"
wifiSignalStrengthTimeData = "wsgt"
wifiSignalStrengthCountData = "wsgc"
bluetoothStateTimeData = "bst"
bluetoothStateCountData = "bsc"
powerUseSummaryData = "pws"
powerUseItemData = "pwi"
dischargeStepData = "dsd"
chargeStepData = "csd"
dischargeTimeRemainData = "dtr"
chargeTimeRemainData = "ctr"
)
var (
powerUseItemNameMap = map[string]bspb.BatteryStats_System_PowerUseItem_Name{
"idle": bspb.BatteryStats_System_PowerUseItem_IDLE,
"cell": bspb.BatteryStats_System_PowerUseItem_CELL,
"phone": bspb.BatteryStats_System_PowerUseItem_PHONE,
"wifi": bspb.BatteryStats_System_PowerUseItem_WIFI,
"blue": bspb.BatteryStats_System_PowerUseItem_BLUETOOTH,
"scrn": bspb.BatteryStats_System_PowerUseItem_SCREEN,
"uid": bspb.BatteryStats_System_PowerUseItem_APP,
"user": bspb.BatteryStats_System_PowerUseItem_USER,
"unacc": bspb.BatteryStats_System_PowerUseItem_UNACCOUNTED,
"over": bspb.BatteryStats_System_PowerUseItem_OVERCOUNTED,
"???": bspb.BatteryStats_System_PowerUseItem_DEFAULT,
"flashlight": bspb.BatteryStats_System_PowerUseItem_FLASHLIGHT,
}
// Contains a mapping of known packages with their shared UIDs. Common shared UIDs
// were found by looking at aggregate checkin data and confirming with code search.
// Check go/android-uids for a non-exhaustive list.
packageNameToSharedUIDMap = map[string]string{
// com.google.uid.shared
"com.google.android.apps.gtalkservice": "GOOGLE_SERVICES",
"com.google.android.backuptransport": "GOOGLE_SERVICES",
"com.google.android.gms": "GOOGLE_SERVICES",
"com.google.android.gms.car.userfeedback": "GOOGLE_SERVICES",
"com.google.android.googleapps": "GOOGLE_SERVICES",
"com.google.android.gsf": "GOOGLE_SERVICES",
"com.google.android.gsf.login": "GOOGLE_SERVICES",
"com.google.android.gsf.notouch": "GOOGLE_SERVICES",
"com.google.android.providers.gmail": "GOOGLE_SERVICES",
"com.google.android.sss.authbridge": "GOOGLE_SERVICES",
"com.google.android.syncadapters.contacts": "GOOGLE_SERVICES",
"com.google.gch.gateway": "GOOGLE_SERVICES",
// com.google.android.calendar.uid.shared
"com.android.calendar": "GOOGLE_CALENDAR",
"com.google.android.calendar": "GOOGLE_CALENDAR",
"com.google.android.syncadapters.calendar": "GOOGLE_CALENDAR",
// android.uid.system
"android": "ANDROID_SYSTEM",
"com.android.changesettings": "ANDROID_SYSTEM",
"com.android.inputdevices": "ANDROID_SYSTEM",
"com.android.keychain": "ANDROID_SYSTEM",
"com.android.location.fused": "ANDROID_SYSTEM",
"com.android.providers.settings": "ANDROID_SYSTEM",
"com.android.settings": "ANDROID_SYSTEM",
"com.google.android.canvas.settings": "ANDROID_SYSTEM",
"com.lge.SprintHiddenMenu": "ANDROID_SYSTEM",
"com.nvidia.tegraprofiler.security": "ANDROID_SYSTEM",
"com.qualcomm.atfwd": "ANDROID_SYSTEM",
"com.qualcomm.display": "ANDROID_SYSTEM",
// android.uid.phone
"com.android.phone": "PHONE",
"com.android.providers.telephony": "PHONE",
"com.android.sdm.plugins.connmo": "PHONE",
"com.android.sdm.plugins.dcmo": "PHONE",
"com.android.sdm.plugins.sprintdm": "PHONE",
"com.htc.android.qxdm2sd": "PHONE",
"com.android.mms.service": "PHONE",
"com.android.server.telecom": "PHONE",
"com.android.sprint.lifetimedata": "PHONE",
"com.android.stk": "PHONE",
"com.motorola.service.ims": "PHONE",
"com.qualcomm.qti.imstestrunner": "PHONE",
"com.qualcomm.qti.rcsbootstraputil": "PHONE",
"com.qualcomm.qti.rcsimsbootstraputil": "PHONE",
"com.qualcomm.qcrilmsgtunnel": "PHONE",
"com.qualcomm.shutdownlistner": "PHONE",
"org.codeaurora.ims": "PHONE",
"com.asus.atcmd": "PHONE",
"com.mediatek.imeiwriter": "PHONE",
// android.uid.nfc
"com.android.nfc": "NFC",
"com.android.nfc3": "NFC",
"com.google.android.uiccwatchdog": "NFC",
// android.uid.shared
"com.android.contacts": "CONTACTS_PROVIDER",
"com.android.providers.applications": "CONTACTS_PROVIDER",
"com.android.providers.contacts": "CONTACTS_PROVIDER",
"com.android.providers.userdictionary": "CONTACTS_PROVIDER",
// android.media
"com.android.gallery": "MEDIA",
"com.android.providers.downloads": "MEDIA",
"com.android.providers.downloads.ui": "MEDIA",
"com.android.providers.drm": "MEDIA",
"com.android.providers.media": "MEDIA",
// android.uid.systemui
"com.android.keyguard": "SYSTEM_UI",
"com.android.systemui": "SYSTEM_UI",
// android.uid.bluetooth
"com.android.bluetooth": "BLUETOOTH",
// android.uid.shell
"com.android.shell": "SHELL",
}
// Known constant UIDs defined in frameworks/base/core/java/android/os/Process.java.
// GIDs are excluded.
knownUIDs = map[int32]string{
0: "ROOT",
1000: "ANDROID_SYSTEM",
1001: "PHONE",
1002: "BLUETOOTH",
1007: "LOG",
1010: "WIFI",
1013: "MEDIA",
1016: "VPN",
1019: "DRM",
1027: "NFC",
1037: "SHARED_RELRO",
2000: "SHELL",
}
)
type stepData struct {
timeMsec float32
level float32
displayState *bspb.BatteryStats_System_DisplayState_State
powerSaveMode *bspb.BatteryStats_System_PowerSaveMode_Mode
idleMode *bspb.BatteryStats_System_IdleMode_Mode
}
// WakelockInfo is a data structure used to sort wakelocks by time or count.
type WakelockInfo struct {
Name string
UID int32
Duration time.Duration
Count float32
}
// byTime sorts wakelock by the time held.
type byTime []*WakelockInfo
func (a byTime) Len() int { return len(a) }
func (a byTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// sort by decreasing time order then increasing alphabetic order to break the tie.
func (a byTime) Less(i, j int) bool {
if x, y := a[i].Duration, a[j].Duration; x != y {
return x > y
}
return a[i].Name < a[j].Name
}
// byCount sorts wakelock by count.
type byCount []*WakelockInfo
func (a byCount) Len() int { return len(a) }
func (a byCount) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// sort by decreasing time order then increasing alphabetic order to break the tie
func (a byCount) Less(i, j int) bool {
if x, y := a[i].Count, a[j].Count; x != y {
return x > y
}
return a[i].Name < a[j].Name
}
// SortByTime ranks a slice of wakelocks by duration.
func SortByTime(items []*WakelockInfo) {
sort.Sort(byTime(items))
}
// SortByCount ranks a slice of wakelocks by count.
func SortByCount(items []*WakelockInfo) {
sort.Sort(byCount(items))
}
// ParseBatteryStats parses the aggregated battery stats in checkin report
// according to frameworks/base/core/java/android/os/BatteryStats.java.
func ParseBatteryStats(pc checkinutil.Counter, cr *checkinutil.CheckinReport, pkgs []*usagepb.PackageInfo) (*bspb.BatteryStats, []string, []error) {
// Support a single version and single aggregation type in a checkin report.
var aggregationType bspb.BatteryStats_AggregationType
var allAppComputedPowerMah float32
var appWakelock, kernelWakelock []*WakelockInfo
p := &bspb.BatteryStats{}
p.System = &bspb.BatteryStats_System{}
uids, reportVersion, warnings, errs := parsePackageManager(pc, cr.RawPackageManager, p.GetSystem(), pkgs)
if len(errs) > 0 {
return nil, warnings, errs
}
kernelWakelockMap := make(map[string]*bspb.BatteryStats_System_KernelWakelock)
for _, r := range cr.RawBatteryStats {
var uid int32
var rawAggregationType, section string
// The first element in r is '9', which used to be the report version but is now just there as a legacy field.
remaining, err := ParseSlice(pc, "All", r[1:], &uid,
&rawAggregationType, §ion)
if err != nil {
errs = append(errs, fmt.Errorf("error parsing entire line: %v", err))
continue
}
switch rawAggregationType {
case sinceCharged:
aggregationType = bspb.BatteryStats_SINCE_CHARGED
case current:
aggregationType = bspb.BatteryStats_CURRENT
case unplugged:
aggregationType = bspb.BatteryStats_SINCE_UNPLUGGED
default:
errs = append(errs, fmt.Errorf("unsupported aggregation type %s", rawAggregationType))
return nil, warnings, errs
}
uid = packageutils.AppID(uid)
if uid == 0 {
// Some lines that are parsed will provide a uid of 0, even though 0 is not the
// correct uid for the relevant package.
// See if we can find an application to claim this.
pkg, err := packageutils.GuessPackage(strings.Join(remaining, ","), "", pkgs)
if err != nil {
errs = append(errs, err)
}
// Many applications will match with android, but we should already have the android
// UID in the map, so ignore if a package matches with android.
if pkg.GetPkgName() != "" && pkg.GetPkgName() != "android" {
uid = packageutils.AppID(pkg.GetUid())
}
}
stats, ok := uids[uid]
if !ok {
// Unexpected UID. Some packages are uploaded with a uid of 0 and so won't be found
// until we come across a case like this. Try to determine package from list.
// Passing an empty uid here because if we reach this case, then the uploaded package
// in the list has a uid of 0.
pkg, err := packageutils.GuessPackage(strings.Join(remaining, ","), "", pkgs)
if err != nil {
errs = append(errs, err)
}
if pkg.GetPkgName() != "" && pkg.GetPkgName() != "android" {
stats = &bspb.BatteryStats_App{
Name: pkg.PkgName,
Uid: proto.Int32(uid),
Child: []*bspb.BatteryStats_App_Child{
{
Name: pkg.PkgName,
VersionCode: pkg.VersionCode,
VersionName: pkg.VersionName,
},
},
}
uids[uid] = stats
} else {
if _, ok := knownUIDs[uid]; !ok {
// We've already gone through the entire package list, and it's not a UID
// that we already know about, so log a warning.
warnings = append(warnings, fmt.Sprintf("found unexpected uid for section, %s", section))
}
stats = &bspb.BatteryStats_App{Uid: proto.Int32(uid)}
uids[uid] = stats
}
}
system := p.GetSystem()
// Parse csv lines according to
// frameworks/base/core/java/android/os/BatteryStats.java.
switch section {
case apkData:
warn, paaErrs := parseAppApk(pc, remaining, stats)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, paaErrs...); e {
return nil, warnings, errs
}
case processData:
p := &bspb.BatteryStats_App_Process{}
warn, plErrs := parseLine(section, remaining, p)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, plErrs...); e {
return nil, warnings, errs
}
stats.Process = append(stats.Process, p)
case sensorData:
s := &bspb.BatteryStats_App_Sensor{}
warn, plErrs := parseLine(section, remaining, s)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, plErrs...); e {
return nil, warnings, errs
}
stats.Sensor = append(stats.Sensor, s)
case stateTimeData:
warn, passErrs := ParseAppStateTime(remaining, stats)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, passErrs...); e {
return nil, warnings, errs
}
case vibratorData:
warn, pavErrs := ParseAppVibrator(remaining, stats)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, pavErrs...); e {
return nil, warnings, errs
}
case foregroundData:
f := &bspb.BatteryStats_App_Foreground{}
warn, plErrs := parseLine(section, remaining, f)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, plErrs...); e {
return nil, warnings, errs
}
stats.Foreground = f
case jobData:
j := &bspb.BatteryStats_App_ScheduledJob{}
warn, plErrs := parseLine(section, remaining, j)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, plErrs...); e {
return nil, warnings, errs
}
stats.ScheduledJob = append(stats.ScheduledJob, j)
case userActivityData:
if uid != 0 {
if err := parseAppUserActivity(section, remaining, stats); err != nil {
errs = append(errs, err)
return nil, warnings, errs
}
}
case wakelockData:
warn, pawErrs := parseAppWakelock(uid, section, remaining, stats, &appWakelock)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, pawErrs...); e {
return nil, warnings, errs
}
case syncData:
warn, pasErrs := parseAppSync(uid, section, remaining, stats)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, pasErrs...); e {
return nil, warnings, errs
}
case networkData:
warn, panErrs := ParseAppNetwork(reportVersion, remaining, stats)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, panErrs...); e {
return nil, warnings, errs
}
case wifiData:
warn, pawErrs := ParseAppWifi(remaining, stats)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, pawErrs...); e {
return nil, warnings, errs
}
case kernelWakelockData:
warn, psklErrs := parseSystemKernelWakelock(section, remaining, kernelWakelockMap, &kernelWakelock)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, psklErrs...); e {
return nil, warnings, errs
}
case wakeupReasonData:
if err := parseSystemWakeupReason(pc, remaining, system); err != nil {
errs = append(errs, err)
return nil, warnings, errs
}
case batteryData:
b := &bspb.BatteryStats_System_Battery{}
warn, plErrs := parseLine(section, remaining, b)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, plErrs...); e {
return nil, warnings, errs
}
system.Battery = b
case batteryDischargeData:
b := &bspb.BatteryStats_System_BatteryDischarge{}
warn, plErrs := parseLine(section, remaining, b)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, plErrs...); e {
return nil, warnings, errs
}
system.BatteryDischarge = b
case batteryLevelData:
l := &bspb.BatteryStats_System_BatteryLevel{}
warn, plErrs := parseLine(section, remaining, l)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, plErrs...); e {
return nil, warnings, errs
}
system.BatteryLevel = l
case miscData:
warn, psmErrs := ParseSystemMisc(pc, reportVersion, remaining, system)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, psmErrs...); e {
return nil, warnings, errs
}
case GlobalBluetoothData:
warn, errs := ParseGlobalBluetooth(remaining, p.System)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, err); e {
return nil, warnings, errs
}
case globalNetworkData:
g := &bspb.BatteryStats_System_GlobalNetwork{}
warn, plErrs := parseLine(section, remaining, g)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, plErrs...); e {
return nil, warnings, errs
}
system.GlobalNetwork = g
case GlobalWifiData:
warn, errs := ParseGlobalWifi(remaining, p.System)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, err); e {
return nil, warnings, errs
}
case screenBrightnessData:
if err := parseSystemScreenBrightness(section, remaining, system); err != nil {
errs = append(errs, err)
return nil, warnings, errs
}
case signalScanningTimeData:
s := &bspb.BatteryStats_System_SignalScanningTime{}
warn, plErrs := parseLine(section, remaining, s)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, plErrs...); e {
return nil, warnings, errs
}
system.SignalScanningTime = s
case signalStrengthTimeData, signalStrengthCountData, dataConnectionTimeData, dataConnectionCountData, wifiStateTimeData, wifiStateCountData, bluetoothStateTimeData, bluetoothStateCountData, wifiSupplStateTimeData, wifiSupplStateCountData, wifiSignalStrengthTimeData, wifiSignalStrengthCountData:
if err := parseSystemTimeCountPair(section, remaining, system); err != nil {
errs = append(errs, err)
return nil, warnings, errs
}
case powerUseSummaryData:
p := &bspb.BatteryStats_System_PowerUseSummary{}
warn, plErrs := parseLine(section, remaining, p)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, plErrs...); e {
return nil, warnings, errs
}
system.PowerUseSummary = p
case powerUseItemData:
warn, err := ParseAppSystemPowerUseItem(pc, remaining, stats, p.System, &allAppComputedPowerMah)
if e, warnings, errs := saveWarningsAndErrors(warnings, warn, errs, err); e {
return nil, warnings, errs
}
default:
warnings = append(warnings, fmt.Sprintf("unknown data category %s", section))
}
}
processAppInfo(uids)
// Copy uids to p.App.
for _, app := range uids {
p.App = append(p.App, app)
}
// Copy to p.System.
var kernelWakelockKeys []string
for key := range kernelWakelockMap {
kernelWakelockKeys = append(kernelWakelockKeys, key)
}
sort.Strings(kernelWakelockKeys)
for _, key := range kernelWakelockKeys {
p.System.KernelWakelock = append(p.System.KernelWakelock, kernelWakelockMap[key])
}
p.System.PowerUseItem = append(p.System.PowerUseItem,
&bspb.BatteryStats_System_PowerUseItem{
Name: bspb.BatteryStats_System_PowerUseItem_APP.Enum(),
ComputedPowerMah: proto.Float32(allAppComputedPowerMah),
})
if m := p.System.GetMisc(); m != nil {
// Screen off time is calculated by subtracting screen on time from total battery real time.
diff := p.System.GetBattery().GetBatteryRealtimeMsec() - m.GetScreenOnTimeMsec()
m.ScreenOffTimeMsec = proto.Float32(diff)
if diff < 0 {
errs = append(errs, fmt.Errorf("negative screen off time"))
}
if reportVersion >= 14 {
// These won't have been populated through regular parsing for version 14+ so it's safe to overwrite here.
m.WifiOnTimeMsec = p.System.GlobalWifi.WifiOnTimeMsec
m.WifiRunningTimeMsec = p.System.GlobalWifi.WifiRunningTimeMsec
m.MobileBytesRx = p.System.GlobalNetwork.MobileBytesRx
m.MobileBytesTx = p.System.GlobalNetwork.MobileBytesTx
m.WifiBytesRx = p.System.GlobalNetwork.WifiBytesRx
m.WifiBytesTx = p.System.GlobalNetwork.WifiBytesTx
}
}
p.ReportVersion = proto.Int32(reportVersion)
p.AggregationType = aggregationType.Enum()
p.StartTimeUsec = proto.Int64(p.System.GetBattery().GetStartClockTimeMsec() * 1000)
p.EndTimeUsec = proto.Int64(cr.TimeUsec)
gmsPkg, err := packageutils.GuessPackage("com.google.android.gms", "", pkgs)
if err != nil {
errs = append(errs, err)
}
if gmsPkg != nil {
p.GmsVersion = gmsPkg.VersionCode
}
p.Build = build.Build(cr.BuildID)
if p.GetBuild().GetType() == "user" {
for _, tag := range p.GetBuild().GetTags() {
if tag == "release-keys" {
p.IsUserRelease = proto.Bool(true)
break
}
}
}
p.DeviceGroup = cr.DeviceGroup
p.CheckinRule = cr.CheckinRule
p.Radio = proto.String(cr.Radio)
p.SdkVersion = proto.Int32(cr.SDKVersion)
p.Bootloader = proto.String(cr.Bootloader)
if cr.CellOperator != "" {
p.Carrier = proto.String(cr.CellOperator + "/" + cr.CountryCode)
}
p.CountryCode = proto.String(cr.CountryCode)
p.TimeZone = proto.String(cr.TimeZone)
return p, warnings, errs
}
// CreateCheckinReport creates a checkinutil.CheckinReport from the given
// sessionpb.Checkin.
func CreateCheckinReport(cp *sessionpb.Checkin) *checkinutil.CheckinReport {
pm, bs := extractCSV(cp.GetCheckin())
return &checkinutil.CheckinReport{
TimeUsec: cp.GetBucketSnapshotMsec() * 1000,
TimeZone: cp.GetSystemInfo().GetTimeZone(),
AndroidID: cp.GetAndroidId(),
DeviceGroup: cp.Groups,
BuildID: cp.GetBuildFingerprint(),
Radio: cp.GetSystemInfo().GetBasebandRadio(),
Bootloader: cp.GetSystemInfo().GetBootloader(),
SDKVersion: cp.GetSystemInfo().GetSdkVersion(),
CellOperator: cp.GetSystemInfo().GetNetworkOperator(),
CountryCode: cp.GetSystemInfo().GetCountryCode(),
RawBatteryStats: bs,
RawPackageManager: pm,
}
}
// saveWarningsAndErrors appends new errors (ne) and new warnings (nw) to existing slices
// and returns true if new errors were added
func saveWarningsAndErrors(warnings []string, nw string, errors []error, ne ...error) (bool, []string, []error) {
newErr := false
for _, e := range ne {
if e != nil {
errors = append(errors, e)
newErr = true
}
}
if len(nw) > 0 {
warnings = append(warnings, nw)
}
return newErr, warnings, errors
}
// updateWakelock adds a wakelock with the specified name into processed if
// the name does not match any wakelock in processed and initializes wakelock
// held time to time. If such wakelock already exists, we increment its held
// time by time.
func updateWakelock(processed []*WakelockInfo, name string, uid int32, d time.Duration) []*WakelockInfo {
// processed contains a list of wakelocks we have seen.
isAdded := false
for _, w := range processed {
if w.Name == name {
w.Duration += d
isAdded = true
break
}
}
if !isAdded {
processed = append(processed, &WakelockInfo{
Name: name,
UID: uid,
Duration: d,
})
}
return processed
}
func extractCSV(input string) ([][]string, [][]string) {
// pkgbs contains package information, separated by line and comma
// bs contains since last charged stats, separated by line and comma
var pkgbs, bs [][]string
// we only use since charged data (ignore unplugged data)
for _, line := range strings.Split(input, "\n") {
line = strings.TrimSpace(line)
arr := strings.Split(line, ",")
if len(arr) < minNumFields {
continue
}
switch arr[2] {
case packageInfo:
pkgbs = append(pkgbs, arr)
case sinceCharged:
bs = append(bs, arr)
}
}
return pkgbs, bs
}
// parseStepData parses sliced lines that were orginally in the form 9,0,i,csd,65975,40,sd,p-
// Use this to parse lines for CHARGE_STEP_DATA (csd) and DISCHARGE_STEP_DATA (dsd).
func parseStepData(r []string) (*stepData, string, error) {
var err error
var warn string
var tm, l float32
var ds bspb.BatteryStats_System_DisplayState_State
var psm bspb.BatteryStats_System_PowerSaveMode_Mode
var im bspb.BatteryStats_System_IdleMode_Mode
if len(r) > 4 {
tm, err = ParseFloat32(r[4])
if err != nil {
return nil, warn, err
}
}
if len(r) > 5 {
// A ? indicates a bug/error with the display state in the log and so we should treat it as such.
// The ? was intended for index 6, but was in index 5 due to a bug in BatteryStats.java (fixed in ag/666451).
if r[5] == "?" {
return nil, warn, errors.New("discovered ? for display state")
}
l, err = ParseFloat32(r[5])
if err != nil {
return nil, warn, err
}
}
ds = bspb.BatteryStats_System_DisplayState_MIXED
if len(r) > 6 {
switch r[6] {
case "s+":
ds = bspb.BatteryStats_System_DisplayState_ON
case "s-":
ds = bspb.BatteryStats_System_DisplayState_OFF
case "sd":
ds = bspb.BatteryStats_System_DisplayState_DOZE
case "sds":
ds = bspb.BatteryStats_System_DisplayState_DOZE_SUSPEND
case "": // Empty strings are valid.
ds = bspb.BatteryStats_System_DisplayState_MIXED
case "?": // A ? indicates a bug/error in the log and so we should treat it as such.
return nil, warn, errors.New("discovered ? when parsing display state")
default:
warn = fmt.Sprintf("unknown display state: %s", r[6])
}
}
psm = bspb.BatteryStats_System_PowerSaveMode_MIXED
im = bspb.BatteryStats_System_IdleMode_NO_DATA
if len(r) > 7 {
switch r[7] {
case "p+":
psm = bspb.BatteryStats_System_PowerSaveMode_ON
case "p-":
psm = bspb.BatteryStats_System_PowerSaveMode_OFF
case "": // Empty strings are valid.
psm = bspb.BatteryStats_System_PowerSaveMode_MIXED
// i+ and i- were in the 8th slot due to a bug in BatteryStats.java (fixed in ag/666451).
case "i+":
im = bspb.BatteryStats_System_IdleMode_ON
case "i-":
im = bspb.BatteryStats_System_IdleMode_OFF
default:
warn = fmt.Sprintf("unknown power save mode: %s", r[7])
}
}
if len(r) > 8 {
switch r[8] {
case "i+":
im = bspb.BatteryStats_System_IdleMode_ON
case "i-":
im = bspb.BatteryStats_System_IdleMode_OFF
case "": // Empty strings are valid.
im = bspb.BatteryStats_System_IdleMode_MIXED
default:
warn = fmt.Sprintf("unknown idle mode: %s", r[8])
}
}
return &stepData{
timeMsec: tm,
level: l,
displayState: &ds,
powerSaveMode: &psm,
idleMode: &im,
}, warn, nil
}
// processAppInfo tries to determine the best name and version_code to assign
// to the BatteryStats_App element of each shared uid.
func processAppInfo(uids map[int32]*bspb.BatteryStats_App) []error {
var errs []error
for uid, app := range uids {
known := false
var headChild *bspb.BatteryStats_App_Child
var childNames []string
for _, child := range app.Child {
childNames = append(childNames, child.GetName())
// Check to see if it's any of the other shared UIDs.
if val, ok := packageNameToSharedUIDMap[child.GetName()]; !known && ok {
app.Name = proto.String(val)
known = true
} else if known && ok && app.GetName() != val {
errs = append(errs, fmt.Errorf("package groups not matched properly"))
}
}
app.Uid = proto.Int32(uid)
if name, ok := knownUIDs[uid]; ok {
app.Name = proto.String(name)
if headChild == nil {
continue
}
}
if len(app.Child) == 1 && headChild == nil {
headChild = app.GetChild()[0]
}
app.VersionCode = proto.Int32(headChild.GetVersionCode())
app.HeadChild = headChild
// The children aren't part of any known shared UIDs.
// Creating a name based on the concatenation of children's names, as defined in ../batterystats/parse.go
if !known {
sort.Strings(childNames) // Needed for consistent ordering
app.Name = proto.String(strings.Join(childNames, "/"))
}
}
return errs
}
// parsePackageManager parses the uid, vers, dsd, csd, ctr, and dtr
// sections of the checkin report. It builds a map from uid to address
// of a BatteryStats_App proto. The proto contains a slice of packages
// that share the same uid the rest of the proto are filled in later.
// It also fills in information about the system into the
// BatteryStats_System proto.
func parsePackageManager(pc checkinutil.Counter, bs [][]string, ps *bspb.BatteryStats_System, pkgs []*usagepb.PackageInfo) (map[int32]*bspb.BatteryStats_App, int32, []string, []error) {
// Use a map to ensure we don't double count packages.
apps := make(map[string]*usagepb.PackageInfo)
for _, p := range pkgs {
apps[p.GetPkgName()] = p
}
uids := make(map[int32]*bspb.BatteryStats_App)
var dsds []*bspb.BatteryStats_System_DischargeStep
var csds []*bspb.BatteryStats_System_ChargeStep
var reportVersion int32
var errs []error
var warns []string
savedErr := false
for _, r := range bs {
// Expect inputs like "8,0,i,uid,1000,com.android.settings".
switch r[3] {
case uidData:
var uid int32
var name string
if _, err := ParseSlice(pc, r[3], r[4:], &uid, &name); err != nil {
errs = append(errs, fmt.Errorf("error parsing PackageManager: %v", err))
continue
}
uid = packageutils.AppID(uid)
if _, known := apps[name]; !known {
apps[name] = &usagepb.PackageInfo{
PkgName: proto.String(name),
Uid: proto.Int32(uid),
}
} else if packageutils.AppID(apps[name].GetUid()) == 0 {
// It looks like a lot of packages have a uid of 0 coming from the device.
// TODO: figure out why we're getting UIDs of 0 on the device side.
apps[name].Uid = proto.Int32(uid)
}
// Expected format: 9,0,i,dsd,28124,21,s+,p-
case dischargeStepData:
data, warn, err := parseStepData(r)
if savedErr, warns, errs = saveWarningsAndErrors(warns, warn, errs, err); savedErr {
continue
}
step := &bspb.BatteryStats_System_DischargeStep{
TimeMsec: proto.Float32(data.timeMsec),
Level: proto.Float32(data.level),
DisplayState: data.displayState,
PowerSaveMode: data.powerSaveMode,
IdleMode: data.idleMode,
}
dsds = append(dsds, step)
// Expected format: 9,0,i,csd,28124,21,s+,p-
case chargeStepData:
data, warn, err := parseStepData(r)
if savedErr, warns, errs = saveWarningsAndErrors(warns, warn, errs, err); savedErr {
continue
}
step := &bspb.BatteryStats_System_ChargeStep{
TimeMsec: proto.Float32(data.timeMsec),
Level: proto.Float32(data.level),
DisplayState: data.displayState,
PowerSaveMode: data.powerSaveMode,
IdleMode: data.idleMode,
}
csds = append(csds, step)
// 9,0,i,vers,11,114,LRX21O,LRX21O
case versionData:
if len(r) < 6 {
errs = append(errs, errors.New("vers section does not contain enough fields"))
continue
}
if _, err := ParseSlice(pc, versionData, r[4:5], &reportVersion); err != nil {
errs = append(errs, fmt.Errorf("error parsing PackageManager: %v", err))
continue
}
if reportVersion < minParseReportVersion {
errs = append(errs, fmt.Errorf("old report version %d", reportVersion))
continue
} else if reportVersion > maxParseReportVersion {
warns = append(warns, fmt.Sprintf("newer report version %d found", reportVersion))
}
// Current format: 9,0,i,dtr,18147528000
case dischargeTimeRemainData:
// Case put here to acknowledge that we know about the section, but the information currently included is not useful for analysis.
if len(r) > 5 {
warns = append(warns, fmt.Sprintf("%s now has additional data", r[3]))
}
// Current format: 9,0,i,ctr,18147528000
case chargeTimeRemainData:
// Case put here to acknowledge that we know about the section, but the information currently included is not useful for analysis.
if len(r) > 5 {
warns = append(warns, fmt.Sprintf("%s now has additional data", r[3]))
}
default:
warns = append(warns, fmt.Sprintf("unknown package manager section %s", r[3]))
}
}
// We've gone through both sources of package/uid info; now we can create the App and Child elements.
for _, p := range apps {
uid := packageutils.AppID(p.GetUid())
if uid == 0 {
// Skip packages uploaded with a UID of 0 (this would be the case for old builds).
continue
}
stats := uids[uid]
if stats == nil {
stats = &bspb.BatteryStats_App{
Uid: proto.Int32(uid),
}
uids[uid] = stats
}
stats.Child = append(stats.Child,
&bspb.BatteryStats_App_Child{
Name: p.PkgName,
VersionCode: p.VersionCode,
VersionName: p.VersionName,
})
}
// New discharge step info is added to the top of the list thus we
// need to traverse in the reverse order to read from the start
for i := len(dsds) - 1; i >= 0; i-- {
ps.DischargeStep = append(ps.DischargeStep, dsds[i])
}
// similar to dsd, traverse in the reverse order
for i := len(csds) - 1; i >= 0; i-- {
ps.ChargeStep = append(ps.ChargeStep, csds[i])
}
return uids, reportVersion, warns, errs
}
// parseAppApk parses "apk"(APK_DATA) in App.
// format: 8,1000,l,apk,5719,android,android.hardware.location.GeofenceHardwareService,0,0,2
// wakeup alarms, Apk name, service name, time spent started, start count, launch count
func parseAppApk(pc checkinutil.Counter, record []string, app *bspb.BatteryStats_App) (string, []error) {
var name string
var wakeups float32
// "wakeups" and "name" are shared across services of the same app apk.
record, err := ParseSlice(pc, apkData, record, &wakeups, &name)
if err != nil {
return "", []error{err}
}
isChild := false
// pkg name should have been added when parsing package manager("uid").
for _, child := range app.GetChild() {
if child.GetName() == name {
isChild = true
break
}
}
if !isChild {
app.Child = append(app.Child, &bspb.BatteryStats_App_Child{Name: proto.String(name)})
}
if app.Apk == nil { // We need to process "wakeups" just once.
app.Apk = &bspb.BatteryStats_App_Apk{Wakeups: proto.Float32(wakeups)}
}
s := &bspb.BatteryStats_App_Apk_Service{}
warn, plErrs := parseLine(apkData, record, s)
if len(plErrs) > 0 {
return warn, plErrs
}
app.Apk.Service = append(app.Apk.Service, s)
return warn, nil
}
// parseAppUserActivity parses "au"(USER_ACTIVITY_TYPES) in App.
// format: 8,1000,l,ua,2,0,0
// "other", "button", "touch" activity counts
func parseAppUserActivity(section string, record []string, app *bspb.BatteryStats_App) error {
for name, rawCount := range record {
Count, err := ParseFloat32(rawCount)
if err != nil {
return err
}
app.UserActivity = append(app.UserActivity,
&bspb.BatteryStats_App_UserActivity{
Name: bspb.BatteryStats_App_UserActivity_Name(name).Enum(),
Count: proto.Float32(Count),
})
}
return nil
}
// ParseAppSystemPowerUseItem parses "pwi"(POWER_USE_ITEM_DATA) in App and System's PowerUseItem.
// We need to match raw item name with proto item name, so we parse manually.
// format: 8,0,u,pwi,unacc,2277
// drain type, power in mAh
// If drain type is "uid", it's per-app data, we add power in mAh into its app proto
// If drain type matches other types specified in "powerUseItemNameMap", we add
// it to system proto.
// If app has a PowerUseItem already, then newly found values from parsing will be added to it.
// The most common case of this would be when an app is installed on a device with multiple users
// (ie. with a work profile). In such cases, the app uid is combined with the user ID (to create
// UIDs such as 1010011 vs 10011) and thus the app is treated and reported separately for each profile.
// TODO: we currently combine them all under the same UID. In the future, we should separate them.
// The sum of app consumed power will be added to system proto later.
func ParseAppSystemPowerUseItem(pc checkinutil.Counter, record []string, app *bspb.BatteryStats_App, system *bspb.BatteryStats_System, allAppComputedPowerMah *float32) (string, error) {
var rawName string
var computedPowerMah float32
if _, err := ParseSlice(pc, powerUseItemData, record, &rawName, &computedPowerMah); err != nil {
return "", err
}
if rawName == "uid" {
*allAppComputedPowerMah += computedPowerMah
pb := app.GetPowerUseItem()
if pb == nil {
pb = &bspb.BatteryStats_App_PowerUseItem{}
app.PowerUseItem = pb
}
pb.ComputedPowerMah = proto.Float32(pb.GetComputedPowerMah() + computedPowerMah)
} else if name, ok := powerUseItemNameMap[rawName]; ok {
system.PowerUseItem = append(system.PowerUseItem,
&bspb.BatteryStats_System_PowerUseItem{
Name: name.Enum(),
ComputedPowerMah: proto.Float32(computedPowerMah),
})
} else {
pc.Count("unknown-app-system-power-use-item-"+rawName, 1)
return fmt.Sprintf("Unknown powerUseItem name %s", rawName), nil
}
return "", nil
}
// ParseAppStateTime parses record into app's StateTime.
//
// record holds content from BatteryStats's stateTimeSection.
// e.g., 19447364,19447364,19447364
// If app has a StateTime already, then newly found values from parsing will be added to it.
func ParseAppStateTime(record []string, app *bspb.BatteryStats_App) (string, []error) {
s := &bspb.BatteryStats_App_StateTime{}
warn, errs := parseLine(stateTimeData, record, s)
if len(errs) > 0 {
return warn, errs
}
pb := app.GetStateTime()
if pb == nil {
app.StateTime = s
return warn, nil
}
pb.ForegroundTimeMsec = proto.Float32(pb.GetForegroundTimeMsec() + s.GetForegroundTimeMsec())
pb.ActiveTimeMsec = proto.Float32(pb.GetActiveTimeMsec() + s.GetActiveTimeMsec())
pb.RunningTimeMsec = proto.Float32(pb.GetRunningTimeMsec() + s.GetRunningTimeMsec())
return warn, nil
}
// parseAppSync parses "sy"(SYNC_DATA) in App.
// format: 8,10007,l,sy,com.google.android.gms.games/com.google/...@gmail.com,2161,4
// name, total time locked, count
func parseAppSync(uid int32, section string, record []string, app *bspb.BatteryStats_App) (string, []error) {
isAdded := false
s := &bspb.BatteryStats_App_Sync{}
warn, plErrs := parseLine(section, record, s)
if len(plErrs) > 0 {
return warn, plErrs
}
// Scrub PII from the sync name
s.Name = proto.String(s.GetName())
for _, s1 := range app.Sync {
if s1.GetName() == s.GetName() {
*s.TotalTimeMsec += s1.GetTotalTimeMsec()
*s.Count += s1.GetCount()
isAdded = true
break
}
}
if !isAdded {
app.Sync = append(app.Sync, s)
}
return warn, nil
}
// ParseAppVibrator parses record into app's Vibrator.
//
// record holds content from BatteryStats's vibratorSection.
// e.g., 14,2
// If app has a Vibrator field already, then newly found values from parsing will be added to it.
func ParseAppVibrator(record []string, app *bspb.BatteryStats_App) (string, []error) {
v := &bspb.BatteryStats_App_Vibrator{}
warn, plErrs := parseLine(vibratorData, record, v)
if len(plErrs) > 0 {
return warn, plErrs
}
pb := app.GetVibrator()
if pb == nil {
app.Vibrator = v
return warn, nil
}
pb.TotalTimeMsec = proto.Float32(pb.GetTotalTimeMsec() + v.GetTotalTimeMsec())
pb.Count = proto.Float32(pb.GetCount() + v.GetCount())
return warn, nil
}
// parseAppWakelock parses "wl"(WAKELOCK_DATA) in App.
// format: 8,1000,l,wl,ConnectivityService,0,f,0,15411273,p,263,0,w,0
// name, full wakelock time, "f"(for full), full wakelock count,
// partial wakelock time, "p"(for partial), partial wakelock count
// window wakelock time, "w"(for window), window wakelock count
func parseAppWakelock(uid int32, section string, record []string, app *bspb.BatteryStats_App, appWakelock *[]*WakelockInfo) (string, []error) {
w := &bspb.BatteryStats_App_Wakelock{}
isAdded := false
// The line contains letters that represent wakelock types, we skip those fields.
warn, plErrs := parseLineWithSkip(section, record, w, []int{2 /*"f"*/, 5 /*"p"*/, 8 /*"w"*/})
if len(plErrs) > 0 {
return warn, plErrs
}
for _, w1 := range app.Wakelock {
if w1.GetName() == w.GetName() {
*w.FullTimeMsec += w.GetFullTimeMsec()
*w.FullCount += w.GetFullCount()
*w.PartialTimeMsec += w.GetPartialTimeMsec()
*w.PartialCount += w.GetPartialCount()
*w.WindowTimeMsec += w.GetWindowTimeMsec()
*w.WindowCount += w.GetWindowCount()
isAdded = true
break
}
}
if !isAdded {
app.Wakelock = append(app.Wakelock, w)
}
*appWakelock = updateWakelock(
*appWakelock,
w.GetName(),
uid,
time.Duration(w.GetFullTimeMsec()+w.GetPartialTimeMsec()+w.GetWindowTimeMsec())*time.Millisecond)
return warn, nil
}
// ParseAppNetwork parses "nt" (NETWORK_DATA) into App.
//
// record holds content from BatteryStats's networkData.
// e.g., 0,0,996,1389 (reportVersion < 8)
// e.g., 0,0,8987,7051,0,0,25,29,0,0 (reportVersion >= 8)
// If app has a Network field already, then newly found values from parsing will be added to it.
// The most common case of this would be when an app is installed on a device with multiple users
// (ie. with a work profile). In such cases, the app uid is combined with the user ID (to create
// UIDs such as 1010011 vs 10011) and thus the app is treated and reported separately for each profile.
func ParseAppNetwork(reportVersion int32, record []string, app *bspb.BatteryStats_App) (string, []error) {
n := &bspb.BatteryStats_App_Network{}
warn, errs := parseLine(networkData, record, n)
if len(errs) > 0 {
return warn, errs
}
// MobileActiveTime is output in microseconds in the log, so we convert to milliseconds here.
n.MobileActiveTimeMsec = proto.Float32(n.GetMobileActiveTimeMsec() / 1e3)
pb := app.GetNetwork()
if pb == nil {
app.Network = n
return warn, nil
}
pb.MobileBytesRx = proto.Float32(pb.GetMobileBytesRx() + n.GetMobileBytesRx())
pb.MobileBytesTx = proto.Float32(pb.GetMobileBytesTx() + n.GetMobileBytesTx())
pb.WifiBytesRx = proto.Float32(pb.GetWifiBytesRx() + n.GetWifiBytesRx())
pb.WifiBytesTx = proto.Float32(pb.GetWifiBytesTx() + n.GetWifiBytesTx())
pb.MobilePacketsRx = proto.Float32(pb.GetMobilePacketsRx() + n.GetMobilePacketsRx())
pb.MobilePacketsTx = proto.Float32(pb.GetMobilePacketsTx() + n.GetMobilePacketsTx())
pb.WifiPacketsRx = proto.Float32(pb.GetWifiPacketsRx() + n.GetWifiPacketsRx())
pb.WifiPacketsTx = proto.Float32(pb.GetWifiPacketsTx() + n.GetWifiPacketsTx())
pb.MobileActiveTimeMsec = proto.Float32(pb.GetMobileActiveTimeMsec() + n.GetMobileActiveTimeMsec())
pb.MobileActiveCount = proto.Float32(pb.GetMobileActiveCount() + n.GetMobileActiveCount())
return warn, nil
}
// ParseAppWifi parses "wfl"(WIFI_DATA) in App.
// Parse manually due to unit conversion. If app has a Wifi field already,
// then newly found values from parsing will be added to it.
// format: 14,10009,l,wfl,1386709324,304313000,0,3000,1500,500
// full wifi lock on time (usec), wifi scan time (usec), app wifi running time (usec), wifi idle time (msec), wifi Rx time (msec), wifi Tx time (msec)
func ParseAppWifi(record []string, app *bspb.BatteryStats_App) (string, []error) {
if len(record) < 3 {
return "", []error{fmt.Errorf("%s line didn't contain enough fields", wifiData)}
}
w := &bspb.BatteryStats_App_Wifi{}
warn, errs := parseLine(wifiData, record, w)
if len(errs) > 0 {
return warn, errs
}
// fullWifiLockTime, scanTime, runningTime are reported in usec, not msec, we convert them to msec here
w.FullWifiLockTimeMsec = proto.Float32(w.GetFullWifiLockTimeMsec() / 1e3)
w.ScanTimeMsec = proto.Float32(w.GetScanTimeMsec() / 1e3)
w.RunningTimeMsec = proto.Float32(w.GetRunningTimeMsec() / 1e3)
pb := app.GetWifi()
if pb == nil {
app.Wifi = w
return warn, nil
}
pb.FullWifiLockTimeMsec = proto.Float32(pb.GetFullWifiLockTimeMsec() + w.GetFullWifiLockTimeMsec())
pb.ScanTimeMsec = proto.Float32(pb.GetScanTimeMsec() + w.GetScanTimeMsec())
pb.RunningTimeMsec = proto.Float32(pb.GetRunningTimeMsec() + w.GetRunningTimeMsec())
pb.ScanCount = proto.Float32(pb.GetScanCount() + w.GetScanCount())
pb.IdleTimeMsec = proto.Float32(pb.GetIdleTimeMsec() + w.GetIdleTimeMsec())
pb.RxTimeMsec = proto.Float32(pb.GetRxTimeMsec() + w.GetRxTimeMsec())
pb.TxTimeMsec = proto.Float32(pb.GetTxTimeMsec() + w.GetTxTimeMsec())
return warn, nil
}
// parseSystemKernelWaeklock parses "kwl"(KERNEL_WAKELOCK_DATA) in system
// format: 8,0,l,kwl,ipc000000b0_sensors.qcom,0,0
// wakelock name, time, count
func parseSystemKernelWakelock(section string, record []string, kernelWakelockMap map[string]*bspb.BatteryStats_System_KernelWakelock, kernelWakelock *[]*WakelockInfo) (string, []error) {
w := &bspb.BatteryStats_System_KernelWakelock{}
warn, plErrs := parseLine(section, record, w)
if len(plErrs) > 0 {
return warn, plErrs
}
if kernelWakelock, ok := kernelWakelockMap[w.GetName()]; ok {
kernelWakelock.TimeMsec = proto.Float32(kernelWakelock.GetTimeMsec() + w.GetTimeMsec())
kernelWakelock.Count = proto.Float32(kernelWakelock.GetCount() + w.GetCount())
} else {
kernelWakelockMap[w.GetName()] = w
}
*kernelWakelock = updateWakelock(*kernelWakelock, w.GetName(), 0 /* uid */, time.Duration(w.GetTimeMsec())*time.Millisecond)
return warn, nil
}
// ParseSystemMisc parses "m"(MISC_DATA) in System.
// format:
// 9,0,l,m,12469,0,20657343842,0,0,0,11258,0,0,5000,2,3000,1 (reportVersion >= 14)
// 9,0,l,m,12469,0,228195853,228195672,0,0,0,8889296,3246978,0,20657343842,0,0,0,11258,0,0 (8 <= reportVersion < 14)
// 8,0,l,m,47452,0,19133321,19133231,0,0,0,1863222,1605056,0,918161,0 (reportVersion < 8)
//
// screen on time, phone on time, [wifi on time, wifi running time,
// bluetooth on time, mobile rx total bytes, mobile tx total bytes,
// wifi rx total bytes, wifi tx total bytes, legacy input event count(always 0)]
// mobile radio active time, mobile radio active adjusted time
// low power mode enabled time, [# connectivity changes],
// [device idle mode enabled time, device idle mode enabled count,
// device idling time, device idling count]
func ParseSystemMisc(pc checkinutil.Counter, reportVersion int32, record []string, system *bspb.BatteryStats_System) (string, []error) {
if system.GetMisc() != nil {
pc.Count("error-parse-system-misc-exist", 1)
return "", []error{errors.New("misc field already exists")}
}
m := &bspb.BatteryStats_System_Misc{}
// screen off time is not part of the line(calculated by subtracting screen
// on time from battery real time. We put a dummy value in the input slice,
// so we can still parse the other fields in the format specified by proto.
record = append(record[:1], append([]string{"0"}, record[1:]...)...)
var warn string
var errs []error
if reportVersion >= 14 {
// Legacy data was removed from the line in version 14 (ag/674773). Adding
// dummy values so we can continue using predefined functions.
record = append(record[:3], append([]string{"0", "0", "0", "0", "0", "0", "0"}, record[3:]...)...)
warn, errs = parseLine(miscData, record, m)
} else {
warn, errs = parseLineWithSkip(miscData, record, m, []int{12} /* legacy input */)
}
if len(errs) == 0 {
if reportVersion < 9 { // due to change in android client side (ag/500625)
m.FullWakelockTimeMsec = proto.Float32(m.GetFullWakelockTimeMsec() / 1e3)
m.PartialWakelockTimeMsec = proto.Float32(m.GetPartialWakelockTimeMsec() / 1e3)
m.MobileActiveTimeMsec = proto.Float32(m.GetMobileActiveTimeMsec() / 1e3)
m.MobileActiveAdjustedTimeMsec = proto.Float32(m.GetMobileActiveAdjustedTimeMsec() / 1e3)
}
system.Misc = m
}
return warn, errs
}
// ParseGlobalBluetooth parses "gble" (GLOBAL_BLUETOOTH_DATA") into system.
// format: 9,0,l,gble,15,16,17,18
// bluetooth_idle_time_msec, bluetooth_rx_time_msec, bluetooth_tx_time_msec, bluetooth_power_mah
func ParseGlobalBluetooth(record []string, system *bspb.BatteryStats_System) (string, []error) {
g := &bspb.BatteryStats_System_GlobalBluetooth{}
warn, errs := parseLine(GlobalBluetoothData, record, g)
if len(errs) == 0 {
system.GlobalBluetooth = g
}
return warn, errs
}
// ParseGlobalWifi parses "gwfl" (GLOBAL_WIFI_DATA") into system.
// format: 9,0,l,gwfl,9,10,11,12,13,14
// wifi_on_time_msec, wifi_running_time_msec, wifi_idle_time_msec, wifi_rx_time_msec, wifi_tx_time_msec, wifi_power_mah
func ParseGlobalWifi(record []string, system *bspb.BatteryStats_System) (string, []error) {
g := &bspb.BatteryStats_System_GlobalWifi{}
warn, errs := parseLine(GlobalWifiData, record, g)
if len(errs) == 0 {
system.GlobalWifi = g
}
return warn, errs
}
// parseSystemScreenBrightness parses "br"(SCREEN_BRIGHTNESS_DATA) in System.
// format: 8,0,l,br,0,0,56369,0,0
// time spent from level 0 to 4
// (0: DARK, ..., 4:BRIGHT, see proto for details)
func parseSystemScreenBrightness(section string, record []string, system *bspb.BatteryStats_System) error {
for name, rawTimeMsec := range record {
timeMsec, err := ParseFloat32(rawTimeMsec)
if err != nil {
return err
}
system.ScreenBrightness = append(system.ScreenBrightness,
&bspb.BatteryStats_System_ScreenBrightness{
Name: bspb.BatteryStats_System_ScreenBrightness_Name(name).Enum(),
TimeMsec: proto.Float32(timeMsec),
})
}
return nil
}
// parseSystemTimeCountPair parses categories that have time count pairs.
// format: time ends with "t", count ends with "c"
// each has five values corresponds to five levels
// (0: NONE OR UNKNOW, ..., 4: GREAT, see proto for details)
// 8,0,l,sgt,2307235,8838772,22120797,18900758,0
// 8,0,l,sgc,19,60,85,38,1
func parseSystemTimeCountPair(section string, record []string, system *bspb.BatteryStats_System) error {
var initLen int
if section == signalStrengthTimeData || section == signalStrengthCountData {
initLen = len(system.SignalStrength)
} else if section == dataConnectionTimeData || section == dataConnectionCountData {
initLen = len(system.DataConnection)
} else if section == wifiStateTimeData || section == wifiStateCountData {
initLen = len(system.WifiState)
} else if section == bluetoothStateTimeData || section == bluetoothStateCountData {
initLen = len(system.BluetoothState)
} else if section == wifiSupplStateTimeData || section == wifiSupplStateCountData {
initLen = len(system.WifiSupplicantState)
} else if section == wifiSignalStrengthTimeData || section == wifiSignalStrengthCountData {
initLen = len(system.WifiSignalStrength)
} else {
return fmt.Errorf("parseSystemTimeCountPair encountered unknown section: %s", section)
}
if initLen == 0 { // No proto exists. Create a new proto and fill the field.
for name, rawValue := range record {
value, err := ParseFloat32(rawValue)
if err != nil {
return err
}
switch section {
case signalStrengthTimeData:
system.SignalStrength = append(system.SignalStrength,
&bspb.BatteryStats_System_SignalStrength{
Name: bspb.BatteryStats_System_SignalStrength_Name(name).Enum(),
TimeMsec: proto.Float32(value),
})
case signalStrengthCountData:
system.SignalStrength = append(system.SignalStrength,
&bspb.BatteryStats_System_SignalStrength{
Name: bspb.BatteryStats_System_SignalStrength_Name(name).Enum(),
Count: proto.Float32(value),
})
case dataConnectionTimeData:
system.DataConnection = append(system.DataConnection,
&bspb.BatteryStats_System_DataConnection{
Name: bspb.BatteryStats_System_DataConnection_Name(name).Enum(),
TimeMsec: proto.Float32(value),
})
case dataConnectionCountData:
system.DataConnection = append(system.DataConnection,
&bspb.BatteryStats_System_DataConnection{
Name: bspb.BatteryStats_System_DataConnection_Name(name).Enum(),
Count: proto.Float32(value),
})
case wifiStateTimeData:
system.WifiState = append(system.WifiState,
&bspb.BatteryStats_System_WifiState{
Name: bspb.BatteryStats_System_WifiState_Name(name).Enum(),
TimeMsec: proto.Float32(value),
})
case wifiStateCountData:
system.WifiState = append(system.WifiState,
&bspb.BatteryStats_System_WifiState{
Name: bspb.BatteryStats_System_WifiState_Name(name).Enum(),
Count: proto.Float32(value),
})
case bluetoothStateTimeData:
system.BluetoothState = append(system.BluetoothState,
&bspb.BatteryStats_System_BluetoothState{
Name: bspb.BatteryStats_System_BluetoothState_Name(name).Enum(),
TimeMsec: proto.Float32(value),
})
case bluetoothStateCountData:
system.BluetoothState = append(system.BluetoothState,
&bspb.BatteryStats_System_BluetoothState{
Name: bspb.BatteryStats_System_BluetoothState_Name(name).Enum(),
Count: proto.Float32(value),
})
case wifiSignalStrengthTimeData:
system.WifiSignalStrength = append(system.WifiSignalStrength, &bspb.BatteryStats_System_WifiSignalStrength{
Name: bspb.BatteryStats_System_WifiSignalStrength_Name(name).Enum(),
TimeMsec: proto.Float32(value),
})
case wifiSignalStrengthCountData:
system.WifiSignalStrength = append(system.WifiSignalStrength, &bspb.BatteryStats_System_WifiSignalStrength{
Name: bspb.BatteryStats_System_WifiSignalStrength_Name(name).Enum(),
Count: proto.Float32(value),
})
case wifiSupplStateTimeData:
system.WifiSupplicantState = append(system.WifiSupplicantState, &bspb.BatteryStats_System_WifiSupplicantState{
Name: bspb.BatteryStats_System_WifiSupplicantState_Name(name).Enum(),
TimeMsec: proto.Float32(value),
})
case wifiSupplStateCountData:
system.WifiSupplicantState = append(system.WifiSupplicantState, &bspb.BatteryStats_System_WifiSupplicantState{
Name: bspb.BatteryStats_System_WifiSupplicantState_Name(name).Enum(),
Count: proto.Float32(value),
})
default:
return fmt.Errorf("parseSystemTimeCountPair encountered unknown section: %s", section)
}
}
} else if initLen == len(record) { // The proto exists. Just fill the field.
for name, rawValue := range record {
value, err := ParseFloat32(rawValue)
if err != nil {
return err
}
switch section {
case signalStrengthTimeData:
system.SignalStrength[name].TimeMsec = proto.Float32(value)
case signalStrengthCountData:
system.SignalStrength[name].Count = proto.Float32(value)
case dataConnectionTimeData:
system.DataConnection[name].TimeMsec = proto.Float32(value)
case dataConnectionCountData:
system.DataConnection[name].Count = proto.Float32(value)
case wifiStateTimeData:
system.WifiState[name].TimeMsec = proto.Float32(value)
case wifiStateCountData:
system.WifiState[name].Count = proto.Float32(value)
case bluetoothStateTimeData:
system.BluetoothState[name].TimeMsec = proto.Float32(value)
case bluetoothStateCountData:
system.BluetoothState[name].Count = proto.Float32(value)
case wifiSupplStateTimeData:
system.WifiSupplicantState[name].TimeMsec = proto.Float32(value)
case wifiSupplStateCountData:
system.WifiSupplicantState[name].Count = proto.Float32(value)
case wifiSignalStrengthTimeData:
system.WifiSignalStrength[name].TimeMsec = proto.Float32(value)
case wifiSignalStrengthCountData:
system.WifiSignalStrength[name].Count = proto.Float32(value)
default:
return fmt.Errorf("parseSystemTimeCountPair encountered unknown section: %s", section)
}
}
} else {
return fmt.Errorf("inconsistent number of fields in %s", section)
}
return nil
}
// parseSystemWakeupReason parses "wr"(WAKEUP_REASON_DATA) in System.
func parseSystemWakeupReason(pc checkinutil.Counter, record []string, system *bspb.BatteryStats_System) error {
// This time is the amount of time we saw the CPU awake from when we received
// a wake reason until we had another reason for it to be awake (someone
// acquiring a user space wake lock or another sleep/wake happening).
// 8,0,l,wr,"200:qcom,smd-rpm:222:fc4cf000.qcom,spmi",760
name := strings.Join(record[:len(record)-1], ",")
var timeMsec float32
if _, err := ParseSlice(pc, wakeupReasonData, record[len(record)-1:], &timeMsec); err != nil {
return err
}
system.WakeupReason = append(system.WakeupReason,
&bspb.BatteryStats_System_WakeupReason{
Name: proto.String(name),
TimeMsec: proto.Float32(timeMsec),
})
return nil
}
// ParseSlice wraps sliceparse.Consume(value, outputs...), increasing pc if it returns an error.
func ParseSlice(pc checkinutil.Counter, name string, value []string, outputs ...interface{}) ([]string, error) {
remaining, err := sliceparse.Consume(value, outputs...)
if err != nil {
pc.Count("error-parse-slice-"+name, 1)
}
return remaining, err
}
// ParseFloat32 parses an individual 32-bit float.
func ParseFloat32(s string) (float32, error) {
f64, err := strconv.ParseFloat(s, 32)
return float32(f64), err
}
func parseValue(src string, dstV reflect.Value) error {
var err error
srcSlice := []string{src}
switch dstV.Kind() {
case reflect.Float32:
var val float32
_, err = sliceparse.Consume(srcSlice, &val)
dstV.Set(reflect.ValueOf(val))
case reflect.Float64:
var val float64
_, err = sliceparse.Consume(srcSlice, &val)
dstV.Set(reflect.ValueOf(val))
case reflect.Int32:
var val int32
_, err = sliceparse.Consume(srcSlice, &val)
dstV.Set(reflect.ValueOf(val))
case reflect.Int64:
var val int64
_, err = sliceparse.Consume(srcSlice, &val)
dstV.Set(reflect.ValueOf(val))
case reflect.String:
dstV.Set(reflect.ValueOf(src))
default:
return fmt.Errorf("parse error: type %s not supported", dstV.Kind().String())
}
return err
}
// parseLineWithSkip skips string with specified index in record then uses parseLine
// to parse the remaining strings.
func parseLineWithSkip(section string, record []string, p proto.Message, skip []int) (string, []error) {
sort.Ints(skip)
next, nextSkip := 0, 0 // use next to traverse record, nextSkip to traverse skip.
for i, s := range record {
if nextSkip != -1 && i == skip[nextSkip] {
nextSkip++
if nextSkip == len(skip) {
// stop skipping
nextSkip = -1
}
} else {
record[next] = s
next++
}
}
// Only need to pass the elements that were not skipped.
return parseLine(section, record[:next], p)
}
// parseLine is a generic parsing function that parses a string slice into a proto.
// The proto should only have fields of type float32, float64, int32, int64 or string.
// The function determines the type a string should be parsed into by the type
// and order specified in the proto.
func parseLine(section string, record []string, p proto.Message) (string, []error) {
var warn string
var errs []error
pV := reflect.ValueOf(p)
// Because of backwards compatibility, there will be times when the proto
// will have more fields than record can provide, so just fill up as many
// fields as possible.
num := len(record)
if len(record) > pV.Elem().NumField()-1 {
num = pV.Elem().NumField() - 1
warn = fmt.Sprintf("The underlying format for %s has %d additional field(s) that are not captured.", section, len(record)-num)
}
for i := 0; i < num; i++ {
valPtrV := reflect.New(pV.Elem().Field(i).Type().Elem())
if err := parseValue(record[i], valPtrV.Elem()); err == nil {
pV.Elem().Field(i).Set(valPtrV)
} else {
errs = append(errs, fmt.Errorf("error parsing %s: %v", section, err))
}
}
return warn, errs
}
<file_sep>/**
*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('historian.Context');
/**
* Class containing the outer svg elements, axes, and scales.
* Manages zoom events, calling redraw on registered objects.
*
* @param {!Array.<number>} xExtent Min and max start_time value of the data.
* @param {number} numSeries The number of series to display as bars.
* This is to adjust the height of the svg if necessary.
* @constructor
*/
historian.Context = function(xExtent, numSeries) {
// Add a margin on either side of the graph.
var graphSize =
historian.Context.VIS_WIDTH - (2 * historian.Context.VIS_MARGIN_);
var msPerPixel = Math.round((xExtent[1] - xExtent[0]) / graphSize);
var marginSize = msPerPixel * historian.Context.VIS_MARGIN_;
/** @type {function(number): number} */
this.xScale = d3.time.scale()
.domain([xExtent[0] - marginSize, xExtent[1] + marginSize])
.range([0, historian.Context.VIS_WIDTH]);
/** @type {function(number): number} */
this.yScale = d3.scale.linear()
.domain([0, 100])
.range([historian.Context.VIS_HEIGHT, 0]);
/** @private {Object} */
this.xAxis_ = d3.svg.axis()
.scale(this.xScale);
/** @private {Object} */
this.yAxis_ = d3.svg.axis()
.scale(this.yScale)
.orient('right');
if (numSeries > 20) {
var addedHeight = ((numSeries - 20) * (historian.Context.VIS_HEIGHT / 20));
historian.Context.margins.TOP += addedHeight;
historian.Context.SVG_HEIGHT += addedHeight;
}
/**
* The outer svg element.
* @type {!Object}
*/
this.svg = d3.select('#historian-graph')
.append('svg')
.attr('width', historian.Context.SVG_WIDTH)
.attr('height', historian.Context.SVG_HEIGHT);
// The series lines are rendered later on in bars.js, however we want
// the lines to appear below everything else.
this.seriesLinesGroup = this.svg.append('g');
// Create clip path for restricting region of chart.
var clip = this.svg.append('svg:clipPath')
.attr('id', 'clip')
.append('svg:rect')
.attr('x', 0)
.attr('y', 0 - historian.Context.margins.TOP)
.attr('width', historian.Context.VIS_WIDTH)
.attr('height', historian.Context.SVG_HEIGHT);
/**
* The main chart area.
* @type {!Object}
*/
this.vis = this.svg.append('g')
.attr('transform',
'translate(' + historian.Context.margins.LEFT +
',' + historian.Context.margins.TOP + ')')
.attr('clip-path', 'url(#clip)');
// Add axes.
this.vis.append('svg:g')
.attr('class', 'x axis')
.attr('transform', 'translate(0, ' + historian.Context.VIS_HEIGHT + ')')
.call(this.xAxis_);
var yAxisXOffset =
historian.Context.margins.LEFT + historian.Context.VIS_WIDTH;
this.svg.append('svg:g')
.attr('class', 'y axis')
.attr('transform',
'translate(' + yAxisXOffset +
', ' + historian.Context.margins.TOP + ')')
.call(this.yAxis_);
/**
* For storing objects that need to be redrawn on zoom.
* @type {!Array.<Object>}
* @private
*/
this.zoomObjects_ = [];
this.zoom = d3.behavior.zoom()
.x(this.xScale)
.scaleExtent([1, 512])
.on('zoom', this.redraw_.bind(this));
this.svg.call(this.zoom);
};
/**
* Margins between svg and visualisation.
*/
historian.Context.margins = {
TOP: 120,
RIGHT: 100,
BOTTOM: 50,
LEFT: 150
};
/**
* Margin to show on either side of the graph in the zoomed out view.
* @private
*/
historian.Context.VIS_MARGIN_ = 50;
/** @private {string} */
historian.Context.WINDOW_WIDTH_ = window.getComputedStyle(
document.getElementsByTagName('body')[0], null).
getPropertyValue('width');
/** @type {number} */
historian.Context.SVG_WIDTH = parseFloat(historian.Context.WINDOW_WIDTH_) - 50;
/** @type {number} */
historian.Context.SVG_HEIGHT = 800;
/** @const {number} */
historian.Context.VIS_WIDTH =
historian.Context.SVG_WIDTH -
historian.Context.margins.LEFT -
historian.Context.margins.RIGHT;
/** @type {number} */
historian.Context.VIS_HEIGHT =
historian.Context.SVG_HEIGHT -
historian.Context.margins.TOP -
historian.Context.margins.BOTTOM;
/** @const @private {number} */
historian.Context.VERTICAL_SCROLL_ = 0;
/** @const @private {number} */
historian.Context.HORIZONTAL_SCROLL_ = 1;
/**
* Saves a reference to object that will have redraw called on zoom.
* @param {!Object} o The object to save.
*/
historian.Context.prototype.registerRedraw = function(o) {
this.zoomObjects_.push(o);
};
/**
* Extra px allowed panning before the start and after the end of the graph.
* @private {number}
*/
historian.Context.PAN_MARGIN_PX_ = 100;
/**
* Rerenders the graph for the current zoom level.
* Calls all registered objects to redraw themselves.
* @private
*/
historian.Context.prototype.redraw_ = function() {
var translateX = this.zoom.translate()[0];
var translateY = this.zoom.translate()[1];
// Don't let the user pan too far right. Any positive value means
// we're showing white space on the left.
translateX = Math.min(historian.Context.PAN_MARGIN_PX_, translateX);
// Limit panning to the left.
var zoomedWidth = this.zoom.scale() * historian.Context.VIS_WIDTH;
var limitedPan =
historian.Context.VIS_WIDTH - zoomedWidth -
historian.Context.PAN_MARGIN_PX_;
translateX = Math.max(limitedPan, translateX);
this.zoom.translate([translateX, translateY]);
var scrollType = historian.Context.VERTICAL_SCROLL_;
var sourceEvent = d3.event.sourceEvent;
if (sourceEvent.type == 'wheel') {
var x = sourceEvent.wheelDeltaX;
var y = sourceEvent.wheelDeltaY;
if (x != 0) {
if (Math.abs(x) > Math.abs(y)) {
// Assume trying to scroll horizontally.
scrollType = historian.Context.HORIZONTAL_SCROLL_;
}
}
}
if (scrollType == historian.Context.HORIZONTAL_SCROLL_) {
// Horizontal scrolling over graph doesn't do anything,
// scroll the page instead.
window.scrollBy(-sourceEvent.wheelDeltaX * 0.1, 0);
} else {
this.svg.select('.x.axis').call(this.xAxis_);
this.zoomObjects_.forEach(function(o) {
o.redraw();
});
}
};
<file_sep>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package parseutils
import (
"bytes"
"fmt"
"io/ioutil"
"reflect"
"sort"
"strings"
"testing"
"time"
"github.com/google/battery-historian/csv"
)
// TestEcnParse tests the parsing of Ecn entries in a history log.
func TestEcnParse(t *testing.T) {
inputs := []string{
// Wifi, mobile connect and multiple disconnects.
strings.Join([]string{
`9,0,i,vers,11,116,LMY06B,LMY06B`,
`9,hsp,3,1,"CONNECTED"`,
`9,hsp,28,1,"DISCONNECTED"`,
`9,hsp,30,0,"CONNECTED"`,
`9,hsp,46,0,"DISCONNECTED"`,
`9,h,0:RESET:TIME:1422620451417`,
`9,h,1000,Ecn=3`,
`9,h,2000,Ecn=28`,
`9,h,2000,Ecn=28`,
`9,h,1000,Ecn=30`,
`9,h,1000,Ecn=46`,
`9,h,1000,Ecn=3`,
`9,h,1000,Ecn=28`,
}, "\n"),
// First entry is a disconnect.
strings.Join([]string{
`9,0,i,vers,11,116,LMY06B,LMY06B`,
`9,hsp,3,1,"CONNECTED"`,
`9,hsp,28,1,"DISCONNECTED"`,
`9,h,0:RESET:TIME:1422620451417`,
`9,h,2000,Ecn=28`,
`9,h,1000,Ecn=3`,
`9,h,1000,Ecn=28`,
}, "\n"),
// Copied from a bug report.
strings.Join([]string{
`9,hsp,3,1,"CONNECTED"`,
`9,hsp,28,1,"DISCONNECTED"`,
`9,hsp,30,0,"CONNECTED"`,
`9,hsp,37,5,"CONNECTED"`,
`9,hsp,38,5,"DISCONNECTED"`,
`9,hsp,46,0,"DISCONNECTED"`,
`9,hsp,121,3,"CONNECTED"`,
`9,hsp,122,3,"DISCONNECTED"`,
`9,h,0:RESET:TIME:1422620451417`,
`9,h,1090,Ecn=3`,
`9,h,1068,Ecn=28`,
`9,h,33,Ecn=28`,
`9,h,17190,Ecn=30`,
`9,h,120,Ecn=37`,
`9,h,3693,Ecn=38`,
`9,h,396,Ecn=30`,
`9,h,964,Ecn=46`,
`9,h,9,Ecn=3`,
`9,h,2151,Ecn=28`,
`9,h,41,Ecn=28`,
`9,h,3714,Ecn=30`,
`9,h,2039,Ecn=46`,
`9,h,10,Ecn=3`,
`9,h,3214,Ecn=28`,
`9,h,106,Ecn=28`,
`9,h,3866,Ecn=30`,
`9,h,1179,Ecn=121`,
`9,h,338,Ecn=122`,
`9,h,166,Ecn=30`,
`9,h,1070,Ecn=121`,
`9,h,249,Ecn=122`,
`9,h,6,Ecn=30`,
`9,h,3329,Ecn=121`,
`9,h,2183,Ecn=122`,
`9,h,14,Ecn=30`,
`9,h,182,Ecn=46`,
`9,h,485,Ecn=3`,
`9,h,2144,Ecn=121`,
`9,h,720,Ecn=122`,
`9,h,182,Ecn=28`,
`9,h,5,Ecn=28`,
`9,h,627,Ecn=30`,
`9,h,43,Ecn=46`,
`9,h,7,Ecn=3`,
`9,h,1,+Wl`, // Extra line needed to test that summarizing of an ongoing connection (Ecn=3) works properly.
}, "\n"),
}
summaryWants := []map[string]Dist{
{
"TYPE_WIFI": {
Num: 2,
TotalDuration: 3 * time.Second,
MaxDuration: 2 * time.Second,
},
"TYPE_MOBILE": {
Num: 1,
TotalDuration: 1 * time.Second,
MaxDuration: 1 * time.Second,
},
},
{
"TYPE_WIFI": {
Num: 2,
TotalDuration: 3 * time.Second,
MaxDuration: 2 * time.Second,
},
},
{
"TYPE_WIFI": {
Num: 5,
TotalDuration: 9480 * time.Millisecond,
MaxDuration: 3214 * time.Millisecond,
},
"TYPE_MOBILE": {
Num: 4,
TotalDuration: 15971 * time.Millisecond,
MaxDuration: 8716 * time.Millisecond,
},
"TYPE_MOBILE_HIPRI": {
Num: 1,
TotalDuration: 3693 * time.Millisecond,
MaxDuration: 3693 * time.Millisecond,
},
"TYPE_MOBILE_SUPL": {
Num: 4,
TotalDuration: 3490 * time.Millisecond,
MaxDuration: 2183 * time.Millisecond,
},
},
}
csvWants := []string{
strings.Join([]string{
csv.FileHeader,
"connectivity,service,1422620452417,1422620454417,TYPE_WIFI,",
"connectivity,service,1422620457417,1422620458417,TYPE_MOBILE,",
"connectivity,service,1422620459417,1422620460417,TYPE_WIFI,",
}, "\n"),
strings.Join([]string{
csv.FileHeader,
"connectivity,service,1422620451417,1422620453417,TYPE_WIFI,",
"connectivity,service,1422620454417,1422620455417,TYPE_WIFI,",
}, "\n"),
strings.Join([]string{
csv.FileHeader,
"connectivity,service,1422620452507,1422620453575,TYPE_WIFI,",
"connectivity,service,1422620470918,1422620474611,TYPE_MOBILE_HIPRI,",
"connectivity,service,1422620470798,1422620475971,TYPE_MOBILE,",
"connectivity,service,1422620475980,1422620478131,TYPE_WIFI,",
"connectivity,service,1422620481886,1422620483925,TYPE_MOBILE,",
"connectivity,service,1422620483935,1422620487149,TYPE_WIFI,",
"connectivity,service,1422620492300,1422620492638,TYPE_MOBILE_SUPL,",
"connectivity,service,1422620493874,1422620494123,TYPE_MOBILE_SUPL,",
"connectivity,service,1422620497458,1422620499641,TYPE_MOBILE_SUPL,",
"connectivity,service,1422620491121,1422620499837,TYPE_MOBILE,",
"connectivity,service,1422620502466,1422620503186,TYPE_MOBILE_SUPL,",
"connectivity,service,1422620500322,1422620503368,TYPE_WIFI,",
"connectivity,service,1422620504000,1422620504043,TYPE_MOBILE,",
"connectivity,service,1422620504050,1422620504051,TYPE_WIFI,",
"Wifi full lock,bool,1422620504051,1422620504051,true,",
}, "\n"),
}
csvTestDescriptions := []string{
"Wifi, mobile connect and multiple disconnects",
"First entry is a disconnect",
"Large connectivity test",
}
for i, input := range inputs {
var b bytes.Buffer
result := AnalyzeHistory(input, FormatTotalTime, &b, true)
validateHistory(input, t, result, 0, 1)
s := result.Summaries[0]
if !reflect.DeepEqual(summaryWants[i], s.ConnectivitySummary) {
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].ConnectivitySummary = %v, want %v", input, s.ConnectivitySummary, summaryWants[i])
}
got := normalizeCSV(b.String())
want := normalizeCSV(csvWants[i])
if !reflect.DeepEqual(got, want) {
t.Errorf("%v: AnalyzeHistory(%v) outputted csv = %q, want: %q", csvTestDescriptions[i], input, got, want)
}
}
}
func TestAnalyzeOverTimeJump(t *testing.T) {
input := strings.Join([]string{
`9,0,i,vers,11,116,LMY06B,LMY06B`,
`9,hsp,8,10013,"com.google.android.gms.fitness/com.google/sergey@google.com"`,
`9,hsp,24,1010083,"gmail-ls/com.google/page@google.com"`,
`9,h,0:RESET:TIME:1422620451417`,
`9,h,20,+Esy=8`,
`9,h,275,-Esy=8`,
`9,h,9,+Esy=24`,
`9,h,1494:TIME:1422654277857`,
`9,h,658,-Esy=24`,
`9,h,8,+Esy=8`,
`9,h,52,-Esy=8`,
}, "\n")
want := newActivitySummary(FormatBatteryLevel)
want.StartTimeMs = 1422654276059
want.EndTimeMs = 1422654278575
want.PerAppSyncSummary[`"gmail-ls/com.google/XXX@google.com"`] = Dist{
Num: 1,
TotalDuration: 2152 * time.Millisecond,
MaxDuration: 2152 * time.Millisecond,
}
want.PerAppSyncSummary[`"com.google.android.gms.fitness/com.google/XXX@google.com"`] = Dist{
Num: 2,
TotalDuration: 327 * time.Millisecond,
MaxDuration: 275 * time.Millisecond,
}
result := AnalyzeHistory(input, FormatBatteryLevel, ioutil.Discard, true)
validateHistory(input, t, result, 0, 1)
s := result.Summaries[0]
if want.StartTimeMs != s.StartTimeMs {
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].StartTimeMs = %d, want %d", input, s.StartTimeMs, want.StartTimeMs)
}
if want.EndTimeMs != s.EndTimeMs {
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].EndTimeMs = %d, want %d", input, s.EndTimeMs, want.EndTimeMs)
}
if !reflect.DeepEqual(want.PerAppSyncSummary, s.PerAppSyncSummary) {
// TODO: write function that find the difference between maps
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].PerAppSyncSummary = %v, want %v", input, s.PerAppSyncSummary, want.PerAppSyncSummary)
}
}
func TestShutdownWithTimeJump(t *testing.T) {
input := strings.Join([]string{
"9,0,i,vers,12,116,LVX72L,LVY29G",
"9,h,0:RESET:TIME:141688070",
"9,h,0,Bl=46,Bs=d,Bh=g,Bp=u,Bt=326,Bv=3814,+r,+BP",
"9,h,292:TIME:141688362",
"9,h,36838,Bt=336",
"9,h,35075,Bt=346",
"9,h,35069,Bt=356",
"9,h,40091,Bt=366",
"9,h,40087,Bt=376",
"9,h,50105,Bt=386",
"9,h,17555,+s,+S",
"9,h,311,-S",
"9,h,207,Bp=n,Bt=390,Bv=3815,-BP",
"9,h,4:START",
"9,h,0:TIME:507421",
"9,h,6996,Bl=44,Bs=d,Bh=g,Bp=n,Bt=285,Bv=3703,+r",
"9,h,85:TIME:514503",
"9,h,1686,+s,+S",
"9,h,288,Sb=1",
"9,h,386,Sb=0,+Eur=2",
"9,h,309,+a,+Euf=2",
"9,h,236,Pst=off",
"9,h,1371,+Psc,Pst=out",
"9,h,33233,Sb=1",
"9,h,9286,Bl=43,Bv=3765",
"9,h,0:TIME:1422918458646",
"9,h,5571,Bl=58,Bs=d,Bh=g,Bp=n,Bt=227,Bv=3803,+r",
"9,h,1246,+s,+S,Sb=4",
"9,h,533,Sb=1,+Wr,+W",
"9,h,605,-W",
"9,h,2,+a,+W,Wsp=scan,+Eur=2",
"9,h,351,-a,",
"9,h,78,+a",
"9,h,42,-a,",
"9,h,47,+a",
"9,h,71,-a",
"9,h,24,+a",
"9,h,35,-a",
"9,h,73,+a",
"9,h,43,-a",
"9,h,34,+a",
"9,h,31,-a,Pst=off",
"9,h,1472,+Psc,+a,Pst=out",
"9,h,906,-a",
"9,h,43,+a",
"9,h,31,-a",
"9,h,50,+a",
"9,h,37,-Psc,-a,Pst=in",
"9,h,788:TIME:1422918470191",
"9,h,900,+Wl,+Ws,+Pr,Pcn=lte,Pss=2",
"9,h,1065,-Ws",
"9,h,1299,-Wl",
"9,h,1629,+Wl,+Ws",
"9,h,897,-Wl,-Ws",
"9,h,161,+Eur=137",
"9,h,3628,+Wl",
"9,h,4429,+Ws,+a",
"9,h,1185,-Ws",
"9,h,3593,Pss=3",
"9,h,6966,-a",
"9,h,2215,-W",
"9,h,980,+W",
"9,h,3043,+S",
"9,h,0,-S",
"9,h,1184,+Ws",
"9,h,193,Bl=57,Bv=3531,-s,-Ws",
"9,h,5530,Wsp=asced",
"9,h,771,Wsp=4-way",
"9,h,21,Wss=4,Wsp=group",
"9,h,130,+Ws,Wsp=compl",
"9,h,391,-Ws",
"9,h,9675,+Ws",
"9,h,599,-Ws",
"9,h,2024,+s",
"9,h,3067,-s,+a",
"9,h,4291,+Ws",
"9,h,589,-Ws",
"9,h,5377,-Wl",
"9,h,168,+Wl",
"9,h,734,-Wl",
"9,h,3138,+Ws,-Pr,Pcn=none",
"9,h,593,-Ws",
"9,h,1032,+S",
"9,h,1181,+Wl",
"9,h,213,-Wl",
"9,h,277,+Wl,+Ws",
"9,h,165,-Wl,-Ws",
"9,h,492,-S",
"9,h,709:SHUTDOWN",
"9,h,38:START",
"9,h,0:TIME:1422979129104",
"9,h,5902,Bl=56,Bs=d,Bh=g,Bp=a,Bt=143,Bv=3921,+r,+BP",
"9,h,1304,+s,+S,Sb=4",
"9,h,603,Sb=1,+W,+Eur=2",
"9,h,820,+Euf=2",
}, "\n")
wantTotalTime := []*ActivitySummary{
{
StartTimeMs: 141688070,
EndTimeMs: 141943700,
},
{
StartTimeMs: 1422918404202,
EndTimeMs: 1422918544725,
},
{
StartTimeMs: 1422979129104,
EndTimeMs: 1422979137733,
},
}
wantBatteryLevel := []*ActivitySummary{
{
StartTimeMs: 141688070,
EndTimeMs: 141943700,
},
{
StartTimeMs: 1422918404202,
EndTimeMs: 1422918458078,
},
{
StartTimeMs: 1422918458078,
EndTimeMs: 1422918463649,
},
{
StartTimeMs: 1422918463649,
EndTimeMs: 1422918503558,
},
{
StartTimeMs: 1422918503558,
EndTimeMs: 1422918544725,
},
{
StartTimeMs: 1422979129104,
EndTimeMs: 1422979137733,
},
}
resultTotalTime := AnalyzeHistory(input, FormatTotalTime, ioutil.Discard, true)
resultBatteryLevel := AnalyzeHistory(input, FormatBatteryLevel, ioutil.Discard, true)
if len(resultTotalTime.Errs) > 0 {
t.Errorf("AnalyzeHistory(%s,FormatTotalTime,...) errs: %v", input, resultTotalTime.Errs)
}
if len(resultBatteryLevel.Errs) > 0 {
t.Errorf("AnalyzeHistory(%s,FormatBatteryLevel,...) errs: %v", input, resultBatteryLevel.Errs)
}
summariesTotalTime := resultTotalTime.Summaries
if len(summariesTotalTime) != len(wantTotalTime) {
t.Errorf("len(AnalyzeHistory(%s,FormatTotalTime,...).Summaries) = %d, want: %d", input, len(summariesTotalTime), len(wantTotalTime))
} else {
for i := 0; i < len(wantTotalTime); i++ {
if wantTotalTime[i].StartTimeMs != summariesTotalTime[i].StartTimeMs {
t.Errorf("summariesTotalTime[%d].StartTimeMs = %d, want: %d", i, summariesTotalTime[i].StartTimeMs, wantTotalTime[i].StartTimeMs)
}
if wantTotalTime[i].EndTimeMs != summariesTotalTime[i].EndTimeMs {
t.Errorf("summariesTotalTime[%d].EndTimeMs = %d, want: %d", i, summariesTotalTime[i].EndTimeMs, wantTotalTime[i].EndTimeMs)
}
}
}
summariesBatteryLevel := resultBatteryLevel.Summaries
if len(summariesBatteryLevel) != len(wantBatteryLevel) {
t.Errorf("len(AnalyzeHistory(%s,FormatBatterylLevel,...).Summaries) = %d, want: %d", input, len(summariesBatteryLevel), len(wantBatteryLevel))
} else {
for i := 0; i < len(wantBatteryLevel); i++ {
if wantBatteryLevel[i].StartTimeMs != summariesBatteryLevel[i].StartTimeMs {
t.Errorf("summariesBatteryLevel[%d].StartTimeMs = %d, want: %d", i, summariesBatteryLevel[i].StartTimeMs, wantBatteryLevel[i].StartTimeMs)
}
if wantBatteryLevel[i].EndTimeMs != summariesBatteryLevel[i].EndTimeMs {
t.Errorf("summariesBatteryLevel[%d].EndTimeMs = %d, want: %d", i, summariesBatteryLevel[i].EndTimeMs, wantBatteryLevel[i].EndTimeMs)
}
}
}
}
func TestPerAppSyncSummary(t *testing.T) {
input := strings.Join([]string{
`9,0,i,vers,11,116,LMY06B,LMY06B`,
`9,hsp,17,1010054,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com"`,
`9,hsp,18,1010051,"com.google.android.apps.docs/com.google/noogler@google.com"`,
`9,hsp,22,1010052,"com.google.android.apps.docs.editors.kix/com.google/noogler@google.com"`,
`9,h,0:RESET:TIME:1422620451417`,
`9,h,1020,+Esy=17`,
`9,h,54,+Esy=18`,
`9,h,1059,-Esy=18`,
`9,h,7,-Esy=17`,
`9,h,171,+Esy=22`,
`9,h,14,+Esy=17`,
`9,h,968,-Esy=17`,
`9,h,7,+Esy=18`,
`9,h,87,-Esy=22`,
`9,h,11,+Esy=22`,
`9,h,560,-Esy=22`,
`9,h,1047,-Esy=18`,
`9,h,74,+Esy=17`,
`9,h,446,-Esy=17`,
`9,h,4828,+Esy=18`,
`9,h,1986:TIME:1422620530684`,
`9,h,332,-Esy=18`,
`9,h,3187,+Esy=22`,
`9,h,1062,-Esy=22`,
`9,h,30,+Esy=18`,
`9,h,15,-Esy=18`,
`9,h,107,+Esy=18`,
`9,h,1001,-Esy=18`,
`9,h,88,+Esy=22`,
`9,h,97,+Esy=18`,
`9,h,792,-Esy=22`,
`9,h,129,-Esy=18`,
`9,h,91,+Esy=17`,
`9,h,150,-Esy=17`,
`9,h,17616,+Esy=22`,
`9,h,89,+Esy=18`,
`9,h,4758,-Esy=22`,
`9,h,12,+Esy=17`,
`9,h,350,-Esy=18`,
`9,h,4637,-Esy=17`,
`9,h,9,+Esy=22`,
`9,h,7,-Esy=22`,
`9,h,24,+Esy=18`,
`9,h,28,-Esy=18`,
`9,h,10,+Esy=17`,
`9,h,10,-Esy=17`,
`9,h,20,+Esy=22`, // Test a sync that had not ended by the end of the summary.
}, "\n")
want := newActivitySummary(FormatBatteryLevel)
want.StartTimeMs = 1422620518345
want.EndTimeMs = 1422620565335
want.PerAppSyncSummary[`"com.google.android.apps.docs.editors.punch/com.google/XXX@google.com"`] = Dist{
Num: 6,
TotalDuration: 7681 * time.Millisecond,
MaxDuration: 4987 * time.Millisecond,
}
want.PerAppSyncSummary[`"com.google.android.apps.docs/com.google/<EMAIL>"`] = Dist{
Num: 8,
TotalDuration: 12167 * time.Millisecond,
MaxDuration: 5120 * time.Millisecond,
}
want.PerAppSyncSummary[`"com.google.android.apps.docs.editors.kix/com.google/XXX@google.com"`] = Dist{
Num: 7,
TotalDuration: 8441 * time.Millisecond,
MaxDuration: 4847 * time.Millisecond,
}
result := AnalyzeHistory(input, FormatBatteryLevel, ioutil.Discard, true)
validateHistory(input, t, result, 0, 1)
s := result.Summaries[0]
if want.StartTimeMs != s.StartTimeMs {
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].StartTimeMs = %d, want %d", input, s.StartTimeMs, want.StartTimeMs)
}
if want.EndTimeMs != s.EndTimeMs {
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].EndTimeMs = %d, want %d", input, s.EndTimeMs, want.EndTimeMs)
}
if !reflect.DeepEqual(want.PerAppSyncSummary, s.PerAppSyncSummary) {
// TODO: write function that find the difference between maps
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].PerAppSyncSummary = %v, want %v", input, s.PerAppSyncSummary, want.PerAppSyncSummary)
}
}
func TestFixTimeline(t *testing.T) {
input := strings.Join([]string{
"9,0,i,vers,12,116,LVX72L,LVY29G",
"9,h,0:RESET:TIME:141688070",
"9,h,0,Bl=46,Bs=d,Bh=g,Bp=u,Bt=326,Bv=3814,+r,+BP",
"9,h,292:TIME:141688362",
"9,h,36838,Bt=336",
"9,h,207,Bp=n,Bt=390,Bv=3815,-BP",
"9,h,4:START",
"9,h,0:TIME:507421",
"9,h,6996,Bl=44,Bs=d,Bh=g,Bp=n,Bt=285,Bv=3703,+r",
"9,h,85:TIME:514503",
"9,h,1686,+s,+S",
"9,h,288,Sb=1",
"9,h,386,Sb=0,+Eur=2",
"9,h,309,+a,+Euf=2",
"9,h,236,Pst=off",
"9,h,1371,+Psc,Pst=out",
"9,h,33233,Sb=1",
"9,h,9286,Bl=43,Bv=3765",
"9,h,0:TIME:1422918458646",
"9,h,5571,Bl=58,Bs=d,Bh=g,Bp=n,Bt=227,Bv=3803,+r",
"9,h,1246,+s,+S,Sb=4",
"9,h,533,Sb=1,+Wr,+W",
"9,h,605,-W",
"9,h,2,+a,+W,Wsp=scan,+Eur=2",
"9,h,351,-a,",
"9,h,906,-a",
"9,h,43,+a",
"9,h,31,-a",
"9,h,50,+a",
"9,h,37,-Psc,-a,Pst=in",
"9,h,788:TIME:1422918470191",
"9,h,900,+Wl,+Ws,+Pr,Pcn=lte,Pss=2",
"9,h,1065,-Ws",
"9,h,1299,-Wl",
"9,h,1629,+Wl,+Ws",
"9,h,897,-Wl,-Ws",
"9,h,161,+Eur=137",
"9,h,3628,+Wl",
"9,h,4429,+Ws,+a",
"9,h,1185,-Ws",
"9,h,3593,Pss=3",
"9,h,6966,-a",
"9,h,2215,-W",
"9,h,980,+W",
"9,h,3043,+S",
"9,h,0,-S",
"9,h,1184,+Ws",
"9,h,193,Bl=57,Bv=3531,-s,-Ws",
"9,h,5530,Wsp=asced",
"9,h,771,Wsp=4-way",
"9,h,21,Wss=4,Wsp=group",
"9,h,130,+Ws,Wsp=compl",
"9,h,391,-Ws",
"9,h,2024,+s",
"9,h,3067,-s,+a",
"9,h,5377,-Wl",
"9,h,3138,+Ws,-Pr,Pcn=none",
"9,h,593,-Ws",
"9,h,1032,+S",
"9,h,1181,+Wl",
"9,h,213,-Wl",
"9,h,492,-S",
"9,h,709:SHUTDOWN",
"9,h,38:START",
"9,h,0:TIME:1422979129104",
"9,h,5902,Bl=56,Bs=d,Bh=g,Bp=a,Bt=143,Bv=3921,+r,+BP",
"9,h,820,+Euf=2",
// Random lines that should be filtered out.
"9,0,i,uid,10079,com.google.android.youtube",
"9,0,l,br,326100,171,0,0,1",
}, "\n")
want := []string{
"9,0,i,vers,12,116,LVX72L,LVY29G",
"9,h,0:RESET:TIME:141688070",
"9,h,0,Bl=46,Bs=d,Bh=g,Bp=u,Bt=326,Bv=3814,+r,+BP",
"9,h,292:TIME:141688362",
"9,h,36838,Bt=336",
"9,h,207,Bp=n,Bt=390,Bv=3815,-BP",
"9,h,4:START",
"9,h,0:TIME:1422918406152",
"9,h,6996,Bl=44,Bs=d,Bh=g,Bp=n,Bt=285,Bv=3703,+r",
"9,h,85:TIME:1422918413233",
"9,h,1686,+s,+S",
"9,h,288,Sb=1",
"9,h,386,Sb=0,+Eur=2",
"9,h,309,+a,+Euf=2",
"9,h,236,Pst=off",
"9,h,1371,+Psc,Pst=out",
"9,h,33233,Sb=1",
"9,h,9286,Bl=43,Bv=3765",
"9,h,0:TIME:1422918460028",
"9,h,5571,Bl=58,Bs=d,Bh=g,Bp=n,Bt=227,Bv=3803,+r",
"9,h,1246,+s,+S,Sb=4",
"9,h,533,Sb=1,+Wr,+W",
"9,h,605,-W",
"9,h,2,+a,+W,Wsp=scan,+Eur=2",
"9,h,351,-a,",
"9,h,906,-a",
"9,h,43,+a",
"9,h,31,-a",
"9,h,50,+a",
"9,h,37,-Psc,-a,Pst=in",
"9,h,788:TIME:1422918470191",
"9,h,900,+Wl,+Ws,+Pr,Pcn=lte,Pss=2",
"9,h,1065,-Ws",
"9,h,1299,-Wl",
"9,h,1629,+Wl,+Ws",
"9,h,897,-Wl,-Ws",
"9,h,161,+Eur=137",
"9,h,3628,+Wl",
"9,h,4429,+Ws,+a",
"9,h,1185,-Ws",
"9,h,3593,Pss=3",
"9,h,6966,-a",
"9,h,2215,-W",
"9,h,980,+W",
"9,h,3043,+S",
"9,h,0,-S",
"9,h,1184,+Ws",
"9,h,193,Bl=57,Bv=3531,-s,-Ws",
"9,h,5530,Wsp=asced",
"9,h,771,Wsp=4-way",
"9,h,21,Wss=4,Wsp=group",
"9,h,130,+Ws,Wsp=compl",
"9,h,391,-Ws",
"9,h,2024,+s",
"9,h,3067,-s,+a",
"9,h,5377,-Wl",
"9,h,3138,+Ws,-Pr,Pcn=none",
"9,h,593,-Ws",
"9,h,1032,+S",
"9,h,1181,+Wl",
"9,h,213,-Wl",
"9,h,492,-S",
"9,h,709:SHUTDOWN",
"9,h,38:START",
"9,h,0:TIME:1422979129104",
"9,h,5902,Bl=56,Bs=d,Bh=g,Bp=a,Bt=143,Bv=3921,+r,+BP",
"9,h,820,+Euf=2",
}
output, c, err := fixTimeline(input)
if err != nil {
t.Error(err)
}
if !c {
t.Error("Timestamps weren't changed.")
}
if !reflect.DeepEqual(want, output) {
t.Errorf("fixTimeline(%v) = %v, want: %v", input, output, want)
}
}
// TestMergeIntervals test merging intervals functionality for sync durations
func TestMergeIntervals(t *testing.T) {
inputs := [][]interval{
// Test case 1: intervals are not overlaped
{
{0, 1},
{2, 3},
{4, 5},
{8, 10},
},
// Test case 2: intervals are included in one big interval
{
{0, 10},
{0, 2},
{4, 5},
{7, 12},
{1, 3},
},
// Test case 3: intervals are partially overlaped, second interval is overlapped with first interval's right part
{
{0, 5},
{3, 8},
},
// Test case 4: intervals are partially overlaped, second interval is overlapped with first interval's left part
{
{4, 8},
{2, 5},
},
// Test case 5: intervals are not overlaped but connected by edges
{
{1, 4},
{4, 8},
{8, 10},
},
// Test case 6: random intervals contain all above situations
{
{0, 1},
{3, 4},
{5, 10},
{6, 8},
{7, 9},
{12, 16},
{11, 15},
{16, 18},
{20, 22},
{26, 29},
{25, 27},
{30, 33},
},
}
wants := [][]interval{
{
{0, 1},
{2, 3},
{4, 5},
{8, 10},
},
{
{0, 12},
},
{
{0, 8},
},
{
{2, 8},
},
{
{1, 10},
},
{
{0, 1},
{3, 4},
{5, 10},
{11, 18},
{20, 22},
{25, 29},
{30, 33},
},
}
var output []interval
for i, input := range inputs {
output = mergeIntervals(input)
if !reflect.DeepEqual(wants[i], output) {
t.Errorf("mergeIntervals(%v) = %v, want %v", input, output, wants[i])
}
}
}
// TestTotalSyncTime test the summarizing of total sync time and num in a history log
func TestTotalSyncTime(t *testing.T) {
input := strings.Join([]string{
`9,hsp,0,10086,"gmail-ls/com.google/XXX@gmail.com"`,
`9,hsp,1,0,"0"`,
`9,hsp,2,-1,"screen"`,
`9,hsp,3,1001,"RILJ"`,
`9,hsp,4,0,"349:cwmcu"`,
`9,hsp,5,10085,"*walarm*:ALARM_ACTION(14804)"`,
`9,hsp,6,0,"118:4-0058:118:4-0058"`,
`9,hsp,7,0,"374:bcmsdh_sdmmc"`,
`9,hsp,8,1000,"*alarm*:android.intent.action.TIME_TICK"`,
`9,hsp,9,1000,"DHCP"`,
`9,hsp,10,10008,"NlpWakeLock"`,
`9,h,0:RESET:TIME:1422681992795`,
`9,h,2145,+Esy=0`,
`9,h,77,-Esy=0`,
`9,h,109,+Esy=1`,
`9,h,19,+Esy=2`,
`9,h,620,-Esy=1`,
`9,h,427,-Esy=2`,
`9,h,5909,+Esy=3`,
`9,h,79,+Esy=4`,
`9,h,2178,+Esy=5`,
`9,h,89,-Esy=4`,
`9,h,6838,+Esy=6`,
`9,h,868,-Esy=3`,
`9,h,94,-Esy=6`,
`9,h,109,-Esy=5`,
`9,h,4894,+Esy=7`,
`9,h,112,+Esy=8`,
`9,h,3000,-Esy=7`,
`9,h,2113,-Esy=8`,
`9,h,432,+Esy=9`,
`9,h,116,-Esy=9`,
`9,h,44,+Esy=10`,
`9,h,887,-Esy=10`,
}, "\n")
want := Dist{
Num: 11,
TotalDuration: 17626 * time.Millisecond,
MaxDuration: 10255 * time.Millisecond,
}
result := AnalyzeHistory(input, FormatTotalTime, ioutil.Discard, true)
validateHistory(input, t, result, 0, 1)
s := result.Summaries[0]
if !reflect.DeepEqual(want, s.TotalSyncSummary) {
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].TotalSyncSummary = %v, want %v", input, s.TotalSyncSummary, want)
}
}
// TestInProgressEvents test the summarizing of events that were in progress at the start or end of the history.
func TestInProgressEvents(t *testing.T) {
input := strings.Join([]string{
`9,hsp,0,10086,"gmail-ls/com.google/XXX@gmail.com"`,
`9,h,0:RESET:TIME:1422681992795`,
`9,h,4321,-Esy=0`, // In progress sync at the beginning
`9,h,111,-S`, // Screen was on at the beginning
`9,h,4000,+Esy=0`,
`9,h,1234,-Esy=0`,
`9,h,1000,+S`, // In progress screen on
`9,h,9876,+Esy=0`, // In progress sync at the end with zero duration
}, "\n")
syncWant := Dist{
Num: 3,
TotalDuration: 5555 * time.Millisecond,
MaxDuration: 4321 * time.Millisecond,
}
screenWant := Dist{
Num: 2,
TotalDuration: 14308 * time.Millisecond,
MaxDuration: 9876 * time.Millisecond,
}
result := AnalyzeHistory(input, FormatTotalTime, ioutil.Discard, true)
validateHistory(input, t, result, 0, 1)
s := result.Summaries[0]
if !reflect.DeepEqual(syncWant, s.TotalSyncSummary) {
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].TotalSyncSummary = %v, want %v", input, s.TotalSyncSummary, syncWant)
}
if !reflect.DeepEqual(screenWant, s.ScreenOnSummary) {
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].ScreenOnSummary = %v, want %v", input, s.ScreenOnSummary, screenWant)
}
}
// TestTwoServiceUIDNegativeEvents tests an error condition containing two negative transitions.
func TestTwoServiceUIDNegativeEvents(t *testing.T) {
input := strings.Join([]string{
`9,hsp,0,10086,"gmail-ls/com.google/XXX@gmail.com"`,
`9,hsp,1,10051,"com.google.android.apps.docs/com.google/noogler@google.com"`,
`9,h,0:RESET:TIME:1422681992795`,
`9,h,4321,+S`,
`9,h,1000,+Esy=0`,
`9,h,1234,-S`,
`9,h,1000,-Esy=0`,
`9,h,4000,-Esy=1`,
`9,h,4321,-Esy=0`, // Second negative transition for ServiceUID=0
}, "\n")
want := []error{
fmt.Errorf(`** Error in 9,h,4321,-Esy=0 in -Esy=0 : two negative transitions for "sync app":"-". `),
}
result := AnalyzeHistory(input, FormatTotalTime, ioutil.Discard, true)
validateHistory(input, t, result, 1, 1)
if !reflect.DeepEqual(want, result.Errs) {
t.Errorf("AnalyzeHistory(%s,...) = %v, want %v", input, result.Errs, want)
}
}
// TestTwoBooleanNegativeEvents tests an error condition containing two negative transitions.
func TestTwoBooleanNegativeEvents(t *testing.T) {
input := strings.Join([]string{
`9,hsp,0,10086,"gmail-ls/com.google/<EMAIL>"`,
`9,h,0:RESET:TIME:1422681992795`,
`9,h,4321,+S`,
`9,h,1000,+Esy=0`,
`9,h,1234,-S`,
`9,h,1000,-Esy=0`,
`9,h,4000,-S`, // Second boolean negative transition
}, "\n")
want := []error{
fmt.Errorf(`** Error in 9,h,4000,-S in -S : two negative transitions for "screen":"-". `),
}
result := AnalyzeHistory(input, FormatTotalTime, ioutil.Discard, true)
validateHistory(input, t, result, 1, 1)
if !reflect.DeepEqual(want, result.Errs) {
t.Errorf("AnalyzeHistory(%s,...) = %v, want %v", input, result.Errs, want)
}
}
// TestScrubPII tests enabling and disabling ScrubPII in AnalyzeHistory.
func TestScrubPII(t *testing.T) {
input := strings.Join([]string{
`9,hsp,0,10086,"gmail-ls/com.google/testname@gmail.com"`,
`9,h,0:RESET:TIME:1422681992795`,
`9,h,4000,+Esy=0`,
`9,h,1000,-Esy=0`,
`9,h,0:RESET:TIME:1422681997795`,
}, "\n")
want := map[bool]string{
true: `"gmail-ls/com.google/XXX@<EMAIL>"`,
false: `"gmail-ls/com.google/testname@gmail.com"`,
}
for doScrub, expectedAddress := range want {
result := AnalyzeHistory(input, FormatTotalTime, ioutil.Discard, doScrub)
validateHistory(input, t, result, 0, 1)
s := result.Summaries[0]
wantSummary := make(map[string]Dist)
wantSummary[expectedAddress] = Dist{
Num: 1,
TotalDuration: 1 * time.Second,
MaxDuration: 1 * time.Second,
}
if !reflect.DeepEqual(wantSummary, s.PerAppSyncSummary) {
t.Errorf("AnalyzeHistory(%s,..., %v).Summaries[0].PerAppSyncSummary = %v, want %v", input, doScrub, s.PerAppSyncSummary, wantSummary)
t.Errorf("Invalid per app sync summary. Got %v, want %v", s.PerAppSyncSummary, wantSummary)
}
}
}
// validateHistory checks there were no errors in the given analysis report,
// and the correct number of summaries.
func validateHistory(input string, t *testing.T, r *AnalysisReport, numErrorsExpected, numSummariesExpected int) {
if len(r.Errs) != numErrorsExpected {
t.Errorf("AnalyzeHistory(%v,...) has errs = %v", input, r.Errs)
}
if len(r.Summaries) != numSummariesExpected {
t.Errorf("len(AnalyzeHistory(%v...).Summaries) = %d, want: %d", input, len(r.Summaries), numSummariesExpected)
}
}
// TestWakeLockParse tests the parsing of wake_lock entries in a history log.
// No wakelock_in entries.
func TestWakeLockParse(t *testing.T) {
input := strings.Join([]string{
`9,0,i,vers,11,116,LMY06B,LMY06B`,
`9,hsp,17,1010054,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com"`,
`9,h,0:RESET:TIME:1422620451417`,
`9,h,1000,+w=17`,
`9,h,10000,-w`,
}, "\n")
want := newActivitySummary(FormatTotalTime)
want.StartTimeMs = 1422620451417
want.EndTimeMs = 1422620462417
want.WakeLockSummary[`"com.google.android.apps.docs.editors.punch/com.google/XXX@google.com"`] = Dist{
Num: 1,
TotalDuration: 10000 * time.Millisecond,
MaxDuration: 10000 * time.Millisecond,
}
result := AnalyzeHistory(input, FormatTotalTime, ioutil.Discard, true)
if len(result.Errs) > 0 {
t.Errorf("Errors encountered while analyzing history: %v", result.Errs)
}
if len(result.Summaries) != 1 {
t.Fatalf("Unwant number of summaries. Got %d, want: %d", len(result.Summaries), 1)
}
s := result.Summaries[0]
if want.StartTimeMs != s.StartTimeMs {
t.Errorf("Start times do not match. Got: %d, want: %d", want.StartTimeMs, s.StartTimeMs)
}
if want.EndTimeMs != s.EndTimeMs {
t.Errorf("End times do not match. Got: %d, want: %d", want.EndTimeMs, s.EndTimeMs)
}
if !reflect.DeepEqual(want.WakeLockSummary, s.WakeLockSummary) {
t.Errorf("Invalid wake lock summary. Got: %v, want: %v", s.WakeLockSummary, want.WakeLockSummary)
}
}
// TestWakeLockInParse tests the parsing of wakelock_in entries in a history log.
// Check that wake lock is ignored if wakelock_in is present.
func TestWakeLockInParse(t *testing.T) {
input := strings.Join([]string{
`9,0,i,vers,11,116,LMY06B,LMY06B`,
`9,hsp,17,1010054,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com"`,
`9,hsp,22,1010052,"com.google.android.apps.docs.editors.kix/com.google/noogler@google.com"`,
`9,h,0:RESET:TIME:1422620451417`,
`9,h,1000,+w=17,+Ewl=17`,
`9,h,2000,+Ewl=22`,
`9,h,3000,-Ewl=17`,
`9,h,5000,-w,-Ewl=22`,
}, "\n")
want := newActivitySummary(FormatTotalTime)
want.StartTimeMs = 1422620451417
want.EndTimeMs = 1422620462417
want.WakeLockSummary[`"com.google.android.apps.docs.editors.punch/com.google/XXX@google.com"`] = Dist{
Num: 1,
TotalDuration: 5000 * time.Millisecond,
MaxDuration: 5000 * time.Millisecond,
}
want.WakeLockSummary[`"com.google.android.apps.docs.editors.kix/com.google/XXX@google.com"`] = Dist{
Num: 1,
TotalDuration: 8000 * time.Millisecond,
MaxDuration: 8000 * time.Millisecond,
}
result := AnalyzeHistory(input, FormatTotalTime, ioutil.Discard, true)
if len(result.Errs) > 0 {
t.Errorf("Errors encountered while analyzing history: %v", result.Errs)
}
if len(result.Summaries) != 1 {
t.Fatalf("Unwant number of summaries. Got %d, want: %d", len(result.Summaries), 1)
}
s := result.Summaries[0]
if want.StartTimeMs != s.StartTimeMs {
t.Errorf("Start times do not match. Got: %d, want: %d", want.StartTimeMs, s.StartTimeMs)
}
if want.EndTimeMs != s.EndTimeMs {
t.Errorf("End times do not match. Got: %d, want: %d", want.EndTimeMs, s.EndTimeMs)
}
if !reflect.DeepEqual(want.WakeLockSummary, s.WakeLockSummary) {
t.Errorf("Invalid wake lock summary. Got: %v, want: %v", s.WakeLockSummary, want.WakeLockSummary)
}
}
// TestUIDToPackageNameMapping tests that mapping of UIDs to package names from the checkin log works properly.
func TestUIDToPackageNameMapping(t *testing.T) {
input := strings.Join([]string{
// Random lines that should be skipped.
"9,0,l,pr,system,0,3150,0,0,0,0",
"9,1000,l,wl,SyncManagerHandleSyncAlarm,0,f,0,1568,p,80,0,w,0",
"9,0,l,sst,0",
// Actual sync lines to be parsed.
"9,10005,l,apk,1,com.android.providers.calendar,com.android.providers.calendar.CalendarProviderIntentService,160,1,1",
// Shared UID
"9,1001,l,apk,9,com.android.phone,com.android.phone.TelephonyDebugService,8630050,1,1",
"9,1001,l,apk,0,com.android.stk,com.android.stk.StkAppService,8630050,1,1",
// Removing legacy '9' to ensure parsing still works.
"10014,l,apk,225,com.google.android.gms,com.google.android.gms.auth.GetToken,0,0,137",
}, "\n")
want := map[int32]string{
10005: "com.android.providers.calendar",
1001: "com.android.phone;com.android.stk",
10014: "com.google.android.gms",
}
got, errs := UIDToPackageNameMapping(input)
if len(errs) > 0 {
t.Fatalf("Encountered errors: %v", errs)
}
if !reflect.DeepEqual(want, got) {
t.Errorf("UID--package mapping incorrect.\n Got: %v,\n want: %v", got, want)
}
}
// TestIdleModeOnAndEjbParse tests the parsing of idle_mode and job entries in a history log.
func TestIdleModeOnAndEjbParse(t *testing.T) {
input := strings.Join([]string{
`9,0,i,vers,11,116,LMY06B,LMY06B`,
`9,hsp,17,1010054,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com"`,
`9,hsp,19,10008,"com.android.providers.downloads/.DownloadIdleService"`,
`9,hsp,20,1010054,"*net_scheduler*\"`,
`9,hsp,21,1010054,"*job*/com.google.android.gms/.gcm.nts.TaskExecutionService"`,
`9,h,0:RESET:TIME:1422620451417`,
`9,h,1000,+w=17`,
`9,h,1000,-Ejb=21`, // no +Ejb = 21
`9,h,10000,-w`,
`9,h,6493,+di,+Ejb=19`,
`9,h,1388,-w`,
`9,h,3,+w=20`,
`9,h,13,-w`,
`9,h,3,+w=20`,
`9,h,114,-w`,
`9,h,5575,-di,-Ejb=19`,
`9,h,28,+w=21,+Ejb=19`,
`9,h,3,-w`,
`9,h,3,+w=21,-Ejb=19`,
`9,h,1,-w`,
`9,h,4,+w=20`,
`9,h,5672,-w,+di,+Ejb=21`, // no -di, no -Ejb=21
`9,h,7,+w=17`,
`9,h,2,-r,-w`,
}, "\n")
want := newActivitySummary(FormatTotalTime)
want.IdleModeOnSummary = Dist{
Num: 2,
TotalDuration: 7105 * time.Millisecond,
MaxDuration: 7096 * time.Millisecond,
}
want.ScheduledJobSummary[`"com.android.providers.downloads/.DownloadIdleService"`] = Dist{
Num: 2,
TotalDuration: 7102 * time.Millisecond,
MaxDuration: 7096 * time.Millisecond,
}
want.ScheduledJobSummary[`"*job*/com.google.android.gms/.gcm.nts.TaskExecutionService"`] = Dist{
Num: 2,
TotalDuration: 2009 * time.Millisecond,
MaxDuration: 2000 * time.Millisecond,
}
result := AnalyzeHistory(input, FormatTotalTime, ioutil.Discard, true)
validateHistory(input, t, result, 0, 1)
s := result.Summaries[0]
if !reflect.DeepEqual(want.IdleModeOnSummary, s.IdleModeOnSummary) {
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].IdleModeOnSummary = %v, want %v", input, s.IdleModeOnSummary, want.IdleModeOnSummary)
}
if !reflect.DeepEqual(want.ScheduledJobSummary, s.ScheduledJobSummary) {
t.Errorf("AnalyzeHistory(%s,...).Summaries[0].ScheduledJobSummary = %v, want %v", input, s.ScheduledJobSummary, want.ScheduledJobSummary)
}
}
// Tests the generating of CSV entries for a tsBool type.
func TestCSVBoolEntry(t *testing.T) {
inputs := []string{
// Several positive and negative transitions.
strings.Join([]string{
"9,0,i,vers,11,116,LMY06B,LMY06B",
"9,h,0:RESET:TIME:1422620451417",
"9,h,1000,+Psc",
"9,h,1500,-Psc",
"9,h,2500,+Psc",
"9,h,2000,-Psc",
}, "\n"),
// First entry is a negative transition.
strings.Join([]string{
"9,0,i,vers,11,116,LMY06B,LMY06B",
"9,h,0:RESET:TIME:1422620451417",
"9,h,1000,-Psc",
"9,h,1000,+Psc",
"9,h,1500,-Psc",
}, "\n"),
// Positive transition before shutdown.
strings.Join([]string{
"9,0,i,vers,11,116,LMY06B,LMY06B",
"9,h,0:RESET:TIME:1422620451417",
"9,h,1000,+Psc",
"9,h,500:SHUTDOWN",
"9,h,4:START",
"9,h,0:TIME:1430000000000",
"9,h,1000,+Psc",
"9,h,2000,-Psc",
}, "\n"),
// Negative transition before shutdown.
strings.Join([]string{
"9,0,i,vers,11,116,LMY06B,LMY06B",
"9,h,0:RESET:TIME:1422620451417",
"9,h,1000,-Psc",
"9,h,500:SHUTDOWN",
"9,h,4:START",
"9,h,0:TIME:1430000000000",
}, "\n"),
}
csvWants := []string{
strings.Join([]string{
csv.FileHeader,
"phone scanning,bool,1422620452417,1422620453917,true,",
"phone scanning,bool,1422620456417,1422620458417,true,",
}, "\n"),
strings.Join([]string{
csv.FileHeader,
"phone scanning,bool,1422620451417,1422620452417,true,",
"phone scanning,bool,1422620453417,1422620454917,true,",
}, "\n"),
strings.Join([]string{
csv.FileHeader,
"phone scanning,bool,1422620452417,1422620452917,true,",
"reboot,bool,1422620452917,1430000000000,true,",
"phone scanning,bool,1430000001000,1430000003000,true,",
}, "\n"),
strings.Join([]string{
csv.FileHeader,
"phone scanning,bool,1422620451417,1422620452417,true,",
"reboot,bool,1422620452917,1430000000000,true,",
}, "\n"),
}
numSummariesWants := []int{
1,
1,
2,
1,
}
csvTestDescriptions := []string{
"Several positive and negative transitions",
"First entry is a negative transition",
"Positive transition before shutdown",
"Negative transition before shutdown",
}
for i, input := range inputs {
var b bytes.Buffer
result := AnalyzeHistory(input, FormatTotalTime, &b, true)
validateHistory(input, t, result, 0, numSummariesWants[i])
got := normalizeCSV(b.String())
want := normalizeCSV(csvWants[i])
if !reflect.DeepEqual(got, want) {
t.Errorf("%v: AnalyzeHistory(%v) outputted csv = %q, want: %q", csvTestDescriptions[i], input, got, want)
}
}
}
// Tests the generating of CSV entries for a tsInt type.
func TestCSVIntEntry(t *testing.T) {
inputs := []string{
// Several brightness changes.
strings.Join([]string{
"9,0,i,vers,11,116,LMY06B,LMY06B",
"9,h,0:RESET:TIME:1422620451417",
"9,h,1000,Sb=0",
"9,h,1500,Sb=1",
"9,h,2500,Sb=4",
"9,h,2000,Sb=0",
}, "\n"),
// With a time reset.
strings.Join([]string{
"9,0,i,vers,11,116,LMY06B,LMY06B",
"9,h,0:RESET:TIME:1422620451417",
"9,h,1000,Sb=0",
"9,h,1500,Sb=1",
"9,h,500:SHUTDOWN",
"9,h,4:START",
"9,h,0:TIME:1430000000000",
"9,h,1000,Sb=4",
"9,h,2000,Sb=0",
}, "\n"),
}
csvWants := []string{
strings.Join([]string{
csv.FileHeader,
"brightness,int,1422620452417,1422620453917,0,",
"brightness,int,1422620453917,1422620456417,1,",
"brightness,int,1422620456417,1422620458417,4,",
"brightness,int,1422620458417,1422620458417,0,",
}, "\n"),
strings.Join([]string{
csv.FileHeader,
"brightness,int,1422620452417,1422620453917,0,",
"brightness,int,1422620453917,1422620454417,1,",
"reboot,bool,1422620454417,1430000000000,true,",
"brightness,int,1430000001000,1430000003000,4,",
"brightness,int,1430000003000,1430000003000,0,",
}, "\n"),
}
numSummariesWants := []int{
1,
2,
}
csvTestDescriptions := []string{
"Brightness changes",
"Shutdown event between brightness changes",
}
for i, input := range inputs {
var b bytes.Buffer
result := AnalyzeHistory(input, FormatTotalTime, &b, true)
validateHistory(input, t, result, 0, numSummariesWants[i])
got := normalizeCSV(b.String())
want := normalizeCSV(csvWants[i])
if !reflect.DeepEqual(got, want) {
t.Errorf("%v: AnalyzeHistory(%v) outputted csv = %q, want: %q", csvTestDescriptions[i], input, got, want)
}
}
}
// Tests the generating of CSV entries for a tsString type.
func TestCSVStringEntry(t *testing.T) {
inputs := []string{
// Several different values.
strings.Join([]string{
"9,0,i,vers,11,116,LMY06B,LMY06B",
"9,h,0:RESET:TIME:1422620451417",
"9,h,1000,Pcn=hspa",
"9,h,1500,Pcn=lte",
"9,h,2500,Pcn=hspap",
"9,h,2000,Pcn=lte",
}, "\n"),
// With a time reset.
strings.Join([]string{
"9,0,i,vers,11,116,LMY06B,LMY06B",
"9,h,0:RESET:TIME:1422620451417",
"9,h,1000,Pcn=hspa",
"9,h,1500,Pcn=lte",
"9,h,500:SHUTDOWN",
"9,h,4:START",
"9,h,0:TIME:1430000000000",
"9,h,1000,Pcn=lte",
"9,h,2000,Pcn=hspap",
}, "\n"),
}
csvWants := []string{
strings.Join([]string{
csv.FileHeader,
"data conn,string,1422620452417,1422620453917,hspa,",
"data conn,string,1422620453917,1422620456417,lte,",
"data conn,string,1422620456417,1422620458417,hspap,",
"data conn,string,1422620458417,1422620458417,lte,",
}, "\n"),
strings.Join([]string{
csv.FileHeader,
"data conn,string,1422620452417,1422620453917,hspa,",
"data conn,string,1422620453917,1422620454417,lte,",
"reboot,bool,1422620454417,1430000000000,true,",
"data conn,string,1430000001000,1430000003000,lte,",
"data conn,string,1430000003000,1430000003000,hspap,",
}, "\n"),
}
numSummariesWants := []int{
1,
2,
}
csvTestDescriptions := []string{
"Data connection changes",
"Shutdown event between data connection changes",
}
for i, input := range inputs {
var b bytes.Buffer
result := AnalyzeHistory(input, FormatTotalTime, &b, true)
validateHistory(input, t, result, 0, numSummariesWants[i])
got := normalizeCSV(b.String())
want := normalizeCSV(csvWants[i])
if !reflect.DeepEqual(got, want) {
t.Errorf("%v: AnalyzeHistory(%v) outputted csv = %q, want: %q", csvTestDescriptions[i], input, got, want)
}
}
}
// Tests the generating of CSV entries for a ServiceUID type.
func TestCSVServiceEntry(t *testing.T) {
inputs := []string{
// Overlapping entries.
strings.Join([]string{
`9,h,0:RESET:TIME:1422620451417`,
`9,hsp,17,1010054,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com"`,
`9,hsp,18,1010051,"com.google.android.apps.docs/com.google/noogler@<EMAIL>"`,
`9,hsp,22,1010052,"com.google.android.apps.docs.editors.kix/com.google/noogler@google.com"`,
`9,h,1000,+Ewl=17`,
`9,h,2000,+Ewl=22`,
`9,h,3000,-Ewl=17`,
`9,h,2000,+Ewl=18`,
`9,h,5000,-Ewl=22`,
}, "\n"),
// Nested entries.
strings.Join([]string{
`9,h,0:RESET:TIME:1422620451417`,
`9,hsp,17,1010054,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com"`,
`9,hsp,18,1010051,"com.google.android.apps.docs/com.google/noogler@google.com"`,
`9,hsp,22,1010052,"com.google.android.apps.docs.editors.kix/com.google/noogler@google.com"`,
`9,h,1000,+Ewl=17`,
`9,h,2000,+Ewl=22`,
`9,h,2000,+Ewl=18`,
`9,h,2000,-Ewl=18`,
`9,h,5000,-Ewl=22`,
`9,h,3000,-Ewl=17`,
}, "\n"),
// First entry is a negative transition.
strings.Join([]string{
`9,h,0:RESET:TIME:1422620451417`,
`9,hsp,17,1010054,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com"`,
`9,h,2000,-Ewl=17`,
}, "\n"),
// Open entry before shutdown.
strings.Join([]string{
`9,h,0:RESET:TIME:1422620451417`,
`9,hsp,17,1010054,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com"`,
`9,hsp,18,1010051,"com.google.android.apps.docs/com.google/noogler@google.com"`,
`9,h,1000,+Ewl=17`,
`9,h,2000,+Ewl=18`,
`9,h,2000,-Ewl=18`,
`9,h,500:SHUTDOWN`,
`9,h,4:START`,
`9,h,0:TIME:1430000000000`,
}, "\n"),
}
csvWants := []string{
strings.Join([]string{
csv.FileHeader,
`wakelock_in,service,1422620452417,1422620457417,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com",1010054`,
`wakelock_in,service,1422620454417,1422620464417,"com.google.android.apps.docs.editors.kix/com.google/noogler@google.com",1010052`,
`wakelock_in,service,1422620459417,1422620464417,"com.google.android.apps.docs/com.google/noogler@google.com",1010051`,
}, "\n"),
strings.Join([]string{
csv.FileHeader,
`wakelock_in,service,1422620456417,1422620458417,"com.google.android.apps.docs/com.google/noogler@google.com",1010051`,
`wakelock_in,service,1422620454417,1422620463417,"com.google.android.apps.docs.editors.kix/com.google/noogler@google.com",1010052`,
`wakelock_in,service,1422620452417,1422620466417,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com",1010054`,
}, "\n"),
strings.Join([]string{
csv.FileHeader,
`wakelock_in,service,1422620451417,1422620453417,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com",1010054`,
}, "\n"),
strings.Join([]string{
csv.FileHeader,
`wakelock_in,service,1422620454417,1422620456417,"com.google.android.apps.docs/com.google/noogler@google.com",1010051`,
`wakelock_in,service,1422620452417,1422620456917,"com.google.android.apps.docs.editors.punch/com.google/noogler@google.com",1010054`,
`reboot,bool,1422620456917,1430000000000,true,`,
}, "\n"),
}
numSummariesWants := []int{
1,
1,
1,
1,
}
csvTestDescriptions := []string{
"Overlapping wakelock entries",
"Nesting wakelock entries",
"First wakelock entry is a negative transition",
"Last Wakelock entry has no corresponding negative transition before shutdown",
}
for i, input := range inputs {
var b bytes.Buffer
result := AnalyzeHistory(input, FormatTotalTime, &b, false)
validateHistory(input, t, result, 0, numSummariesWants[i])
got := normalizeCSV(b.String())
want := normalizeCSV(csvWants[i])
if !reflect.DeepEqual(got, want) {
t.Errorf("%v: AnalyzeHistory(%v) outputted csv = %q, want: %q", csvTestDescriptions[i], input, got, want)
}
}
}
// Removes trailing spaces and sorts the csv lines.
func normalizeCSV(text string) []string {
lines := strings.Split(strings.TrimSpace(text), "\n")
// Order of events generated might not be the same - if several transitions are open
// at a SHUTDOWN event, then we iterate through the open events and create csv entries.
// As iteration order of go maps is not defined, this may result a different order generated.
sort.Strings(lines)
return lines
}
<file_sep>/**
*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('historian.util');
goog.require('goog.string');
/**
* @fileoverview Functions to read in the csv data as series,
* and aggregate data.
*/
/**
* Static method to aggregates entries with overlapping times.
* returning entries with arrays of services.
* @param {!historian.SerieData} series The series to aggregate.
* @return {!historian.SerieData} The aggregated series.
* @private
*/
historian.util.aggregateData_ = function(series) {
var aggregatedEntries = [];
// Process the first entry.
var first = series.values[0];
aggregatedEntries.push({
'start_time': first.start_time,
'end_time': first.end_time,
'value': 1,
'services': [first.value]
});
for (var i = 1; i < series.values.length; i++) {
var current = series.values[i];
var numAggregated = aggregatedEntries.length;
// If the current entry begins after all the aggregated entries,
// don't need to aggregate anything, just create a new entry.
if (current.start_time >= aggregatedEntries[numAggregated - 1].end_time) {
aggregatedEntries.push({
'start_time': current.start_time,
'end_time': current.end_time,
'value': 1,
'services': [current.value]
});
continue;
}
var done = false;
for (var j = 0; j < aggregatedEntries.length; j++) {
var entry = aggregatedEntries[j];
// Skip over all aggregated entries that don't overlap with
// the current entry.
if (entry.end_time < current.start_time ||
entry.start_time > current.end_time) {
continue;
}
if (current.start_time === entry.start_time) {
if (current.end_time < entry.end_time) {
// The entry is contained within an existing aggregated entry.
// Split the aggregated entry into two parts.
var newEntry = {
'start_time': current.end_time,
'end_time': entry.end_time,
'value': entry.services.length,
'services': entry.services.slice()
};
// Add the current entry to the aggregated entry.
entry.end_time = current.end_time;
entry.value = entry.value + 1;
entry.services.push(current.value);
aggregatedEntries.splice(j + 1, 0, newEntry);
done = true;
break;
} else if (current.end_time === entry.end_time) {
// The entries have equal times. Add to existing services array.
entry.value = entry.value + 1;
entry.services.push(current.value);
done = true;
break;
} else {
// The current entry ends after the existing aggregated entry.
// Add to existing services array, and set a new start
// point for the current entry for processing in the next
// iteration.
entry.value = entry.value + 1;
entry.services.push(current.value);
current.start_time = entry.end_time;
}
} else if (current.start_time > entry.start_time) {
// Split the existing aggregated entry into 2 parts,
// the time occuring before the current entry start time,
// and the time after.
var newEntry = {
'start_time': current.start_time,
'end_time': entry.end_time,
'value': entry.services.length,
'services': entry.services.slice()
};
entry.end_time = current.start_time;
aggregatedEntries.splice(j + 1, 0, newEntry);
}
}
if (!done) {
aggregatedEntries.push({
'start_time': current.start_time,
'end_time': current.end_time,
'value': 1,
'services': [current.value]
});
}
}
return {
'name': series.name,
'type': series.type,
'values': aggregatedEntries,
'index': series.index
};
};
/**
* Comparator function for sorting entries. Sorts by start_time, then end_time.
* @param {(!historian.Entry | !historian.AggregatedEntry)} e1
* The first entry to compare.
* @param {(!historian.Entry | !historian.AggregatedEntry)} e2
* The second entry to compare
* @return {number} -1 if e1 should be before e2, 0 if equal, 1 otherwise.
*/
function compareEntries(e1, e2) {
if (e1.start_time < e2.start_time) {
return -1;
} else if (e1.start_time === e2.start_time) {
if (e1.end_time < e2.end_time) {
return -1;
} else if (e1.end_time === e2.end_time) {
return 0;
}
return 1;
}
return 1;
}
/**
* Metrics that will not be processed or displayed.
* @private @const {!Object}
*/
historian.util.IGNORE_METRICS_ = {
'health': true,
'plug': true,
'plugged': true,
'temperature': true,
'voltage': true
};
/**
* Metrics which will be aggregated.
*/
historian.util.metricsToAggregate = {
'SyncManager app' : -1,
'Foreground process' : -1,
'wakelock_in' : -1
};
/**
* Metrics which will be filtered by UID.
*/
historian.util.appSpecificMetrics = {
'SyncManager app' : true,
'Foreground process' : true,
'wakelock_in' : true,
'Top app': true
};
/**
* Returns whether the metric is aggregated.
* @param {string} name The metric name.
* @return {boolean} True if the metric is aggregated, false otherwise.
*/
historian.util.isAggregatedMetric = function(name) {
return (name in historian.util.metricsToAggregate);
};
/**
* Class for mapping service names to uids.
* @constructor
*/
historian.util.ServiceMapper = function() {
/** @private {!Object} */
this.mapping_ = {};
};
/**
* Adds a service to uid mapping, Assumes only one mapping per service exists.
* However, a uid can correspond to many services.
* If either service or uid is undefined or empty, the mapping is not added.
*
* @param {string} service The service to add.
* @param {string} uid The uid corresponding to the service.
*/
historian.util.ServiceMapper.prototype.addService = function(service, uid) {
if (uid && service) {
this.mapping_[service] = uid;
}
};
/**
* Returns the uid for a service.
* @param {string} service The service to get the UID for.
* @return {string} The uid for the service, empty string if none found.
*/
historian.util.ServiceMapper.prototype.uid = function(service) {
if (service in this.mapping_) {
return this.mapping_[service];
}
return '';
};
/**
* Parses the given csv data, and returns an object containing the battery level
* and other series data, as well as aggregating the sync app and
* wake lock metrics.
* @param {string} csvText Historian data in CSV format.
* @return {!historian.AllData} Series data.
*/
historian.util.readCsv = function(csvText) {
var data = {};
data.serviceMapper = new historian.util.ServiceMapper();
var csv = d3.csv.parse(csvText, function(d) {
var entry = {
metric: d.metric,
type: d.type,
start_time: +d.start_time,
end_time: +d.end_time,
value: d.value
};
if (d.type == 'service') {
data.serviceMapper.addService(d.value, d.opt);
}
return entry;
});
// Find domain of the data.
data.extent = /** @type {!Array<{number}>} */ (d3.extent(csv, function(d) {
return d.start_time;
}));
// Separate data into series - each data value is added as an entry into
// the value array for that series.
var seriesData = /** @type {!historian.SeriesData} */ ([]);
var unique = {};
var syncAppIndex = 0;
csv.forEach(function(d) {
var name = d.metric;
if (name in historian.util.IGNORE_METRICS_) {
return;
}
// if we haven't seen the metric before, create an entry in the series
// array.
if (!unique.hasOwnProperty(name)) {
var series = {
'name': name,
'type': d.type,
'values': []
};
unique[name] = series;
if (name !== 'level') {
seriesData.push(series);
}
if (name in historian.util.metricsToAggregate) {
historian.util.metricsToAggregate[name] = seriesData.length - 1;
}
}
// Add entry into value array for that series.
var series = unique[name];
var entry = {
'start_time': +d.start_time,
'end_time': +d.end_time,
'value': d.value
};
if (d.type === 'int') {
entry.value = +d.value;
}
series.values.push(entry);
});
// wakelock_in replaces wake_lock
// Some wake lock csv entries may still have been generated.
if ('wakelock_in' in unique) {
if ('Partial wakelock' in unique) {
var index = seriesData.indexOf(unique['Partial wakelock']);
seriesData.splice(index, 1);
delete unique['Partial wakelock'];
}
}
historian.util.generateIndexes_(seriesData, unique);
seriesData.forEach(function(serie) {
serie.values.sort(compareEntries);
});
// Aggregate metrics that can have overlapping data points for time values.
for (var m in historian.util.metricsToAggregate) {
var index = historian.util.metricsToAggregate[m];;
if (index !== -1) {
var aggregated = historian.util.aggregateData_(unique[m]);
seriesData[index] = aggregated;
}
}
// Create a color function for each series.
historian.color.generateSeriesColors(seriesData);
data.barData = seriesData;
if (!('level' in unique)) {
unique['level'] = {
'name': 'level',
'type': 'int',
'values': []
};
}
data.levelData = /** @type {!historian.SerieData} */ (unique['level'].values);
return (data);
};
/**
* Assigns an index to each metric, some of which are predefined.
* This determines the order in which the metrics are rendered.
* @param {!historian.SeriesData}
* seriesData The Series to generate indexes for.
* @param {Object} exists The hashmap of series name to series object.
* @private
*/
historian.util.generateIndexes_ = function(seriesData, exists) {
var definedOrder = [
'Reboot',
'CPU running',
'wakelock_in',
'Partial wakelock',
'Screen',
'Brightness',
'SyncManager app',
'JobScheduler',
'Wifi full lock',
'Wifi scan',
'Phone scanning',
'Phone state',
'GPS',
'Mobile radio',
'Data connection',
'Signal strength',
'Network connectivity',
'Video',
'Power Save Mode',
'Doze Mode',
'Phone call',
'Sensor',
'Top app',
'Foreground process'
];
var order = {};
var index = 0;
for (var i = 0; i < definedOrder.length; i++) {
var s = definedOrder[i];
if (s in exists) {
order[s] = index;
index++;
}
}
var numSeries = seriesData.length;
var nextAvailableIndex = numSeries - Object.keys(order).length - 1;
seriesData.forEach(function(s) {
var name = s['name'];
// Always display charging status last. Allocate index at the end.
if (name == 'charging status') {
} else if (name in order) {
s['index'] = numSeries - order[name] - 1;
} else {
s['index'] = nextAvailableIndex;
nextAvailableIndex--;
}
});
if ('charging status' in exists) {
exists['charging status']['index'] = nextAvailableIndex;
}
};
/**
* How far to cluster based on the given min duration.
* @private
*/
historian.util.CLUSTER_DISTANCE_MULTIPLE_ = 8;
/**
* Group together data points close to each other.
* @param {!historian.SeriesData} seriesData The data to cluster.
* @param {number} minDuration The smallest duration visible for the
* current zoom level.
* @return {!Array<!historian.ClusteredSerieData>} Clustered data.
*/
historian.util.cluster = function(seriesData, minDuration) {
var clusteredSeriesData = [];
seriesData.forEach(function(serie) {
if (serie.values.length == 0) {
return;
}
var serieData = [];
clusteredSeriesData.push({
'name': serie.name,
'type': serie.type,
'values': serieData,
'index': serie.index,
'color': serie.color
});
var startIndex = 0;
// Skip blank entries.
while (startIndex < serie.values.length &&
!historian.util.isNonBlankEntry_(serie, serie.values[startIndex])) {
startIndex++;
}
// No non blank entries to cluster.
if (startIndex == serie.values.length) {
return;
}
var clusteredEntry =
new historian.util.ClusterEntry(serie.values[startIndex]);
for (var i = startIndex + 1; i < serie.values.length; i++) {
var d = serie.values[i];
if (!historian.util.isNonBlankEntry_(serie, d)) {
// Skip entries of value 0 while clustering.
continue;
}
var greatestClusterEndTime =
clusteredEntry.first_entry_end_time +
(minDuration * historian.util.CLUSTER_DISTANCE_MULTIPLE_);
// If the entry is far from the previous cluster, start a new cluster.
if (d.start_time >= greatestClusterEndTime) {
serieData.push(clusteredEntry);
clusteredEntry = new historian.util.ClusterEntry(d);
// If the current entry and the previous cluster are visible for the
// current zoom level, don't cluster them together.
// Create a new cluster for the current entry.
} else if (historian.util.duration(d) >= minDuration &&
clusteredEntry.active_duration >= minDuration) {
serieData.push(clusteredEntry);
clusteredEntry = new historian.util.ClusterEntry(d);
} else {
clusteredEntry.add_(d);
}
}
serieData.push(clusteredEntry);
});
return clusteredSeriesData;
};
/**
* Class for holding entries belonging to a cluster.
* @param {(!historian.Entry | !historian.AggregatedEntry)} d
* The data entry to start cluster with.
* @constructor
*/
historian.util.ClusterEntry = function(d) {
/**
* Map from value to count and duration.
* @type {Object}
*/
this.clustered_values = {};
/** @type {number} */
this.start_time = d.start_time;
/** @type {number} */
this.end_time = d.end_time;
/** @type {number} */
this.first_entry_end_time = d.end_time;
/** @type {number} */
this.clustered_count = 0;
/** @type {number} */
this.active_duration = 0;
this.add_(d);
};
/**
* Adds entry to the cluster.
* @param {(!historian.Entry | !historian.AggregatedEntry)} d
* The data entry to add.
* @private
*/
historian.util.ClusterEntry.prototype.add_ = function(d) {
if (this.end_time < d.end_time) {
this.end_time = d.end_time;
}
this.active_duration += historian.util.duration(d);
var values = [];
if (d.services != null) {
// Aggregated entry, more than 1 service exists.
values = d.services;
} else {
values.push(d.value);
}
this.clustered_count += values.length;
values.forEach(function(v) {
if (!(this.clustered_values.hasOwnProperty(v))) {
this.clustered_values[v] = {'count': 0, 'duration': 0};
}
this.clustered_values[v]['count']++;
this.clustered_values[v]['duration'] += historian.util.duration(d);
}, this);
};
/**
* Returns the value to duration map as an array, sorted by duration
* in descending order.
* @return {Array.<!Object>}
*/
historian.util.ClusterEntry.prototype.getSortedValues = function() {
var sorted = [];
for (var key in this.clustered_values) {
sorted.push({
'value': key,
'count': this.clustered_values[key]['count'],
'duration': this.clustered_values[key]['duration']
});
}
sorted.sort(function(a, b) {
if (a['duration'] < b['duration']) {
return 1;
} else if (a['duration'] > b['duration']) {
return -1;
}
return 0;
});
return sorted;
};
/**
* Returns the value with the maximum duration.
* @return {(number | string)}
*/
historian.util.ClusterEntry.prototype.getMaxValue = function() {
var maxValue = '';
for (var v in this.clustered_values) {
var duration = this.clustered_values[v]['duration'];
if (maxValue == '') {
maxValue = v;
} else {
var curMaxDuration = this.clustered_values[maxValue]['duration'];
if (duration > curMaxDuration) {
maxValue = v;
}
}
}
return maxValue;
};
/**
* Values for a metric that won't be displayed as colored lines.
* @private @const {!Object}
*/
historian.util.BLANK_VALUES_ = {
'data conn': 'none'
};
/**
* Returns true if the entry would be rendered as a non blank line.
* @param {!historian.SerieData} serie The series the data entry belongs to.
* @param {(!historian.Entry | !historian.AggregatedEntry)} d Entry.
* @return {boolean} True if non empty, false otherwise.
* @private
*/
historian.util.isNonBlankEntry_ = function(serie, d) {
if (serie.type === 'int' && d.value == 0) {
return false;
}
if (serie.name in historian.util.BLANK_VALUES_) {
if (historian.util.BLANK_VALUES_[serie.name] == d.value) {
return false;
}
}
return true;
};
/**
* Returns the ms duration of a data entry.
* @param {Object} d Entry to calculate duration of.
* @return {number} Duration in ms.
*/
historian.util.duration = function(d) {
return (d.end_time - d.start_time);
};
goog.exportSymbol('historian.formatString', goog.string.subs);
<file_sep>/**
*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// upload.js file contains all the javascript scripts for upload.html
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html('Uploading:' + percentVal);
if (percentComplete === 100) {
setTimeout(function() { percent.html('Uploading Complete!')}, 1000);
setTimeout(function() { percent.html('Analyzing...')}, 3000);
}
},
complete: function(xhr) {
$('body').html(xhr.responseText);
}
});
})();
$(document).ready(function() {
$('.progress').hide();
$('.bar').hide();
$('.percent').hide();
$('form').submit(function() {
$('.progress').show();
$('.bar').show();
$('.percent').show();
});
});
<file_sep>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package parseutils contains the state machine logic to analyze battery history.
package parseutils
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/google/battery-historian/csv"
)
// These constants should be kept consistent with BatteryStats.java.
const (
FormatBatteryLevel = "batteryLevel"
FormatTotalTime = "totalTime"
BatteryStatsCheckinVersion = "9"
HistoryStringPool = "hsp"
HistoryData = "h"
)
var (
// ResetRE is a regular expression to match RESET event.
ResetRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," + HistoryData + "," +
"(?P<timeDelta>\\d+)" + ":RESET:TIME:(?P<timeStamp>\\d+)")
// ShutdownRE is a regular expression to match SHUTDOWN event.
ShutdownRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," + HistoryData + "," +
"(?P<timeDelta>\\d+)" + ":SHUTDOWN")
// StartRE is a regular expression to match START event.
StartRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," + HistoryData + "," +
"(?P<timeDelta>\\d+):" + "START")
// TimeRE is a regular expression to match TIME event.
TimeRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," + HistoryData + "," +
"(?P<timeDelta>\\d+)" + ":TIME:(?P<timeStamp>\\d+)")
// GenericHistoryLineRE is a regular expression to match any of the history lines.
GenericHistoryLineRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," +
HistoryData + "," + "(?P<timeDelta>\\d+).+")
// GenericHistoryStringPoolLineRE is a regular expression to match any of the history string pool lines.
GenericHistoryStringPoolLineRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," +
HistoryStringPool + "," + "(?P<index>\\d+),(?P<uid>-?\\d+),(?P<service>.+)")
// VersionLineRE is a regular expression to match the vers statement in the history log.
VersionLineRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + `,\d+,i,vers,\d+,\d+,.*`)
// DataRE is a regular expression to match the data event log.
DataRE = regexp.MustCompile("(?P<transition>[+-]?)" + "(?P<key>\\w+)" + "(,?(=?(?P<value>\\S+))?)")
// PIIRE is a regular expression to match any PII string of the form abc@xxx.yyy.
PIIRE = regexp.MustCompile("(?P<prefix>\\S+/)" + "(?P<account>\\S+)" + "(?P<site>@)" + "(?P<suffix>\\S*)")
// OverflowRE is a regular expression that matches OVERFLOW event.
OverflowRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," + HistoryData + "," +
"\\d+:\\*OVERFLOW\\*")
// CheckinApkLineRE is a regular expression that matches the "apk" line in a checkin log.
CheckinApkLineRE = regexp.MustCompile("(\\d+,)?(?P<uid>\\d+),l,apk,\\d+,(?P<pkgName>[^,]+),.*")
// Constants defined in http://developer.android.com/reference/android/net/ConnectivityManager.html
connConstants = map[string]string{
"0": "TYPE_MOBILE",
"1": "TYPE_WIFI",
"2": "TYPE_MOBILE_MMS",
"3": "TYPE_MOBILE_SUPL",
"4": "TYPE_MOBILE_DUN",
"5": "TYPE_MOBILE_HIPRI",
"6": "TYPE_WIMAX",
"7": "TYPE_BLUETOOTH",
"8": "TYPE_DUMMY",
"9": "TYPE_ETHERNET",
"17": "TYPE_VPN",
}
)
// ServiceUID contains the identifying service for battery operations.
type ServiceUID struct {
Start int64
// We are treating UIDs as strings
Service, UID string
}
// Dist is a distribution summary for a battery metric.
type Dist struct {
Num int32
TotalDuration time.Duration
MaxDuration time.Duration
}
// interval is used for gathering all sync durations to summarize total sync time
type interval struct {
startTimeMs, endTimeMs int64
}
// Calculate total duration of sync time without breaking down by apps
func calTotalSync(state *DeviceState) Dist {
var d Dist
d.Num = int32(len(state.syncIntervals))
// merge intervals
var intervals []interval
if d.Num > 0 {
intervals = mergeIntervals(state.syncIntervals)
}
// loop through intervals to gather total sync time
for _, i := range intervals {
duration := time.Duration(i.endTimeMs-i.startTimeMs) * time.Millisecond
d.TotalDuration += duration
// the max duration here is the merged intervals' max duration
if duration > d.MaxDuration {
d.MaxDuration = duration
}
}
return d
}
// Merge all the intervals for syncs in all apps
func mergeIntervals(intervals []interval) []interval {
// Need to sort the intervals by startTime here,
// because the following algorithm will be relied on sorted intervals
sort.Sort(sortByStartTime(intervals))
var res []interval
prev := intervals[0]
for _, cur := range intervals[1:] {
if prev.endTimeMs < cur.startTimeMs {
res = append(res, prev)
prev = cur
} else {
prev = interval{prev.startTimeMs, max(prev.endTimeMs, cur.endTimeMs)}
}
}
res = append(res, prev)
return res
}
// Counts on negative transitions
func (s *ServiceUID) assign(curTime int64, summaryActive bool, summaryStartTime int64, activeMap map[string]*ServiceUID, summary map[string]Dist, tr, value, desc string, csv *csv.State) error {
_, alreadyActive := activeMap[value]
switch tr {
case "":
// The entity was already active when the summary was taken,
// so count the active time since the beginning of the summary.
s.Start = summaryStartTime
activeMap[value] = s
case "+":
if alreadyActive {
return fmt.Errorf("two positive transitions seen for %q", desc)
}
s.Start = curTime
activeMap[value] = s
case "-":
if !alreadyActive {
if summary[s.Service].Num != 0 {
return fmt.Errorf("two negative transitions for %q:%q", desc, tr)
}
// There was no + transition for this, so assuming that it was
// already active at the beginning of the summary period.
s.Start = summaryStartTime
activeMap[value] = s
csv.AddEntryWithOpt(desc, s, s.Start, s.UID)
}
if summaryActive {
d := summary[s.Service]
duration := time.Duration(curTime-activeMap[value].Start) * time.Millisecond
d.TotalDuration += duration
if duration > d.MaxDuration {
d.MaxDuration = duration
}
d.Num++
summary[s.Service] = d
}
delete(activeMap, value)
default:
return fmt.Errorf("unknown transition for %q:%q", desc, tr)
}
csv.AddEntryWithOpt(desc, s, curTime, s.UID)
return nil
}
func (s *ServiceUID) initStart(curTime int64) {
if s.Start != 0 {
s.Start = curTime
}
}
func (s *ServiceUID) updateSummary(curTime int64, summaryActive bool, summaryStartTime int64, summary map[string]Dist) {
if s.Start == 0 {
s.Start = summaryStartTime
}
if summaryActive {
d := summary[s.Service]
duration := time.Duration(curTime-s.Start) * time.Millisecond
d.TotalDuration += duration
if duration > d.MaxDuration {
d.MaxDuration = duration
}
d.Num++
summary[s.Service] = d
}
s.Start = curTime
}
// GetStartTime returns the start time of the entry.
func (s *ServiceUID) GetStartTime() int64 {
return s.Start
}
// GetType returns the type of the entry.
func (s *ServiceUID) GetType() string {
return "service"
}
// GetValue returns the stored service for the entry.
func (s *ServiceUID) GetValue() string {
return s.Service
}
// GetKey returns the unique identifier for the entry.
// UIDs can have multiple service names, however we want each
// service name to have it's own csv entry.
func (s *ServiceUID) GetKey(desc string) csv.Key {
return csv.Key{
desc,
s.Service,
}
}
// tsInt contains an integer state with initial timestamp in ms.
type tsInt struct {
Start int64
Value int
}
func (s *tsInt) assign(curTime int64, value string, summaryActive bool, desc string, csv *csv.State) error {
parsedInt, err := strconv.Atoi(value)
if err != nil {
return fmt.Errorf("parsing int error for %q", desc)
}
csv.AddEntry(desc, s, curTime)
s.Value = parsedInt
s.Start = curTime
csv.AddEntry(desc, s, curTime)
return nil
}
func (s *tsInt) initStart(curTime int64) {
if s.Start != 0 {
s.Start = curTime
}
}
// GetStartTime returns the start time of the entry.
func (s *tsInt) GetStartTime() int64 {
return s.Start
}
// GetType returns the type of the entry.
func (s *tsInt) GetType() string {
return "int"
}
// GetValue returns the stored service for the entry.
func (s *tsInt) GetValue() string {
return strconv.Itoa(s.Value)
}
// GetKey returns the unique identifier for the entry.
func (s *tsInt) GetKey(desc string) csv.Key {
return csv.Key{
desc,
"",
}
}
// tsBool contains a bool state with initial timestamp in ms.
type tsBool struct {
Start int64
Value bool
}
// Counts on negative transitions only, as some booleans just indicate a state
func (s *tsBool) assign(curTime int64, summaryActive bool, summaryStartTime int64, summary *Dist, tr, desc string, csv *csv.State) error {
isOn := false
switch tr {
case "+":
isOn = true
case "-":
if !s.Value {
if summary.Num != 0 {
return fmt.Errorf("two negative transitions for %q:%q", desc, tr)
}
// First negative transition for an event that was in progress at start.
s.Value = true
// Set the start time so the csv entry stores the correct value.
s.Start = summaryStartTime
csv.AddEntry(desc, s, s.Start)
}
default:
return fmt.Errorf("unknown transition for %q:%q", desc, tr)
}
if s.Start == 0 {
s.Start = summaryStartTime
}
// On -> Off
if !isOn && s.Value {
if summaryActive {
duration := time.Duration(curTime-s.Start) * time.Millisecond
summary.TotalDuration += duration
if duration > summary.MaxDuration {
summary.MaxDuration = duration
}
summary.Num++
}
s.Value = false
csv.AddEntry(desc, s, curTime)
}
// Off -> On
if isOn && !s.Value {
s.Value = true
csv.AddEntry(desc, s, curTime)
}
// Note the time the new state starts
s.Start = curTime
return nil
}
func (s *tsBool) initStart(curTime int64) {
if s.Start != 0 {
s.Start = curTime
}
}
func (s *tsBool) updateSummary(curTime int64, summaryActive bool, summaryStartTime int64, summary *Dist) {
if s.Start == 0 {
s.Start = summaryStartTime
}
if s.Value {
if summaryActive {
duration := time.Duration(curTime-s.Start) * time.Millisecond
summary.TotalDuration += duration
if duration > summary.MaxDuration {
summary.MaxDuration = duration
}
summary.Num++
}
s.Start = curTime
}
}
// GetStartTime returns the start time of the entry.
func (s *tsBool) GetStartTime() int64 {
return s.Start
}
// GetType returns the type of the entry.
func (s *tsBool) GetType() string {
return "bool"
}
// GetValue returns the stored service for the entry.
func (s *tsBool) GetValue() string {
if s.Value {
return "true"
}
return "false"
}
// GetKey returns the unique identifier for the entry.
func (s *tsBool) GetKey(desc string) csv.Key {
return csv.Key{
desc,
"",
}
}
// tsString contains a string state with initial timestamp in ms
type tsString struct {
Start int64
Value string
}
func (s *tsString) assign(curTime int64, summaryActive bool, summaryStartTime int64, summary map[string]Dist, value, desc string, csv *csv.State) error {
if s.Start == 0 {
s.Start = summaryStartTime
}
if s.Value != value {
csv.AddEntry(desc, s, curTime)
if summaryActive {
d := summary[s.Value]
duration := time.Duration(curTime-s.Start) * time.Millisecond
d.TotalDuration += duration
if duration > d.MaxDuration {
d.MaxDuration = duration
}
d.Num++
summary[s.Value] = d
}
// Note the time the new state starts
s.Start = curTime
s.Value = value
csv.AddEntry(desc, s, curTime)
}
return nil
}
func (s *tsString) initStart(curTime int64) {
if s.Start != 0 {
s.Start = curTime
}
}
func (s *tsString) updateSummary(curTime int64, summaryActive bool, summaryStartTime int64, summary map[string]Dist) {
if s.Start == 0 {
s.Start = summaryStartTime
}
if s.Value == "" {
s.Value = "default"
}
if summaryActive {
d := summary[s.Value]
duration := time.Duration(curTime-s.Start) * time.Millisecond
d.TotalDuration += duration
if duration > d.MaxDuration {
d.MaxDuration = duration
}
d.Num++
summary[s.Value] = d
}
s.Start = curTime
}
// GetStartTime returns the start time of the entry.
func (s *tsString) GetStartTime() int64 {
return s.Start
}
// GetType returns the type of the entry.
func (s *tsString) GetType() string {
return "string"
}
// GetValue returns the stored service for the entry.
func (s *tsString) GetValue() string {
return s.Value
}
// GetKey returns the unique identifier for the entry.
func (s *tsString) GetKey(desc string) csv.Key {
return csv.Key{
desc,
"",
}
}
func (d *Dist) print(b io.Writer, duration time.Duration) {
fmt.Fprintf(b, "=> Rate (per hr): (%5.2f , %10.2f secs)\t Total: (%5d, %20s, %20s)\n", float64(d.Num)/duration.Hours(), d.TotalDuration.Seconds()/duration.Hours(), d.Num, d.TotalDuration, d.MaxDuration)
}
// DeviceState maintains the instantaneous state of the device created using battery history events.
//
// All fields of this type must have corresponding initialization code in initStartTimeForAllStates()
type DeviceState struct {
CurrentTime int64
LastWakeupTime int64 // To deal with asynchronous arrival of wake reasons
LastWakeupDuration time.Duration // To deal with asynchronous arrival
WakeLockInSeen bool // To determine if detailed wakelock_in events (Ewl) are available for use instead of wake lock (w).
// Instanteous state
Temperature tsInt
Voltage tsInt
BatteryLevel tsInt
Brightness tsInt
SignalStrength tsInt
PhoneState tsString
DataConnection tsString // hspa, hspap, lte
PlugType tsString
ChargingStatus tsString
Health tsString
//WakeLockType tsString // Alarm, WAlarm
// Device State metrics from BatteryStats
CPURunning tsBool
SensorOn tsBool
GpsOn tsBool
WifiFullLock tsBool
WifiScan tsBool
WifiMulticastOn tsBool
MobileRadioOn tsBool
WifiOn tsBool
WifiRunning tsBool
PhoneScanning tsBool
ScreenOn tsBool
Plugged tsBool
PhoneInCall tsBool
WakeLockHeld tsBool
// SyncOn tsBool
IdleModeOn tsBool
WakeLockHolder ServiceUID
WakeupReason ServiceUID
syncIntervals []interval
// Map of uid -> serviceUID for all active entities
ActiveProcessMap map[string]*ServiceUID
AppSyncingMap map[string]*ServiceUID
ForegroundProcessMap map[string]*ServiceUID
TopApplicationMap map[string]*ServiceUID // There can only be one on top, so the map will have just one entry
// Connectivity changes are represented in the history log like other applications.
// For example, we get lines like 9,hsp,3,1,"CONNECTED" and 9,hsp,28,1,"DISCONNECTED",
// so they are processed and read into ServiceUID objects by the code down in
// analyzeHistoryLine. So even though changes aren't specific to an app, for the sake
// of simplicity, they are processed like the rest.
ConnectivityMap map[string]*ServiceUID
ScheduledJobMap map[string]*ServiceUID
// If wakelock_in events are not available, then only the first entity to acquire a
// wakelock gets charged, so the map will have just one entry
WakeLockMap map[string]*ServiceUID
// Event names
/*
EventNull tsBool
EventProc ServiceUID
EventFg ServiceUID
EventTop ServiceUID
EventSy ServiceUID
*/
// Not implemented yet
BluetoothOn tsBool
VideoOn tsBool
AudioOn tsBool
LowPowerModeOn tsBool
}
// initStartTimeForAllStates is used when the device transitions from charging
// battery state to discharging. At this time, we don't want to reset the
// state variables, just start accounting from this time. So if a wakelock
// has been held (or a screen turned on) for some time, we want to discount
// any time prior to the event of the device being unplugged,
// but still remember what state the device is in and initialize the time.
func (state *DeviceState) initStartTimeForAllStates() {
state.Temperature.initStart(state.CurrentTime)
state.Voltage.initStart(state.CurrentTime)
state.BatteryLevel.initStart(state.CurrentTime)
state.Brightness.initStart(state.CurrentTime)
state.SignalStrength.initStart(state.CurrentTime)
state.PhoneState.initStart(state.CurrentTime)
state.DataConnection.initStart(state.CurrentTime)
state.PlugType.initStart(state.CurrentTime)
state.ChargingStatus.initStart(state.CurrentTime)
state.Health.initStart(state.CurrentTime)
state.CPURunning.initStart(state.CurrentTime)
state.SensorOn.initStart(state.CurrentTime)
state.GpsOn.initStart(state.CurrentTime)
state.WifiFullLock.initStart(state.CurrentTime)
state.WifiScan.initStart(state.CurrentTime)
state.WifiMulticastOn.initStart(state.CurrentTime)
state.MobileRadioOn.initStart(state.CurrentTime)
state.WifiOn.initStart(state.CurrentTime)
state.WifiRunning.initStart(state.CurrentTime)
state.PhoneScanning.initStart(state.CurrentTime)
state.ScreenOn.initStart(state.CurrentTime)
state.Plugged.initStart(state.CurrentTime)
state.PhoneInCall.initStart(state.CurrentTime)
state.WakeLockHeld.initStart(state.CurrentTime)
state.WakeLockHolder.initStart(state.CurrentTime)
state.WakeupReason.initStart(state.CurrentTime)
state.BluetoothOn.initStart(state.CurrentTime)
state.VideoOn.initStart(state.CurrentTime)
state.AudioOn.initStart(state.CurrentTime)
state.LowPowerModeOn.initStart(state.CurrentTime)
state.IdleModeOn.initStart(state.CurrentTime)
for _, s := range state.ActiveProcessMap {
s.initStart(state.CurrentTime)
}
for _, s := range state.AppSyncingMap {
s.initStart(state.CurrentTime)
}
for _, s := range state.ForegroundProcessMap {
s.initStart(state.CurrentTime)
}
for _, s := range state.TopApplicationMap {
s.initStart(state.CurrentTime)
}
for _, s := range state.ConnectivityMap {
s.initStart(state.CurrentTime)
}
for _, s := range state.WakeLockMap {
s.initStart(state.CurrentTime)
}
for _, s := range state.ScheduledJobMap {
s.initStart(state.CurrentTime)
}
}
// newDeviceState returns a new properly initialized DeviceState structure.
func newDeviceState() *DeviceState {
return &DeviceState{
ActiveProcessMap: make(map[string]*ServiceUID),
AppSyncingMap: make(map[string]*ServiceUID),
ForegroundProcessMap: make(map[string]*ServiceUID),
TopApplicationMap: make(map[string]*ServiceUID),
ConnectivityMap: make(map[string]*ServiceUID),
WakeLockMap: make(map[string]*ServiceUID),
ScheduledJobMap: make(map[string]*ServiceUID),
}
}
// ActivitySummary contains battery statistics during an aggregation interval.
// Each entry in here should have a corresponding value in session.proto:Summary
type ActivitySummary struct {
Reason string
Active bool
StartTimeMs int64 // Millis
EndTimeMs int64 // Millis
InitialBatteryLevel int
FinalBatteryLevel int
SummaryFormat string
PluggedInSummary Dist
ScreenOnSummary Dist
MobileRadioOnSummary Dist
WifiOnSummary Dist
CPURunningSummary Dist
GpsOnSummary Dist
SensorOnSummary Dist
WifiScanSummary Dist
WifiFullLockSummary Dist
WifiRunningSummary Dist
WifiMulticastOnSummary Dist
PhoneCallSummary Dist
PhoneScanSummary Dist
// Stats for total syncs without breaking down by apps
TotalSyncSummary Dist
// Stats for each individual state
DataConnectionSummary map[string]Dist // LTE, HSPA
ConnectivitySummary map[string]Dist
ForegroundProcessSummary map[string]Dist
ActiveProcessSummary map[string]Dist
TopApplicationSummary map[string]Dist
PerAppSyncSummary map[string]Dist
WakeupReasonSummary map[string]Dist
ScheduledJobSummary map[string]Dist
HealthSummary map[string]Dist
PlugTypeSummary map[string]Dist
ChargingStatusSummary map[string]Dist // c, d, n, f
PhoneStateSummary map[string]Dist
WakeLockSummary map[string]Dist
Date string
AudioOnSummary Dist
VideoOnSummary Dist
LowPowerModeOnSummary Dist
IdleModeOnSummary Dist
}
// newActivitySummary returns a new properly initialized ActivitySummary structure.
func newActivitySummary(summaryFormat string) *ActivitySummary {
return &ActivitySummary{
Active: true,
SummaryFormat: summaryFormat,
InitialBatteryLevel: -1,
DataConnectionSummary: make(map[string]Dist),
ConnectivitySummary: make(map[string]Dist),
ForegroundProcessSummary: make(map[string]Dist),
ActiveProcessSummary: make(map[string]Dist),
TopApplicationSummary: make(map[string]Dist),
PerAppSyncSummary: make(map[string]Dist),
WakeupReasonSummary: make(map[string]Dist),
HealthSummary: make(map[string]Dist),
PlugTypeSummary: make(map[string]Dist),
ChargingStatusSummary: make(map[string]Dist),
PhoneStateSummary: make(map[string]Dist),
WakeLockSummary: make(map[string]Dist),
ScheduledJobSummary: make(map[string]Dist),
}
}
// MultiDist is a named distribution summary for a battery metric.
type MultiDist struct {
Name string
Stat Dist
}
// SortByTimeAndCount sorts MultiDist in descending order of TotalDuration.
type SortByTimeAndCount []MultiDist
func (a SortByTimeAndCount) Len() int { return len(a) }
func (a SortByTimeAndCount) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a SortByTimeAndCount) Less(i, j int) bool {
if a[i].Stat.TotalDuration != a[j].Stat.TotalDuration {
// Sort order is time followed by count
return a[i].Stat.TotalDuration < a[j].Stat.TotalDuration
}
return a[i].Stat.Num < a[j].Stat.Num
}
// sortByStartTime sorts intervals in ascending order of startTimeMs
type sortByStartTime []interval
func (a sortByStartTime) Len() int { return len(a) }
func (a sortByStartTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a sortByStartTime) Less(i, j int) bool {
return a[i].startTimeMs < a[j].startTimeMs
}
// max function for int64
func max(a int64, b int64) int64 {
if a >= b {
return a
}
return b
}
func printMap(b io.Writer, name string, m map[string]Dist, duration time.Duration) {
stats := make([]MultiDist, len(m), len(m))
idx := 0
for k, v := range m {
stats[idx] = MultiDist{Name: k, Stat: v}
idx++
}
sort.Sort(sort.Reverse(SortByTimeAndCount(stats)))
fmt.Fprintln(b, name, "\n---------------------")
for _, s := range stats {
if s.Stat.TotalDuration.Nanoseconds() > 0 {
fmt.Fprintf(b, "%85s => Rate (per hr): (%5.2f , %10.2f secs)\tTotal: (%5d, %20s, %20s)\n", s.Name, float64(s.Stat.Num)/duration.Hours(), s.Stat.TotalDuration.Seconds()/duration.Hours(), s.Stat.Num, s.Stat.TotalDuration, s.Stat.MaxDuration)
}
}
fmt.Fprintln(b)
}
// concludeActiveFromState summarizes all activeProcesses, syncs running, apps on top, etc.
func concludeActiveFromState(state *DeviceState, summary *ActivitySummary, csv *csv.State) (*DeviceState, *ActivitySummary) {
// Battery level: Bl **
if state.BatteryLevel.Value != summary.FinalBatteryLevel {
// Throw: Logical error as summary.FinalBatteryLevel should already be up to date
state.BatteryLevel.Start = state.CurrentTime
}
//////////////// Boolean States ////////////
// CPURunning: r **
state.CPURunning.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.CPURunningSummary)
// Screen: S **
state.ScreenOn.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.ScreenOnSummary)
// Phone in call: Pcl **
state.PhoneInCall.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.PhoneCallSummary)
// Mobile Radio: Pr **
state.MobileRadioOn.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.MobileRadioOnSummary)
// Phone scanning: Psc **
state.PhoneScanning.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.PhoneScanSummary)
// Wifi: W **
state.WifiOn.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.WifiOnSummary)
// Wifi Full lock: Wl **
state.WifiFullLock.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.WifiFullLockSummary)
// Wifi Running: Wr **
state.WifiRunning.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.WifiRunningSummary)
// Plugged: BP
state.Plugged.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.PluggedInSummary)
// GPS: g
state.GpsOn.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.GpsOnSummary)
// Sensor: s
state.SensorOn.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.SensorOnSummary)
// Wifi Scan: Ws
state.WifiScan.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.WifiScanSummary)
// Wifi Multicast: Wm
state.WifiMulticastOn.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.WifiMulticastOnSummary)
// Idle (Doze) Mode: di
state.IdleModeOn.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, &summary.IdleModeOnSummary)
//////////////// String States ////////////
// Phone state: Pst
state.PhoneState.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.PhoneStateSummary)
// Data Connection: Pcn **
state.DataConnection.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.DataConnectionSummary)
// Plug type: Bp
state.PlugType.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.PlugTypeSummary)
// Charging status: Bs
state.ChargingStatus.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.ChargingStatusSummary)
// Battery Health: Bh
state.Health.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.HealthSummary)
/////////////////////////
// wake_reason: wr **
if state.WakeupReason.Service != "" {
state.WakeupReason.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.WakeupReasonSummary)
}
// wake_lock: w **
if state.WakeLockHeld.Value && !state.WakeLockInSeen {
state.WakeLockHolder.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.WakeLockSummary)
}
///////////////////
// Active processes: Epr **
for _, suid := range state.ActiveProcessMap {
suid.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.ActiveProcessSummary)
}
// Foreground processes: Efg **
for _, suid := range state.ForegroundProcessMap {
suid.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.ForegroundProcessSummary)
}
// Top application: Etp **
for _, suid := range state.TopApplicationMap {
suid.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.TopApplicationSummary)
}
// Sync application: Esy **
for _, suid := range state.AppSyncingMap {
var start int64
if suid.Start == 0 {
start = summary.StartTimeMs
} else {
start = suid.Start
}
if summary.Active {
i := interval{start, state.CurrentTime}
state.syncIntervals = append(state.syncIntervals, i)
}
suid.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.PerAppSyncSummary)
}
// wakelock_in: Ewl **
for _, suid := range state.WakeLockMap {
suid.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.WakeLockSummary)
}
// Connectivity changes: Ecn **
for _, suid := range state.ConnectivityMap {
t, ok := connConstants[suid.UID]
if !ok {
t = "UNKNOWN"
}
ntwkSummary := summary.ConnectivitySummary
if suid.Start == 0 {
suid.Start = summary.StartTimeMs
}
if summary.Active {
d := ntwkSummary[t]
duration := time.Duration(state.CurrentTime-suid.Start) * time.Millisecond
d.TotalDuration += duration
if duration > d.MaxDuration {
d.MaxDuration = duration
}
d.Num++
ntwkSummary[t] = d
}
suid.Start = state.CurrentTime
}
t := time.Unix(0, summary.StartTimeMs*1e6)
summary.Date = fmt.Sprintf("%d-%02d-%02d", t.Year(), t.Month(), t.Day())
// Applications execute scheduled jobs: Ejb
for _, suid := range state.ScheduledJobMap {
suid.updateSummary(state.CurrentTime, summary.Active, summary.StartTimeMs, summary.ScheduledJobSummary)
}
// Temperature: Bt
// Voltage: Bv
// Screen Brightness: Sb
// Phone signal strength: Pss
// Not implemented as yet:
// Bluetooth, Audio, Video
return state, summary
}
// summarizeActiveState stores the current summary in the output slice and resets the summary.
// If a reset of state is requested too (after a reboot or a reset of battery history) only then
// is the state cleared, otherwise the state is retained after summarizing.
func summarizeActiveState(d *DeviceState, s *ActivitySummary, summaries *[]ActivitySummary, reset bool, reason string, csv *csv.State) (*DeviceState, *ActivitySummary) {
if s.StartTimeMs != s.EndTimeMs {
s.Reason = reason
d, s = concludeActiveFromState(d, s, csv)
s.TotalSyncSummary = calTotalSync(d)
*summaries = append(*summaries, *s)
}
s = newActivitySummary(s.SummaryFormat)
d.syncIntervals = []interval{}
if !reset {
s.StartTimeMs = d.CurrentTime
s.EndTimeMs = d.CurrentTime
s.InitialBatteryLevel = d.BatteryLevel.Value
s.FinalBatteryLevel = d.BatteryLevel.Value
} else {
d = newDeviceState()
}
return d, s
}
// Print outputs a string containing aggregated battery stats.
func (s *ActivitySummary) Print(b io.Writer) {
fmt.Fprintln(b, "Summary Period: (", s.StartTimeMs, "-", s.EndTimeMs, ") :",
time.Unix(0, s.StartTimeMs*int64(time.Millisecond)),
" - ", time.Unix(0, s.EndTimeMs*int64(time.Millisecond)))
fmt.Fprintln(b, "Date: ", s.Date)
fmt.Fprintln(b, "Reason:", s.Reason)
duration := time.Duration(s.EndTimeMs-s.StartTimeMs) * time.Millisecond
if duration == 0 {
log.Printf("Error! Invalid duration equals 0 !")
}
fmt.Fprintln(b, "Total Summary Duration ", duration)
fmt.Fprintln(b, "BatteryLevel Drop ", s.InitialBatteryLevel, "->", s.FinalBatteryLevel, "=",
s.InitialBatteryLevel-s.FinalBatteryLevel)
levelDropPerHour := float64(s.InitialBatteryLevel-s.FinalBatteryLevel) / duration.Hours()
fmt.Fprintf(b, "Drop rate per hour : %.2f pct/hr\n", levelDropPerHour)
fmt.Fprintln(b)
fmt.Fprintf(b, "%30s", "ScreenOn: ")
s.ScreenOnSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "CPURunning: ")
s.CPURunningSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "RadioOn: ")
s.MobileRadioOnSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "PhoneCall")
s.PhoneCallSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "GpsOn")
s.GpsOnSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "WifiFullLock")
s.WifiFullLockSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "WifiScan")
s.WifiScanSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "WifiMulticastOn")
s.WifiMulticastOnSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "WifiOn: ")
s.WifiOnSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "WifiRunning")
s.WifiRunningSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "PhoneScan")
s.PhoneScanSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "SensorOn")
s.SensorOnSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "PluggedIn:")
s.PluggedInSummary.print(b, duration)
fmt.Fprintf(b, "%30s", "DozeModeOn:")
s.IdleModeOnSummary.print(b, duration)
printMap(b, "DataConnectionSummary", s.DataConnectionSummary, duration)
printMap(b, "ConnectivitySummary", s.ConnectivitySummary, duration)
printMap(b, "WakeLockSummary", s.WakeLockSummary, duration)
printMap(b, "TopApplicationSummary", s.TopApplicationSummary, duration)
printMap(b, "PerAppSyncSummary", s.PerAppSyncSummary, duration)
fmt.Fprintf(b, "TotalSyncTime: %v, TotalSyncNum: %v\n", s.TotalSyncSummary.TotalDuration, s.TotalSyncSummary.Num)
printMap(b, "WakeupReasonSummary", s.WakeupReasonSummary, duration)
printMap(b, "ForegroundProcessSummary", s.ForegroundProcessSummary, duration)
printMap(b, "HealthSummary", s.HealthSummary, duration)
printMap(b, "PlugTypeSummary", s.PlugTypeSummary, duration)
printMap(b, "ChargingStatusSummary", s.ChargingStatusSummary, duration)
printMap(b, "PhoneStateSummary", s.PhoneStateSummary, duration)
printMap(b, "ActiveProcessSummary", s.ActiveProcessSummary, duration)
printMap(b, "ScheduledJobSummary", s.ScheduledJobSummary, duration)
}
// updateState method interprets the events contained in the battery history string
// according to the definitions in:
// android//frameworks/base/core/java/android/os/BatteryStats.java
func updateState(b io.Writer, csv *csv.State, state *DeviceState, summary *ActivitySummary, summaries *[]ActivitySummary,
idxMap map[string]ServiceUID, idx, tr, key, value string) (*DeviceState, *ActivitySummary, error) {
switch key {
case "Bs": // status
i := state.ChargingStatus
active := summary.Active
ret := state.ChargingStatus.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
summary.ChargingStatusSummary, value, "Charging status", csv)
switch value {
case "?": // unknown
case "c": // charging
if active && i != state.ChargingStatus {
state, summary = summarizeActiveState(state, summary, summaries, false, "CHARGING", csv)
summary.Active = false
}
case "n": // not-charging
fallthrough
case "d": // discharging
if !active {
state.initStartTimeForAllStates()
summary.StartTimeMs = state.CurrentTime
summary.EndTimeMs = state.CurrentTime
summary.Active = true
}
case "f": // full
default:
return state, summary, fmt.Errorf("unknown status = %q", value)
}
return state, summary, ret
case "Bh": // health
switch value {
case "?": // unknown
case "g": // good
case "h": // overheat
case "d": // dead
case "v": // over-voltage
case "f": // failure
case "c": // cold
default:
return state, summary, fmt.Errorf("unknown health = %q", value)
}
return state, summary, state.Health.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
summary.HealthSummary, value, "health", csv)
case "Bp": // plug
switch value {
case "n": // none
case "a": // ac
case "w": // wireless
case "u": // usb
default:
return state, summary, fmt.Errorf("unknown plug type = %q", value)
}
return state, summary, state.PlugType.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
summary.PlugTypeSummary, value, "plug", csv)
case "Bt": // temperature
return state, summary, state.Temperature.assign(state.CurrentTime, value, summary.Active, "temperature", csv)
case "Bv": // volt
return state, summary, state.Voltage.assign(state.CurrentTime, value, summary.Active, "voltage", csv)
case "Bl": // level
i := state.BatteryLevel
parsedLevel, err := strconv.Atoi(value)
if err != nil {
return state, summary, errors.New("parsing int error for level")
}
ret := state.BatteryLevel.assign(state.CurrentTime, value, summary.Active, "level", csv)
summary.FinalBatteryLevel = parsedLevel
if !summary.Active || summary.InitialBatteryLevel == -1 {
summary.InitialBatteryLevel = parsedLevel
} else {
if summary.Active && summary.SummaryFormat == FormatBatteryLevel && i != state.BatteryLevel {
state, summary = summarizeActiveState(state, summary, summaries, false, "LEVEL", csv)
}
}
return state, summary, ret
case "BP": // plugged = {+BP, -BP}
return state, summary, state.Plugged.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.PluggedInSummary, tr, "plugged", csv)
case "r": // running
// Needs special handling as the wakeup reason will arrive asynchronously
switch tr {
case "+":
// Note the time the new state starts
state.CPURunning.Start = state.CurrentTime
state.CPURunning.Value = true
csv.AddEntry("CPU running", &state.CPURunning, state.CurrentTime)
// Store the details of the last wakeup to correctly attribute wakeup reason
state.LastWakeupTime = state.CurrentTime
case "-":
if !state.CPURunning.Value {
// -r was received without a corresponding +r
if state.CPURunning.Start != 0 && state.CPURunning.Start != summary.StartTimeMs {
// This is not the beginning of a new session
return state, summary, errors.New("-r received without a corresponding +r")
}
state.CPURunning.Start = summary.StartTimeMs
}
csv.AddEntry("CPU running", &state.CPURunning, state.CurrentTime)
if summary.Active {
duration := time.Duration(state.CurrentTime-state.CPURunning.Start) * time.Millisecond
summary.CPURunningSummary.TotalDuration += duration
if duration > summary.CPURunningSummary.MaxDuration {
summary.CPURunningSummary.MaxDuration = duration
}
summary.CPURunningSummary.Num++
}
state.LastWakeupDuration = time.Duration(state.CurrentTime-state.CPURunning.Start) * time.Millisecond
// Note the time the new state starts
state.CPURunning.Start = state.CurrentTime
state.CPURunning.Value = false
// Account for wakeup reason stats
if state.WakeupReason.Service != "" {
if summary.Active {
d := summary.WakeupReasonSummary[state.WakeupReason.Service]
duration := state.LastWakeupDuration
d.TotalDuration += duration
if duration > d.MaxDuration {
d.MaxDuration = duration
}
d.Num++
summary.WakeupReasonSummary[state.WakeupReason.Service] = d
}
state.WakeupReason.Service = ""
}
default:
return state, summary, fmt.Errorf("unknown transition for cpu running : %q", tr)
}
return state, summary, nil
case "wr": // wake reason
// Special case as there are no transitions for this.
// Just the wake reason that also arrives asynchronously
// WakeupReason, WakeupReasonSummary
serviceUID, ok := idxMap[value]
if !ok {
return state, summary, fmt.Errorf("unable to find index %q in idxMap for wakelock", value)
}
state.WakeupReason.Service = serviceUID.Service
if state.CPURunning.Value == true {
state.WakeupReason.Start = state.CPURunning.Start
} else {
// Wakeup reason received when CPU is not running.
// Summarize here based on the lastwakeuptime and lastwakeupduration
if state.LastWakeupTime == 0 {
return state, summary, nil
}
state.WakeupReason.Start = state.LastWakeupTime
if summary.Active {
d := summary.WakeupReasonSummary[state.WakeupReason.Service]
duration := state.LastWakeupDuration
d.TotalDuration += duration
if duration > d.MaxDuration {
d.MaxDuration = duration
}
d.Num++
summary.WakeupReasonSummary[state.WakeupReason.Service] = d
}
state.WakeupReason.Service = ""
state.LastWakeupTime = 0
state.LastWakeupDuration = 0
}
case "w": // wake_lock
// Special case this, as the +w will only have the first application to take the wakelock
if state.WakeLockInSeen {
// If wakelock_in has been seen, ignore wake_lock.
return state, summary, nil
}
switch tr {
case "":
fallthrough
case "+":
if state.WakeLockHeld.Value {
if value == "" {
// Dealing with the case where we see +w=123, +w
// This is just reporting that a wakelock was already held when
// the summary was requested, so we just ignore +w
if state.WakeLockHolder.Service == "" {
return state, summary, errors.New("Logic error")
}
return state, summary, nil
}
// Dealing with the case where we see two consecutive +w=123, +w=456
return state, summary, errors.New("two holders of the wakelock?")
}
if value == "" {
// Dealing with the case where we see a +w for the first time
// The entity was already active when the summary was taken,
// so count the active time since the beginning of the summary.
state.WakeLockHolder.Service = "unknown-wakelock-holder"
if state.CurrentTime != summary.StartTimeMs {
return state, summary, errors.New("got w state in the middle of the summary")
}
} else {
serviceUID, ok := idxMap[value]
if !ok {
return state, summary, fmt.Errorf("Wakelock held by unknown service : %q", value)
}
state.WakeLockHolder.Service = serviceUID.Service
}
state.WakeLockHolder.Start = state.CurrentTime
state.WakeLockHeld = tsBool{Start: state.CurrentTime, Value: true}
case "-":
if !state.WakeLockHeld.Value {
// There was no + transition for this
state.WakeLockHolder.Start = summary.StartTimeMs
state.WakeLockHolder.Service = "unknown-wakelock-holder"
}
if summary.Active {
d := summary.WakeLockSummary[state.WakeLockHolder.Service]
duration := time.Duration(state.CurrentTime-state.WakeLockHolder.Start) * time.Millisecond
d.TotalDuration += duration
if duration > d.MaxDuration {
d.MaxDuration = duration
}
d.Num++
summary.WakeLockSummary[state.WakeLockHolder.Service] = d
}
state.WakeLockHeld = tsBool{Start: state.CurrentTime, Value: false}
default:
return state, summary, fmt.Errorf("unknown transition for wakelock : %q", tr)
}
csv.AddEntry("Partial wakelock", &state.WakeLockHolder, state.CurrentTime)
case "g": // gps
return state, summary, state.GpsOn.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.GpsOnSummary, tr, "GPS", csv)
case "s": // sensor
return state, summary, state.SensorOn.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.SensorOnSummary, tr, "Sensor", csv)
case "S": // screen
return state, summary, state.ScreenOn.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.ScreenOnSummary, tr, "Screen", csv)
case "Sb": // brightness
return state, summary, state.Brightness.assign(state.CurrentTime, value, summary.Active, "Brightness", csv)
case "Pcl": // phone_in_call
return state, summary, state.PhoneInCall.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.PhoneCallSummary, tr, "Phone call", csv)
case "Pcn": // data_conn
return state, summary, state.DataConnection.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
summary.DataConnectionSummary, value, "Data connection", csv)
case "Pr": // modile_radio
return state, summary, state.MobileRadioOn.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.MobileRadioOnSummary, tr, "Mobile radio", csv)
case "Psc": // phone_scanning
return state, summary, state.PhoneScanning.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.PhoneScanSummary, tr, "Phone scanning", csv)
case "Pss": // signal_strength
return state, summary, state.SignalStrength.assign(state.CurrentTime, value, summary.Active, "Signal strength", csv)
case "Pst": // phone_state
switch value {
case "in":
case "out":
case "em": // emergency
case "off":
default:
return state, summary, fmt.Errorf("unknown phone state = %q", value)
}
return state, summary, state.PhoneState.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
summary.PhoneStateSummary, value, "Phone state", csv)
case "Enl": // null
return state, summary, errors.New("sample: Null Event line = " + tr + key + value)
case "Epr": // proc
serviceUID, ok := idxMap[value]
if !ok {
return state, summary, fmt.Errorf("unable to find index %q in idxMap for active process", value)
}
return state, summary, serviceUID.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs, state.ActiveProcessMap,
summary.ActiveProcessSummary, tr, value, "Active process", csv)
case "Efg": // fg
serviceUID, ok := idxMap[value]
if !ok {
return state, summary, fmt.Errorf("unable to find index %q in idxMap for foreground process", value)
}
return state, summary, serviceUID.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs, state.ForegroundProcessMap,
summary.ForegroundProcessSummary, tr, value, "Foreground process", csv)
case "Etp": // top
serviceUID, ok := idxMap[value]
if !ok {
return state, summary, fmt.Errorf("unable to find index %q in idxMap for top app", value)
}
return state, summary, serviceUID.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs, state.TopApplicationMap,
summary.TopApplicationSummary, tr, value, "Top app", csv)
case "Esy": // sync
serviceUID, ok := idxMap[value]
if !ok {
return state, summary, fmt.Errorf("unable to find index %q in idxMap sync app", value)
}
_, alreadyActive := state.AppSyncingMap[value]
if tr == "-" {
var start int64
if !alreadyActive {
start = summary.StartTimeMs
} else {
start = state.AppSyncingMap[value].Start
}
if summary.Active {
i := interval{start, state.CurrentTime}
state.syncIntervals = append(state.syncIntervals, i)
}
}
return state, summary, serviceUID.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs, state.AppSyncingMap,
summary.PerAppSyncSummary, tr, value, "SyncManager app", csv)
case "W": // wifi
return state, summary, state.WifiOn.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.WifiOnSummary, tr, "Wifi on", csv)
case "Wl": // wifi_full_lock
return state, summary, state.WifiFullLock.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.WifiFullLockSummary, tr, "Wifi full lock", csv)
case "Ws": // wifi_scan
return state, summary, state.WifiScan.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.WifiScanSummary, tr, "Wifi scan", csv)
case "Wm": // wifi_multicast
return state, summary, state.WifiMulticastOn.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.WifiMulticastOnSummary, tr, "Wifi multicast", csv)
case "Wr": // wifi_running
// Temporary workaround to disambiguate Wr
if len(tr) > 0 {
// WifI Lock
return state, summary, state.WifiRunning.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.WifiRunningSummary, tr, "Wifi running", csv)
}
case "lp", "ps": // Low power mode was renamed to power save mode in M: ag/659258
return state, summary, state.LowPowerModeOn.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.LowPowerModeOnSummary, tr, "Power Save Mode", csv)
case "a": // audio
return state, summary, state.AudioOn.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.AudioOnSummary, tr, "Audio", csv)
case "v": // video
return state, summary, state.VideoOn.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.VideoOnSummary, tr, "Video", csv)
case "Ecn":
suid := idxMap[value]
t, ok := connConstants[suid.UID]
if !ok {
t = "UNKNOWN"
}
activeNtwks := state.ConnectivityMap
ntwkSummary := summary.ConnectivitySummary
_, alreadyActive := activeNtwks[t]
switch suid.Service {
case `"CONNECTED"`:
if alreadyActive {
// Intended behavior, no change to record.
return state, summary, nil
}
suid.Start = state.CurrentTime
activeNtwks[t] = &suid
case `"DISCONNECTED"`:
d := ntwkSummary[t]
if !alreadyActive {
// There was no CONNECT for this, and there hasn't been a prior
// DISCONNECT, so assuming that it was already active at the
// beginning of the summary period (the current ActivitySummary).
// There could be duplicate DISCONNECTs due to b/19114418 and
// b/19269815 so we need to verify that this is the first
// DISCONNECT seen.
if d.Num != 0 {
return state, summary, nil
}
suid.Start = summary.StartTimeMs
activeNtwks[t] = &suid
csv.AddEntry("Network connectivity", &ServiceUID{suid.Start, t, suid.UID}, suid.Start)
}
if summary.Active {
duration := time.Duration(state.CurrentTime-activeNtwks[t].Start) * time.Millisecond
d.TotalDuration += duration
if duration > d.MaxDuration {
d.MaxDuration = duration
}
d.Num++
ntwkSummary[t] = d
}
delete(activeNtwks, t)
default:
fmt.Printf("Unknown Ecn change string: %s\n", suid.Service)
return state, summary, fmt.Errorf("Unknown Ecn change string: %s\n", suid.Service)
}
csv.AddEntry("Network connectivity", &ServiceUID{state.CurrentTime, t, suid.UID}, state.CurrentTime)
case "Ewl": // wakelock_in
if !state.WakeLockInSeen {
// TODO: Verify if WakeLockMap should be overwritten or extended.
// First time seeing wakelock_in, overwrite the current map in case
// wake_lock summaries have been stored.
state.WakeLockMap = make(map[string]*ServiceUID)
state.WakeLockInSeen = true
}
serviceUID, ok := idxMap[value]
if !ok {
return state, summary, fmt.Errorf("unable to find index %q in idxMap for wakelock_in", value)
}
return state, summary, serviceUID.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs, state.WakeLockMap,
summary.WakeLockSummary, tr, value, "wakelock_in", csv)
case "di": // device idle (doze) mode of M
return state, summary, state.IdleModeOn.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs,
&summary.IdleModeOnSummary, tr, "Doze Mode", csv)
case "Ejb": // job: an application executing a scheduled job
serviceUID, ok := idxMap[value]
if !ok {
return state, summary, fmt.Errorf("unable to find index %q in idxMap for job", value)
}
return state, summary, serviceUID.assign(state.CurrentTime,
summary.Active, summary.StartTimeMs, state.ScheduledJobMap,
summary.ScheduledJobSummary, tr, value, "JobScheduler", csv)
// TODO:
case "Epk": // pkg: installed
case "Esm": // motion: significant motion
case "Eac": // active : device active
case "Eur": // User
case "Euf": // UserFg
case "Wsp": // WiFi Supplicant
case "Wss": // WiFi Signal Strength
// Not yet implemented in the framework
case "b": // bluetooth
return state, summary, errors.New("sample: bluetooth line = " + tr + key + value)
default:
fmt.Printf("/ %s / %s / %s /\n", tr, key, value)
return state, summary, errors.New("unknown key " + key)
}
return state, summary, nil
}
func printDebugEvent(b io.Writer, event, line string, state *DeviceState, summary *ActivitySummary) {
fmt.Fprintln(b, "Processed", event, "in "+line,
" state.CurrentTime =", time.Unix(0, state.CurrentTime*int64(time.Millisecond)),
" summary.StartTime=", time.Unix(0, summary.StartTimeMs*int64(time.Millisecond)),
" summary.EndTime=", time.Unix(0, summary.EndTimeMs*int64(time.Millisecond)))
}
// SubexpNames returns a mapping of the sub-expression names to values if the Regexp
// successfully matches the string, otherwise, it returns false.
func SubexpNames(r *regexp.Regexp, s string) (bool, map[string]string) {
if matches := r.FindStringSubmatch(strings.TrimSpace(s)); matches != nil {
names := r.SubexpNames()
result := make(map[string]string)
for i, match := range matches {
result[names[i]] = match
}
return true, result
}
return false, nil
}
func analyzeData(b io.Writer, csv *csv.State, state *DeviceState, summary *ActivitySummary, summaries *[]ActivitySummary,
idxMap map[string]ServiceUID, line string) (*DeviceState, *ActivitySummary, error) {
/*
8,h,60012:START
8,h,0:RESET:TIME:1400165448955
8,h,0:TIME:1398116676025
8,h,15954,+r,+w=37,+Wl,+Ws,Wr=28
*/
// Check for history resets
if matches, result := SubexpNames(ResetRE, line); matches {
ts, exists := result["timeStamp"]
if !exists {
return state, summary, errors.New("Count not extract TIME in line:" + line)
}
parsedInt64, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
return state, summary, errors.New("int parsing error for TIME in line:" + line)
}
// Reset state and summary and start from scratch, History string pool
// is still valid as we just read it
if summary.StartTimeMs > 0 {
state, summary = summarizeActiveState(state, summary, summaries, true, "RESET", csv)
}
summary.StartTimeMs = parsedInt64
summary.EndTimeMs = parsedInt64
// state is reinitialized by summary.SummarizeAndResetState() so
// this should never come before summaryPtr resetting.
state.CurrentTime = parsedInt64
return state, summary, nil
}
if matches, result := SubexpNames(ShutdownRE, line); matches {
// There should be a START statement immediately following this, so it would be
// redundant to save the state here.
timeDelta := result["timeDelta"]
parsedInt64, err := strconv.ParseInt(timeDelta, 10, 64)
if err != nil {
return state, summary, errors.New("int parsing error for timestamp in line:" + line)
}
state.CurrentTime += parsedInt64
summary.EndTimeMs = state.CurrentTime
csv.AddRebootEvent(state.CurrentTime)
return state, summary, nil
}
// Check for reboots, no need to increment the time as TIME statement will follow
// just after START statement
if matches := StartRE.FindStringSubmatch(line); matches != nil {
csv.PrintAllReset(state.CurrentTime)
// If there was no SHUTDOWN event in the bugreport,
// we need to create the reboot entry here.
if !csv.HasRebootEvent() {
csv.AddRebootEvent(state.CurrentTime)
}
// printDebugEvent("START", line, state, summary)
// Reset state and summary and start from scratch, History string pool
// is still valid as we just read it
state, summary = summarizeActiveState(state, summary, summaries, true, "START", csv)
return state, summary, nil
}
// Check for history start time
if matches, result := SubexpNames(TimeRE, line); matches {
parsedInt64, err := strconv.ParseInt(result["timeStamp"], 10, 64)
if err != nil {
return state, summary, errors.New("int parsing error for TIME in line:" + line)
}
// Do not reset the summary start time if we are just parsing the next periodic report.
// This is a random timestamp chosen to filter out timestamps that start at epoch.
cutTime := time.Date(2005, time.August, 17, 12, 0, 0, 0, time.UTC).UnixNano() / int64(time.Millisecond)
if summary.StartTimeMs < cutTime && parsedInt64 > cutTime {
summary.StartTimeMs = parsedInt64
summary.EndTimeMs = parsedInt64
}
state.CurrentTime = parsedInt64
// Prints the reboot event if it exists. We assume a SHUTDOWN event is followed by START, then TIME.
// It is printed here so the end time of the reboot event is the next start time.
csv.PrintRebootEvent(state.CurrentTime)
// printDebugEvent("TIME", line, state, summary)
return state, summary, nil
}
// Check for overflow
if OverflowRE.MatchString(line) {
fmt.Fprintln(b, "Overflow line in "+line)
// History is no longer useful
return state, summary, nil
}
parts := strings.Split(line, ",")
if len(parts) < 3 {
return state, summary, errors.New("unknown format: " + line)
}
// Update current timestamp
timeDelta := parts[2]
parsedInt64, err := strconv.ParseInt(timeDelta, 10, 64)
if err != nil {
return state, summary, errors.New("int parsing error for timestamp in line:" + line)
}
state.CurrentTime += parsedInt64
summary.EndTimeMs = state.CurrentTime
success := true
var errorBuffer bytes.Buffer
if len(parts) >= 4 {
partArr := sanitizeInput(parts[3:])
for _, part := range partArr {
if matches, result := SubexpNames(DataRE, part); matches {
var err error
state, summary, err = updateState(b, csv, state, summary, summaries, idxMap, timeDelta,
result["transition"], result["key"], result["value"])
if err != nil {
success = false
errorBuffer.WriteString("** Error in " + line + " in " + part + " : " + err.Error() + ". ")
}
}
}
if success {
return state, summary, nil
}
return state, summary, errors.New(errorBuffer.String())
} else if len(parts) == 3 {
return state, summary, nil
}
return state, summary, errors.New("Unknown format: " + line)
}
// sanitizeInput converts comma separated parts array of a string with the batteryHistory bug
// of no separator before w=, to an array with correct number of parts from:
// +r,+w=27,Wr=28,+Esy=29,Pss=0w=105w=10,-Esy=30 =>
// +r,+w=27,Wr=28,+Esy=29,Pss=0,w=105,w=10,-Esy=30
func sanitizeInput(inputs []string) []string {
var outputs []string
for _, part := range inputs {
// Sanitize string
if strings.Count(part, "=") > 1 {
if strings.Contains(part, "w=") {
part = strings.Replace(part, "w=", ",w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
}
} else if strings.Contains(part, "Wsw=") {
part = strings.Replace(part, "Wsw=", "Ws,w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
} else if strings.Contains(part, "Ww=") {
part = strings.Replace(part, "Ww=", "W,w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
} else if strings.Contains(part, "Wlw=") {
part = strings.Replace(part, "Wlw=", "Wl,w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
} else if strings.Contains(part, "Wmw=") {
part = strings.Replace(part, "Wmw=", "Wm,w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
} else if strings.Contains(part, "sw=") {
part = strings.Replace(part, "sw=", "s,w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
} else if strings.Contains(part, "Sw=") {
part = strings.Replace(part, "Sw=", "S,w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
} else if strings.Contains(part, "rw=") {
part = strings.Replace(part, "rw=", "r,w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
} else if strings.Contains(part, "Prw=") {
part = strings.Replace(part, "Prw=", "Pr,w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
} else if strings.Contains(part, "Pclw=") {
part = strings.Replace(part, "Pclw=", "Pcl,w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
} else if strings.Contains(part, "BPw=") {
part = strings.Replace(part, "BPw=", "BP,w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
} else if strings.Contains(part, "gw=") {
part = strings.Replace(part, "gw=", "g,w=", -1)
outputs = append(outputs, strings.Split(part, ",")...)
continue
} else {
outputs = append(outputs, part)
}
}
return outputs
}
// ScrubPII scrubs any part of the string that looks like an email address (@<blah>.com)
// From:
// com.google.android.apps.plus.content.EsProvider/com.google/<EMAIL>.doe@<EMAIL>/extra
// To:
// com.google.android.apps.plus.content.EsProvider/com.google/XXX@gmail.com/extra
func ScrubPII(input string) string {
output := ""
matches := PIIRE.FindStringSubmatch(input)
if matches == nil {
return input
}
names := PIIRE.SubexpNames()
for i, match := range matches {
if names[i] == "account" {
output += "XXX"
} else if i != 0 {
output += match
}
}
return output
}
// analyzeHistoryLine takes a battery history event string and updates the device state.
func analyzeHistoryLine(b io.Writer, csvState *csv.State, state *DeviceState, summary *ActivitySummary,
summaries *[]ActivitySummary, idxMap map[string]ServiceUID, line string, scrubPII bool) (*DeviceState, *ActivitySummary, error) {
if match, result := SubexpNames(GenericHistoryStringPoolLineRE, line); match {
index := result["index"]
service := result["service"]
if scrubPII {
service = ScrubPII(service)
}
idxMap[index] = ServiceUID{
Service: service,
UID: result["uid"],
}
return state, summary, nil
} else if GenericHistoryLineRE.MatchString(line) {
return analyzeData(b, csvState, state, summary, summaries, idxMap, line)
} else if matched, _ := regexp.MatchString("^NEXT: (\\d+)", line); matched {
// Check for NEXT
for k := range idxMap {
delete(idxMap, k)
}
return state, summary, nil
} else if matched, _ := regexp.MatchString("^7,h", line); matched {
// Ignore old history versions
return state, summary, nil
} else if !VersionLineRE.MatchString(line) {
return state, summary, errors.New("unknown line format: " + line)
}
return state, summary, nil
}
// AnalysisReport contains fields that are created as a result of analyzing and parsing a history.
type AnalysisReport struct {
Summaries []ActivitySummary
TimestampsAltered bool
OutputBuffer bytes.Buffer
IdxMap map[string]ServiceUID
Errs []error
}
// AnalyzeHistory takes as input a complete history log and desired summary format.
// It then analyzes the log line by line (delimited by newline characters).
// No summaries (before an OVERFLOW line) are excluded/filtered out.
func AnalyzeHistory(history, format string, csvWriter io.Writer, scrubPII bool) *AnalysisReport {
// 8,hsp,0,10073,"com.google.android.volta"
// 8,hsp,28,0,"200:qcom,smd-rpm:203:fc4281d0.qcom,mpm:222:fc4cf000.qcom,spmi"
h, c, err := fixTimeline(history)
var errs []error
if err != nil {
errs = append(errs, err)
}
deviceState := newDeviceState()
summary := newActivitySummary(format)
summaries := []ActivitySummary{}
idxMap := make(map[string]ServiceUID)
if format != FormatTotalTime {
csvWriter = ioutil.Discard
}
csvState := csv.NewState(csvWriter)
var b bytes.Buffer
for _, line := range h {
if OverflowRE.MatchString(line) {
// Stop summary as soon as you OVERFLOW
break
}
deviceState, summary, err = analyzeHistoryLine(&b, csvState, deviceState, summary, &summaries, idxMap, line, scrubPII)
if err != nil && len(line) > 0 {
errs = append(errs, err)
}
}
csvState.PrintAllReset(deviceState.CurrentTime)
csvState.PrintRebootEvent(deviceState.CurrentTime)
if summary.Active {
deviceState, summary = summarizeActiveState(deviceState, summary, &summaries, true, "END", csvState)
}
return &AnalysisReport{
Summaries: summaries,
TimestampsAltered: c,
OutputBuffer: b,
IdxMap: idxMap,
Errs: errs,
}
}
// fixTimeline processes the given history, tries to fix the time statements in the
// history so that there is a consistent timeline, filters out lines that are not a
// part of the history log, and returns a slice of the fixed history, split by new
// lines, along with a boolean to indicate if the original history timestamps were
// modified. The function operates with the assumption that the last time statement
// in a history (between reboots) is the most accurate. This function should be
// called before analyzing the history.
func fixTimeline(h string) ([]string, bool, error) {
var s []string
// Filter out non-history log lines.
for _, l := range strings.Split(h, "\n") {
l = strings.TrimSpace(l)
if GenericHistoryLineRE.MatchString(l) || GenericHistoryStringPoolLineRE.MatchString(l) || VersionLineRE.MatchString(l) {
s = append(s, l)
}
}
changed := false
var time int64 // time will be defined at the beginning of the current line --> the time before the delta has been added
timeFound := false
var result map[string]string
for i := len(s) - 1; i >= 0; i-- {
line := s[i]
if timeFound {
if StartRE.MatchString(line) || ShutdownRE.MatchString(line) || OverflowRE.MatchString(line) {
// Seeing a START or SHUTDOWN means that the time we were using won't be valid for earlier statements
// so go back to looking for a new TIME statement to use.
timeFound = false
continue
}
// For both 9,h,4051:TIME:1426513282239 and 9,h,0:RESET:TIME:1420714559370
if sep := strings.Split(line, ":TIME:"); len(sep) == 2 {
if time < 0 {
return nil, false, errors.New("negative time calculated")
}
// Replace the time reported in the history log with the calculated time.
s[i] = fmt.Sprintf("%s:TIME:%d", sep[0], time)
changed = true
}
if match, result := SubexpNames(GenericHistoryLineRE, line); match {
d, err := strconv.ParseInt(result["timeDelta"], 10, 64)
if err != nil {
return nil, changed, err
}
time -= d
}
} else {
if timeFound, result = SubexpNames(TimeRE, line); !timeFound {
timeFound, result = SubexpNames(ResetRE, line)
}
if timeFound {
t, err := strconv.ParseInt(result["timeStamp"], 10, 64)
if err != nil {
return nil, changed, err
}
d, err := strconv.ParseInt(result["timeDelta"], 10, 64)
if err != nil {
return nil, changed, err
}
time = t - d
}
}
}
return s, changed, nil
}
// UIDToPackageNameMapping builds a mapping of UIDs to package names.
// For shared UIDs, package names will be combined and delineated by ';'
func UIDToPackageNameMapping(checkin string) (map[int32]string, []error) {
m := make(map[int32]string)
var errs []error
for _, l := range strings.Split(checkin, "\n") {
if match, result := SubexpNames(CheckinApkLineRE, l); match {
u, err := strconv.ParseInt(result["uid"], 10, 32)
if err != nil {
errs = append(errs, fmt.Errorf("invalid UID in checkin 'apk' line: %q", err))
continue
}
uid := int32(u)
apk := result["pkgName"]
if n, ok := m[uid]; ok {
m[uid] = fmt.Sprintf("%s;%s", n, apk)
} else {
m[uid] = apk
}
}
}
return m, errs
}
<file_sep>/**
*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('historian.Historian');
goog.require('historian.Bars');
goog.require('historian.Context');
goog.require('historian.LevelLine');
goog.require('historian.util');
/**
* A single data point for a serie.
*
* @typedef {{
* start_time: number,
* end_time: number,
* value: (string | number)
* }}
*/
historian.Entry;
/**
* A single data point for a aggregated serie.
*
* @typedef {{
* start_time: number,
* end_time: number,
* value: (string | number),
* services: !Array<string>
* }}
*/
historian.AggregatedEntry;
/**
* The data for a single serie.
*
* @typedef {{
* name: string,
* type: string,
* values: Array<(!historian.Entry|!historian.AggregatedEntry)>,
* index: number,
* color: (function(string): string | undefined)
* }}
*/
historian.SerieData;
/**
* The clustered data for a single serie.
*
* @typedef {{
* name: string,
* type: string,
* values: Array<(!historian.util.ClusterEntry)>,
* index: number,
* color: (function(string): string | undefined)
* }}
*/
historian.ClusteredSerieData;
/**
* The data for all the series.
*
* @typedef {!Array<!historian.SerieData>}
*/
historian.SeriesData;
/**
* The object for the level line, bar data, graph extent and service mappings.
*
* @typedef {{
* barData: !historian.SeriesData,
* levelData: !historian.SerieData,
* extent: !Array<number>,
* serviceMapper: !historian.util.ServiceMapper
* }}
*/
historian.AllData;
/**
* Creates the historian graph from the csv data.
* @export
*/
historian.render = function() {
var historianCsv = d3.select('#csv-data')
.text();
var data = historian.util.readCsv( /** @type {string} */ (historianCsv));
var context = new historian.Context(data.extent, data.barData.length);
var bars = new historian.Bars(context, data.barData, data.serviceMapper);
var levelLine = new historian.LevelLine(context, data.levelData);
};
<file_sep>/**
*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('historian.utilTest');
goog.setTestOnly('historian.utilTest');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.jsunit');
goog.require('historian.util');
var mockControl;
var mockInNonBlankEntry;
var propertyReplacer = new goog.testing.PropertyReplacer();
var _ = goog.testing.mockmatchers.ignoreArgument;
function setUp() {
mockControl = new goog.testing.MockControl();
mockIsNonBlankEntry =
mockControl.createMethodMock(historian.util, 'isNonBlankEntry_');
}
function tearDown() {
mockControl.$resetAll();
mockControl.$tearDown();
}
function createTestEntry(arr) {
return {start_time: arr[0], end_time: arr[1], value: arr[2]};
}
function createTestSeries(values) {
var processedValues = [];
values.forEach(function(v) {
processedValues.push(createTestEntry(v));
});
return {
name: 'test',
values: processedValues,
type: 'service',
index: '0'
};
}
function createExpectedSeries(values) {
var processedValues = [];
values.forEach(function(v) {
var entry = createTestEntry(v);
entry['services'] = v[3];
processedValues.push(entry);
});
return processedValues;
}
function testAggregateData() {
var tests = [
// Single interval.
[
[0, 100, 'service1']
],
// Same interval.
[
[0, 100, 'service1'],
[0, 100, 'service2']
],
// Non overlapping intervals.
[
[0, 100, 'service1'],
[110, 200, 'service2']
],
// End time equals start time of next interval.
[
[0, 100, 'service1'],
[100, 200, 'service2']
],
// Overlapping interval, same start time, earlier end time.
[
[0, 100, 'service1'],
[0, 50, 'service2']
],
// Overlapping interval, same start time, later end time.
[
[0, 100, 'service1'],
[0, 150, 'service2']
],
// Overlapping interval, later start time, earlier end time.
[
[0, 100, 'service1'],
[25, 50, 'service2']
],
// Overlapping interval, later start time, same end time.
[
[0, 100, 'service1'],
[25, 100, 'service2']
],
// Overlapping interval, later start time, later end time.
[
[0, 100, 'service1'],
[25, 150, 'service2']
],
// Nested intervals.
[
[0, 100, 'service1'],
[20, 80, 'service2'],
[40, 60, 'service3']
],
// Out of order intervals.
[
[200, 300, 'service1'],
[100, 400, 'service2'],
[150, 500, 'service3']
]
];
var expected = [
[
[0, 100, 1, ['service1']]
],
[
[0, 100, 2, ['service1', 'service2']]
],
[
[0, 100, 1, ['service1']],
[110, 200, 1, ['service2']]
],
[
[0, 100, 1, ['service1']],
[100, 200, 1, ['service2']]
],
[
[0, 50, 2, ['service1', 'service2']],
[50, 100, 1, ['service1']]
],
[
[0, 100, 2, ['service1', 'service2']],
[100, 150, 1, ['service2']]
],
[
[0, 25, 1, ['service1']],
[25, 50, 2, ['service1', 'service2']],
[50, 100, 1, ['service1']]
],
[
[0, 25, 1, ['service1']],
[25, 100, 2, ['service1', 'service2']]
],
[
[0, 25, 1, ['service1']],
[25, 100, 2, ['service1', 'service2']],
[100, 150, 1, ['service2']]
],
[
[0, 20, 1, ['service1']],
[20, 40, 2, ['service1', 'service2']],
[40, 60, 3, ['service1', 'service2', 'service3']],
[60, 80, 2, ['service1', 'service2']],
[80, 100, 1, ['service1']]
],
[
[100, 150, 1, ['service2']],
[150, 200, 2, ['service2', 'service3']],
[200, 300, 3, ['service1', 'service2', 'service3']],
[300, 400, 2, ['service2', 'service3']],
[400, 500, 1, ['service3']]
]
];
var i = 0;
tests.forEach(function(t) {
var output = historian.util.aggregateData_(createTestSeries(t));
var expectedSeries = createExpectedSeries(expected[i]);
var expectedValues = expectedSeries.sort(compareEntries);
var same = (output.values.length === expectedValues.length) &&
output.values.every(function(element, index) {
return compareServices(element, expectedValues[index]);
});
if (!same) {
console.log('Test ' + i + ' failed. Output was: ');
console.log(output.values);
console.log('Expected ');
console.log(expectedValues);
}
i++;
});
}
function compareServices(e1, e2) {
if (e1.services.length !== e2.services.length) {
return false;
}
e1.services.sort();
e2.services.sort();
for (var i = 0; i < e1.services.length; i++) {
if (e1.services[i] !== e2.services[i]) {
return false;
}
}
return (e1.start_time === e2.start_time &&
e1.end_time === e2.end_time &&
e1.value === e2.value);
}
function createExpectedClusteredValue(value, count, duration) {
return {
'value': value,
'count': count,
'duration': duration
};
}
function createExpectedClusteredValues(values) {
var clustered = {};
values.forEach(function(c) {
clustered[c[2]] = {
'count': c[0],
'duration': c[1]
};
});
return clustered;
}
function verifyCluster(expectedEntry, clusteredEntry) {
assertEquals(expectedEntry.start_time, clusteredEntry.start_time);
assertEquals(expectedEntry.end_time, clusteredEntry.end_time);
assertEquals(expectedEntry.clustered_count, clusteredEntry.clustered_count);
assertEquals(expectedEntry.active_duration, clusteredEntry.active_duration);
assertObjectEquals(
expectedEntry.clustered_values, clusteredEntry.clustered_values);
}
function testSimpleCluster() {
var values = [
[0, 100, 'service1'],
[110, 200, 'service2'],
[3000, 10000, 'service2'],
[20000, 30000, 'service2'],
[30100, 30200, 'service3'],
[101000, 102000, 'service1']
];
var expected = [
{
'start_time': 0,
'end_time': 10000,
'clustered_count': 3,
'active_duration': 7190,
'clustered_values': createExpectedClusteredValues([
[1, 100, 'service1'],
[2, 7090, 'service2']
])
},
// New cluster as entry and previous cluster duration is greater
// than minDuration
{
'start_time': 20000,
'end_time': 30200,
'clustered_count': 2,
'active_duration': 10100,
'clustered_values': createExpectedClusteredValues([
[1, 10000, 'service2'],
[1, 100, 'service3'],
])
},
{
'start_time': 101000,
'end_time': 102000,
'clustered_count': 1,
'active_duration': 1000,
'clustered_values': createExpectedClusteredValues([
[1, 1000, 'service1'],
])
}
];
var series = [
createTestSeries(values)
];
mockIsNonBlankEntry(_, _).$returns(true).$times(values.length);
mockControl.$replayAll();
var clustered = historian.util.cluster(series, 6000);
assertEquals(1, clustered.length);
var clusteredSerie = clustered[0];
assertEquals(expected.length, clusteredSerie.values.length);
for (var i = 0; i < expected.length; i++) {
verifyCluster(clusteredSerie.values[i], expected[i]);
}
mockControl.$verifyAll();
}
<file_sep>Battery Historian 2.0
=====================
Battery Historian is a tool to inspect battery related information and events on an Android device (Android 5.0 Lollipop and later: API Level 21+) while the device was on battery. It allows application developers to visualize system and application level events on a timeline and easily see various aggregated statistics since the device was last fully charged.
Introduction
------------
Battery Historian 2.0 is a complete rewrite in Go and uses some JavaScript visualization libraries to display battery related events on a timeline with panning and zooming functionality. In addition, v2.0 allows developers to pick an application and inspect the metrics that impact battery specific to the chosen application.
Getting Started
---------------
If you are new to the Go programming language:
* Follow the instructions available at <http://golang.org/doc/install> for downloading and installing the Go compilers, tools, and libraries.
* Create a workspace directory according to the instructions at
<http://golang.org/doc/code.html#Organization> and ensure that `GOPATH` and
`GOBIN` environment variables are appropriately set and added to your `$PATH`
environment variable. `$GOBIN should be set to $GOPATH/bin`.
Next, install Go support for Protocol Buffers by running go get.
```
# Grab the code from the repository and install the proto package.
$ go get -u github.com/golang/protobuf/proto
$ go get -u github.com/golang/protobuf/protoc-gen-go
```
The compiler plugin, protoc-gen-go, will be installed in $GOBIN, which must be
in your $PATH for the protocol compiler, protoc, to find it.
Next, download the Battery Historian 2.0 code:
```
# Download Battery Historian 2.0
$ go get -u github.com/google/battery-historian/...
$ cd $GOPATH/src/github.com/google/battery-historian
# Compile Javascript files using the Closure compiler
$ bash setup.sh
# Run Historian on your machine (make sure $PATH contains $GOBIN)
$ go run cmd/battery-historian/battery-historian.go [--port <default:9999>]
```
Remember, you must always run battery-historian from inside the `$GOPATH/src/github.com/google/battery-historian` directory:
```
cd $GOPATH/src/github.com/google/battery-historian
go run cmd/battery-historian/battery-historian.go [--port <default:9999>]
```
#### How to take a bug report
To take a bug report from your Android device, you will need to enable USB debugging under `Settings > System > Developer Options`. On Android 4.2 and higher, the Developer options screen is hidden by default. You can enable this by following the instructions [here](<http://developer.android.com/tools/help/adb.html#Enabling>).
Next, to obtain a bug report from your development device
```
$ adb bugreport > bugreport.txt
```
### Start analyzing!
You are all set now. Run `historian` and visit <http://localhost:9999> and upload the `bugreport.txt` file to start analyzing.
By default, Android does not record timestamps for application-specific
userspace wakelock transitions even though aggregate statistics are maintained
on a running basis. If you want Historian to display detailed information about
each individual wakelock on the timeline, you should enable full wakelock reporting using the following command before starting your experiment:
```
adb shell dumpsys batterystats --enable full-wake-history
```
Note that by enabling full wakelock reporting the battery history log overflows
in a few hours. Use this option for short test runs (3-4 hrs).
To reset aggregated battery stats and timeline at the beginning of a measurement:
```
adb shell dumpsys batterystats --reset
```
Screenshots
-----------



Advanced
--------
The following information is for advanced users only who are interested in modifying the code.
##### Modifying the proto files
If you modify the proto files (pb/\*/\*.proto), you will need to regenerate the compiled Go output files using `regen_proto.sh`.
##### Other command line tools
```
# System stats
$ go run exec/local_checkin_parse.go --input=bugreport.txt
# Timeline analysis
$ go run exec/local_history_parse.go --summary=totalTime --input=bugreport.txt
```
Support
-------
- G+ Community (Discussion Thread: Battery Historian): https://plus.google.com/b/108967384991768947849/communities/114791428968349268860
If you've found an error in this sample, please file an issue:
<https://github.com/google/battery-historian/issues>
License
-------
Copyright 2016 Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
<http://www.apache.org/licenses/LICENSE-2.0>
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
<file_sep>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Historian v2 analyzes bugreports and outputs battery analysis results.
package main
import (
"flag"
"fmt"
"log"
"net/http"
"github.com/google/battery-historian/analyzer"
)
var (
optimized = flag.Bool("optimized", true, "Whether to output optimized js files. Disable for local debugging.")
port = flag.Int("port", 9999, "service port")
)
type analysisServer struct{}
func (*analysisServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Printf("Starting processing for: %s", r.Method)
analyzer.UploadHandler(w, r)
}
func initFrontend() {
http.HandleFunc("/", analyzer.UploadHandler)
http.Handle("/static/", http.FileServer(http.Dir(".")))
http.Handle("/compiled/", http.FileServer(http.Dir(".")))
if *optimized == false {
http.Handle("/third_party/", http.FileServer(http.Dir(".")))
http.Handle("/js/", http.FileServer(http.Dir(".")))
}
}
func main() {
flag.Parse()
initFrontend()
analyzer.InitTemplates()
analyzer.SetIsOptimized(*optimized)
log.Println("Listening on port: ", *port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
}
<file_sep>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/google/battery-historian/parseutils"
)
var (
summaryFormat = flag.String("summary", parseutils.FormatBatteryLevel, "1. batteryLevel 2. totalTime")
historyFile = flag.String("history", "", "Battery history file generated by `adb shell dumpsys batterystats -c --history-start <start>`")
csvFile = flag.String("csv", "", "Output filename to write csv timeseries data to.")
scrubPII = flag.Bool("scrub", true, "Whether ScrubPII is applied to addresses.")
)
func usage() {
fmt.Println("Incorrect summary argument. Format: --summary=[batteryLevel|totalTime] --history=<log-file> [--csv=<csv-output-file>]")
os.Exit(1)
}
func checkFlags() {
switch *summaryFormat {
case parseutils.FormatBatteryLevel:
case parseutils.FormatTotalTime:
default:
fmt.Println("1")
usage()
}
if *historyFile == "" {
fmt.Println("2")
usage()
}
}
func main() {
flag.Parse()
checkFlags()
// read the whole file
history, err := ioutil.ReadFile(*historyFile)
if err != nil {
log.Fatal(err)
}
writer := ioutil.Discard
if *csvFile != "" && *summaryFormat == parseutils.FormatTotalTime {
f, err := os.Create(*csvFile)
if err != nil {
log.Fatal(err)
}
defer f.Close()
csvWriter := bufio.NewWriter(f)
defer csvWriter.Flush()
writer = csvWriter
}
rep := parseutils.AnalyzeHistory(string(history), *summaryFormat, writer, *scrubPII)
// Exclude summaries with no change in battery level
var a []parseutils.ActivitySummary
for _, s := range rep.Summaries {
if s.InitialBatteryLevel != s.FinalBatteryLevel {
a = append(a, s)
}
}
if rep.TimestampsAltered {
fmt.Println("Some timestamps were changed while processing the log.")
}
if len(rep.Errs) > 0 {
fmt.Println("Errors encountered:")
for _, err := range rep.Errs {
fmt.Println(err.Error())
}
}
fmt.Println("\nNumber of summaries ", len(a), "\n")
for _, s := range a {
s.Print(&rep.OutputBuffer)
}
fmt.Println(rep.OutputBuffer.String())
}
<file_sep>/**
*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Utilities to display app specific metrics.
*/
/**
* Adds a new row to bdy, putting each element in data into a
* separate column. The objects must have a 'name' field, and can have an
* optional 'title' field that will be used as the title for the cell.
*
* @param {Node} bdy the tbody (or thead) to add a row to
* @param {Array<{name: string, title: string}>} data the data to put
* into each cell
*/
historian.addRowWithDesc = function(bdy, data) {
var tr = bdy.insertRow();
for (var i = 0; i < data.length; i++) {
var td = tr.insertCell();
if (d = data[i]) {
td.appendChild(document.createTextNode(d.name));
if (d.title) {
td.setAttribute('title', d.title);
}
}
}
};
/**
* Adds a new row to bdy, putting each element in data into a
* separate column. If title is set, then it will be used as the title
* (tooltip) for the row.
*
* @param {Node} bdy the tbody (or thead) to add a row to
* @param {Array<string>} data the data to put into each cell
* @param {string} title a description of the row contents
*/
historian.addRow = function(bdy, data, title) {
var tr = bdy.insertRow();
if (title) {
tr.setAttribute('title', title);
}
for (var i = 0; i < data.length; i++) {
var td = tr.insertCell();
if (data[i]) {
td.appendChild(document.createTextNode(data[i]));
}
}
};
/**
* Displays or hides the section detailing the child field in the app proto.
*
* @param {string} appName the saved app proto name
* @param {Array<Object>} children the list of child elements
*/
historian.displayAppChild = function(appName, children) {
// Display this section only if there are multiple children or
// if the single child is under one of our predefined shared UID
// groupings (ie. com.google.android.gms under GOOGLE_SERVICES).
if (children && (children.length > 1 ||
(children.length == 1 && children[0].name != appName))) {
var div = document.createElement('div');
document.getElementById('appChildSection').style.display = 'block';
// Pre-sort in alphabetical order
children.sort(function(a, b) {return a.name.localeCompare(b.name)});
var table = document.createElement('table');
table.setAttribute('class', 'tablesorter');
var thead = document.createElement('thead');
historian.addRow(thead, ['Package Name', 'Version Code', 'Version Name']);
table.appendChild(thead);
var tbody = document.createElement('tbody');
for (var i = 0; i < children.length; i++) {
var child = children[i];
historian.addRow(tbody,
[child.name, child.version_code, child.version_name]);
}
table.appendChild(tbody);
div.appendChild(table);
document.getElementById('appChild').innerHTML = div.innerHTML;
// The tablesorter function will only work on elements that have
// been added to the HTML, and even then, using 'table' would not work here.
historian.activateTablesorter($('#appChild table'), [], false);
} else {
document.getElementById('appChildSection').style.display = 'none';
}
};
/**
* Displays or hides the section detailing the Apk field in the app proto.
*
* @param {Object} apk the apk field of the app proto
*/
historian.displayAppApk = function(apk) {
if (apk) {
var div = document.createElement('div');
document.getElementById('appApkSection').style.display = 'block';
document.getElementById('appWakeups').innerHTML = apk.wakeups;
if (apk.service && apk.service.length > 0) {
// Pre-sort services by descreasing number of launches and starts.
apk.service.sort(function(a, b) {
if (a.launches === b.launches) {
return b.starts - a.starts;
}
return b.launches - a.launches;
});
var table = document.createElement('table');
table.setAttribute('class', 'tablesorter');
var thead = document.createElement('thead');
historian.addRowWithDesc(thead, [
{name: 'Service Name'},
{name: 'Time started'},
{
name: '# starts',
title: 'Total number of times startService() was called',
},
{
name: '# launches',
title: 'Total number of times the service was launched',
}
]);
table.appendChild(thead);
var tbody = document.createElement('tbody');
for (var i = 0; i < apk.service.length; i++) {
var service = apk.service[i];
historian.addRow(tbody, [
service.name,
historian.time.getTime(service.start_time_msec),
service.starts,
service.launches
]);
}
table.appendChild(tbody);
div.appendChild(table);
}
document.getElementById('appServices').innerHTML = div.innerHTML;
historian.activateTablesorter($('#appServices table'), [], false);
} else {
document.getElementById('appApkSection').style.display = 'none';
}
};
/**
* Displays or hides the section detailing the app's network activity.
*
* @param {Object} network the Network field of the app proto
* @param {Object} wifi the Wifi field of the app proto
*/
historian.displayAppNetworkInfo = function(network, wifi) {
if (network || wifi) {
document.getElementById('appNetworkInfoSection').style.display = 'block';
var div = document.createElement('div');
var table = document.createElement('table');
// Don't want to enable sorting for the table, but it needs the blue
// classification in order to look like the rest of the tables.
table.setAttribute('class', 'tablesorter-blue');
var tbody = document.createElement('tbody');
if (network) {
var mobileRxKB = network.mobile_bytes_rx / 1024;
var mobileTxKB = network.mobile_bytes_tx / 1024;
historian.addRow(tbody, [
'Mobile KB transferred',
historian.formatString('%s total (%s received, %s transmitted)',
(mobileRxKB + mobileTxKB).toFixed(2), mobileRxKB.toFixed(2),
mobileTxKB.toFixed(2))
]);
var wifiRxKB = network.wifi_bytes_rx / 1024;
var wifiTxKB = network.wifi_bytes_tx / 1024;
historian.addRow(tbody, [
'Wifi KB transferred',
historian.formatString('%s total (%s received, %s transmitted)',
(wifiRxKB + wifiTxKB).toFixed(2), wifiRxKB.toFixed(2),
wifiTxKB.toFixed(2))
]);
historian.addRow(tbody, [
'Mobile packets transferred',
historian.formatString('%s total (%s received, %s transmitted)',
network.mobile_packets_rx + network.mobile_packets_tx,
network.mobile_packets_rx, network.mobile_packets_tx)
]);
historian.addRow(tbody, [
'Wifi packets transferred',
historian.formatString('%s total (%s received, %s transmitted)',
network.wifi_packets_rx + network.wifi_packets_tx,
network.wifi_packets_rx, network.wifi_packets_tx)
]);
historian.addRow(tbody, [
'Mobile active time',
historian.time.formatDuration(network.mobile_active_time_msec)
],
'Amount of time the app kept the mobile radio active');
historian.addRow(tbody,
['Mobile active count', network.mobile_active_count]);
}
if (wifi) {
historian.addRow(tbody, [
'Full wifi lock time',
historian.time.formatDuration(wifi.full_wifi_lock_time_msec)
]);
if (reportVersion >= 12) {
// This was added during the time when the report version was 12 and
// the BatteryStatsImpl version was 119 (ag/650841), but some version
// reports won't have this info.
// TODO(kwekua): modify our parsing to use BatteryStatsImpl so that
// we can be smarter about showing this value.
historian.addRow(tbody, ['Wifi scan time', wifi.scan_count]);
}
historian.addRow(tbody, [
'Wifi scan count',
historian.time.formatDuration(wifi.scan_time_msec)
]);
if (reportVersion >= 14) {
historian.addRow(tbody, [
'Wifi idle time',
historian.time.formatDuration(wifi.idle_time_msec)
]);
historian.addRow(tbody, [
'Wifi transfer time',
historian.formatString('%s total (%s receiving, %s transmitting)',
historian.time.formatDuration(wifi.rx_time_msec +
wifi.tx_time_msec),
historian.time.formatDuration(wifi.rx_time_msec),
historian.time.formatDuration(wifi.tx_time_msec))
]);
}
}
table.appendChild(tbody);
div.appendChild(table);
document.getElementById('appNetworkInfo').innerHTML = div.innerHTML;
} else {
document.getElementById('appNetworkInfoSection').style.display = 'none';
}
};
/**
* Displays or hides the section detailing the app's processes.
*
* @param {Array<Object>} processes the list of processes in the app proto
*/
historian.displayAppProcess = function(processes) {
if (processes && processes.length > 0) {
document.getElementById('appProcessSection').style.display = 'block';
// Pre-sort in decreasing order of user time, system time, and starts.
processes.sort(function(a, b) {
if (a.user_time_msec === b.user_time_msec) {
if (a.system_time_msec === b.system_time_msec) {
return b.starts - a.starts;
}
return b.system_time_msec - a.system_time_msec;
}
return b.user_time_msec - a.user_time_msec;
});
var div = document.createElement('div');
var table = document.createElement('table');
table.setAttribute('class', 'tablesorter');
var thead = document.createElement('thead');
historian.addRowWithDesc(thead, [
{name: 'Process Name'},
{
name: 'User Time',
title: 'Total time spent executing in user code',
},
{
name: 'System Time',
title: 'Total time spent executing in system code',
},
{
name: 'Foreground Time',
title: 'CPU time spent while the process was in the foreground',
},
{
name: '# Starts',
title: '# times the process has been started',
},
{name: '# ANRs'},
{name: '# Crashes'}
]);
table.appendChild(thead);
var tbody = document.createElement('tbody');
for (var i = 0; i < processes.length; i++) {
var process = processes[i];
historian.addRow(tbody, [
process.name,
historian.time.formatDuration(process.user_time_msec),
historian.time.formatDuration(process.system_time_msec),
historian.time.formatDuration(process.foreground_time_msec),
process.starts,
process.anrs,
process.crashes
]);
}
table.appendChild(tbody);
div.appendChild(table);
document.getElementById('appProcess').innerHTML = div.innerHTML;
// Apply tablesort 'duration' parser to User Time, System Time,
// and Foreground Time columns.
historian.activateTablesorter($('#appProcess table'), [1, 2, 3], false);
} else {
document.getElementById('appProcessSection').style.display = 'none';
}
};
/**
* Displays or hides the section detailing scheduled jobs used by the app.
*
* @param {Array<Object>} scheduledJobs the list of scheduled jobs in the
* app proto
*/
historian.displayAppScheduledJob = function(scheduledJobs) {
if (scheduledJobs && scheduledJobs.length > 0) {
document.getElementById('appScheduledJobSection').style.display = 'block';
// Pre-sort by decreasing total time and count.
scheduledJobs.sort(function(a, b) {
if (a.total_time_msec === b.total_time_msec) {
return b.count - a.count;
}
return b.total_time_msec;
});
var div = document.createElement('div');
var table = document.createElement('table');
table.setAttribute('class', 'tablesorter');
var thead = document.createElement('thead');
historian.addRow(thead, ['Job Name', 'Total Time', 'Count']);
table.appendChild(thead);
var tbody = document.createElement('tbody');
for (var i = 0; i < scheduledJobs.length; i++) {
var j = scheduledJobs[i];
historian.addRow(
tbody,
[j.name, historian.time.formatDuration(j.total_time_msec), j.count]);
}
table.appendChild(tbody);
div.appendChild(table);
document.getElementById('appScheduledJob').innerHTML = div.innerHTML;
// Apply tablesort 'duration' parser to Total Time column.
historian.activateTablesorter($('#appScheduledJob table'), [1], false);
} else {
document.getElementById('appScheduledJobSection').style.display = 'none';
}
};
/**
* Displays or hides the section detailing the app's sensor activity.
*
* @param {Array<Object>} sensors the list of sensor info in the app proto
*/
historian.displayAppSensor = function(sensors) {
if (sensors && sensors.length > 0) {
document.getElementById('appSensorSection').style.display = 'block';
// Pre-sort in decreasing order of total time and count.
sensors.sort(function(a, b) {
if (a.total_time_msec === b.total_time_msec) {
return b.count - a.count;
}
return b.total_time_msec - a.total_time_msec;
});
var div = document.createElement('div');
var table = document.createElement('table');
table.setAttribute('class', 'tablesorter');
var thead = document.createElement('thead');
historian.addRow(thead, ['Sensor Number', 'Total Time', 'Count']);
table.appendChild(thead);
var tbody = document.createElement('tbody');
for (var i = 0; i < sensors.length; i++) {
var s = sensors[i];
historian.addRow(tbody, [
s.number,
historian.time.formatDuration(s.total_time_msec),
s.count
]);
}
table.appendChild(tbody);
div.appendChild(table);
document.getElementById('appSensor').innerHTML = div.innerHTML;
// Apply tablesort 'duration' parser to Total Time column.
historian.activateTablesorter($('#appSensor table'), [1], false);
} else {
document.getElementById('appSensorSection').style.display = 'none';
}
};
/**
* Displays or hides the section detailing all of the app's sync activity.
*
* @param {Array<Object>} syncs the list of sync info in the app proto
*/
historian.displayAppSync = function(syncs) {
if (syncs && syncs.length > 0) {
document.getElementById('appSyncSection').style.display = 'block';
// Pre-sort in decreasing order of total time and count.
syncs.sort(function(a, b) {
if (a.total_time_msec === b.total_time_msec) {
return b.count - a.count;
}
return b.total_time_msec - a.total_time_msec;
});
var div = document.createElement('div');
var table = document.createElement('table');
table.setAttribute('class', 'tablesorter');
var thead = document.createElement('thead');
historian.addRow(thead, ['Sync Name', 'Total Time', 'Count']);
table.appendChild(thead);
var tbody = document.createElement('tbody');
for (var i = 0; i < syncs.length; i++) {
var s = syncs[i];
historian.addRow(
tbody,
[s.name, historian.time.formatDuration(s.total_time_msec), s.count]);
}
table.appendChild(tbody);
div.appendChild(table);
document.getElementById('appSync').innerHTML = div.innerHTML;
// Apply tablesort 'duration' parser to Total Time column.
// The tablesorter function will only work on elements that have
// been added to the HTML, and even then, using 'table' would not work here.
historian.activateTablesorter($('#appSync table'), [1], false);
} else {
document.getElementById('appSyncSection').style.display = 'none';
}
};
/**
* Mapping of UserActivity enum value to name.
* @const
*/
historian.userActivityName = ['OTHER', 'BUTTON', 'TOUCH'];
/**
* Displays or hides the section detailing user interaction with the app.
*
* @param {Array<Object>} ua the list of UserActivity info in the app proto
*/
historian.displayAppUserActivity = function(ua) {
if (ua && ua.length > 0) {
document.getElementById('appUserActivitySection').style.display = 'block';
var div = document.createElement('div');
var table = document.createElement('table');
table.setAttribute('class', 'tablesorter');
var thead = document.createElement('thead');
historian.addRow(thead, ['Name', 'Count']);
table.appendChild(thead);
// Pre-sort by decreasing count.
ua.sort(function(a, b) {
return b.count - a.count;
});
var tbody = document.createElement('tbody');
for (var i = 0; i < ua.length; i++) {
var a = ua[i];
// Unfortunately the UserActivity.Name gets converted to its int value
// instead of its string value.
var name = a.name > historian.userActivityName.length ?
'UNKNOWN' : historian.userActivityName[a.name];
historian.addRow(tbody, [name, a.count]);
}
table.appendChild(tbody);
div.appendChild(table);
document.getElementById('appUserActivity').innerHTML = div.innerHTML;
historian.activateTablesorter($('#appUserActivity table'), [], false);
} else {
document.getElementById('appUserActivitySection').style.display = 'none';
}
};
/**
* Displays or hides the section detailing wakelocks held by the app.
*
* @param {Array<Object>} wakelocks the list of Wakelock info in the app proto
*/
historian.displayAppWakelock = function(wakelocks) {
if (wakelocks && wakelocks.length > 0) {
document.getElementById('appWakelockSection').style.display = 'block';
// Pre-sort in decreasing order of full time, partial time, window time,
// full count, partial count, and window count.
wakelocks.sort(function(a, b) {
if (a.full_time_msec === b.full_time_msec) {
if (a.partial_time_msec === b.partial_time_msec) {
if (a.window_time_msec === b.window_time_msec) {
if (a.full_count === b.full_count) {
if (a.partial_count === b.partial_count) {
return b.window_count - a.window_count;
}
return b.partial_count - a.partial_count;
}
return b.full_count - a.full_count;
}
return b.window_time_msec - a.window_time_msec;
}
return b.partial_time_msec - a.partial_time_msec;
}
return b.full_time_msec - a.partial_time_msec;
});
var div = document.createElement('div');
var table = document.createElement('table');
table.setAttribute('class', 'tablesorter');
var thead = document.createElement('thead');
historian.addRowWithDesc(thead, [
{name: 'Wakelock Name'},
{name: 'Full Time', title: 'Time held holding a full wake lock'},
{name: 'Full Count', title: 'Number of full wake locks held'},
{name: 'Partial Time', title: 'Time held holding a partial wake lock'},
{name: 'Partial Count', title: 'Number of partial wake locks held'},
{name: 'Window Time', title: 'Time held holding a window wake lock'},
{name: 'Window Count', title: 'Number of window wake locks held'}
]);
table.appendChild(thead);
var tbody = document.createElement('tbody');
for (var i = 0; i < wakelocks.length; i++) {
var w = wakelocks[i];
historian.addRow(tbody, [
w.name,
historian.time.formatDuration(w.full_time_msec),
w.full_count,
historian.time.formatDuration(w.partial_time_msec),
w.partial_count,
historian.time.formatDuration(w.window_time_msec),
w.window_count
]);
}
table.appendChild(tbody);
div.appendChild(table);
document.getElementById('appWakelock').innerHTML = div.innerHTML;
// Apply tablesort 'duration' parser to Full Time, Partial Time,
// and Window Time columns.
historian.activateTablesorter($('#appWakelock table'), [1, 3, 5], false);
} else {
document.getElementById('appWakelockSection').style.display = 'none';
}
};
/**
* Displays info about the desired app.
*
* @param {number} appUid the uid of the app to display information about
*/
historian.displayApp = function(appUid) {
document.getElementById('noAppSelected').style.display = 'none';
document.getElementById('selectedAppStats').style.display = 'block';
app = appStats[appUid];
var div = document.createElement('div');
var table = document.createElement('table');
// Don't want to enable sorting for the table, but it needs the blue
// classification in order to look like the rest of the tables.
table.setAttribute('class', 'tablesorter-blue');
var tbody = document.createElement('tbody');
historian.addRow(tbody, ['Application', app.name]);
historian.addRow(tbody, ['Version Code', app.version_code]);
historian.addRow(tbody, ['UID', app.uid]);
if (app.power_use_item) {
historian.addRow(tbody, [
'Computed power drain',
historian.formatString('%s %',
((100 * app.power_use_item.computed_power_mah) / batteryCapacity)
.toFixed(2))
]);
}
if (app.foreground) {
historian.addRow(tbody, [
'Foreground',
historian.formatString('%s times over %s',
app.foreground.count,
historian.time.formatDuration(app.foreground.total_time_msec))
]);
}
// Foreground, Active, and Running times are excluded because they're not
// believed to be useful.
if (app.vibrator) {
historian.addRow(tbody, [
'Vibrator use',
historian.formatString('%s times over %s',
app.vibrator.count,
historian.time.formatDuration(app.vibrator.total_time_msec))
]);
}
table.appendChild(tbody);
div.appendChild(table);
document.getElementById('miscSummary').innerHTML = div.innerHTML;
historian.displayAppChild(app.name, app.child);
historian.displayAppApk(app.apk);
historian.displayAppNetworkInfo(app.network, app.wifi);
historian.displayAppProcess(app.process);
historian.displayAppScheduledJob(app.scheduled_job);
historian.displayAppSensor(app.sensor);
historian.displayAppSync(app.sync);
historian.displayAppUserActivity(app.user_activity);
historian.displayAppWakelock(app.wakelock);
};
/**
* Displays text to let the user know that no app has been selected.
*/
historian.showNoSelection = function() {
document.getElementById('noAppSelected').style.display = 'block';
document.getElementById('selectedAppStats').style.display = 'none';
};
/**
* Determines the app selected by the user and intitiates the showing of its
* details, or shows the message that no app has been selected if a user clears
* the app selection.
*/
historian.displaySelectedApp = function() {
var e = document.getElementById('appSelector');
var v = e.options[e.selectedIndex].value;
if (v == 'none_chosen') {
historian.showNoSelection();
} else {
historian.displayApp(v);
}
};
<file_sep>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package presenter
const (
// Checkin Summary Stats: Prefixed with C
cUptimeSecsPerHr = "UptimeSecsPerHr"
cScreenOffUptimeSecsPerHr = "ScreenOffUptimeSecsPerHr"
cScreenOnTimeSecsPerHr = "ScreenOnTimeSecsPerHr"
cPartialWakelockTimeSecsPerHr = "PartialWakelockTimeSecsPerHr"
cKernelOverheadTimeSecsPerHr = "KernelOverheadTimeSecsPerHr"
cSignalScanningTimeSecsPerHr = "SignalScanningTimeSecsPerHr"
cMobileActiveTimeSecsPerHr = "MobileActiveTimeSecsPerHr"
cWifiOnTimeSecsPerHr = "WifiOnTimeSecsPerHr"
cWifiIdleTimeSecsPerHr = "WifiIdleTimeSecsPerHr"
cWifiTransmitTimeSecsPerHr = "WifiTransmitTimeSecsPerHr"
cBluetoothIdleTimeSecsPerHr = "BluetoothIdleTimeSecsPerHr"
cBluetoothTransmitTimeSecsPerHr = "BluetoothTransmitTimeSecsPerHr"
cScreenOffDichargeRatePerHr = "ScreenOffDichargeRatePerHr"
cScreenOnDichargeRatePerHr = "ScreenOnDichargeRatePerHr"
cMobileKiloBytesPerHr = "MobileKiloBytesPerHr"
cWifiKiloBytesPerHr = "WifiKiloBytesPerHr"
cWifiDischargeRatePerHr = "WifiDischargeRatePerHr"
cBluetoothDischargeRatePerHr = "BluetoothDischargeRatePerHr"
// History Summary Stats: Prefixed with H
hScreenOn = "ScreenOn"
hScreenOnNumPerHr = "ScreenOnNumPerHr"
hScreenOnSecsPerHr = "ScreenOnSecsPerHr"
hCPURunning = "CPURunning"
hCPURunningNumPerHr = "CPURunningNumPerHr"
hCPURunningSecsPerHr = "CPURunningSecsPerHr"
hRadioOn = "RadioOn"
hRadioOnNumPerHr = "RadioOnNumPerHr"
hRadioOnSecsPerHr = "RadioOnSecsPerHr"
hPhoneCall = "PhoneCall"
hPhoneCallNumPerHr = "PhoneCallNumPerHr"
hPhoneCallSecsPerHr = "PhoneCallSecsPerHr"
hGpsOn = "GpsOn"
hGpsOnNumPerHr = "GpsOnNumPerHr"
hGpsOnSecsPerHr = "GpsOnSecsPerHr"
hWifiFullLock = "WifiFullLock"
hWifiFullLockNumPerHr = "WifiFullLockNumPerHr"
hWifiFullLockSecsPerHr = "WifiFullLockSecsPerHr"
hWifiScan = "WifiScan"
hWifiScanNumPerHr = "WifiScanNumPerHr"
hWifiScanSecsPerHr = "WifiScanSecsPerHr"
hWifiMulticastOn = "WifiMulticastOn"
hWifiMulticastOnNumPerHr = "WifiMulticastOnNumPerHr"
hWifiMulticastOnSecsPerHr = "WifiMulticastOnSecsPerHr"
hWifiOn = "WifiOn"
hWifiOnNumPerHr = "WifiOnNumPerHr"
hWifiOnSecsPerHr = "WifiOnSecsPerHr"
hPhoneScan = "PhoneScan"
hPhoneScanNumPerHr = "PhoneScanNumPerHr"
hPhoneScanSecsPerHr = "PhoneScanSecsPerHr"
hSensorOn = "SensorOn"
hSensorOnNumPerHr = "SensorOnNumPerHr"
hSensorOnSecsPerHr = "SensorOnSecsPerHr"
hPluggedIn = "PluggedIn"
hPluggedInNumPerHr = "PluggedInNumPerHr"
hPluggedInSecsPerHr = "PluggedInSecsPerHr"
hTotalSync = "TotalSync"
hTotalSyncNumPerHr = "TotalSyncNumPerHr"
hTotalSyncSecsPerHr = "TotalSyncSecsPerHr"
hIdleModeOn = "IdleModeOn"
hIdleModeOnNumPerHr = "IdleModeOnNumPerHr"
hIdleModeOnSecsPerHr = "IdleModeOnSecsPerHr"
// Multi variable stats
hDataConnectionSummary = "DataConnectionSummary"
hConnectivitySummary = "ConnectivitySummary"
hPerAppSyncSummary = "PerAppSyncSummary"
hWakeupReasonSummary = "WakeupReasonSummary"
hPhoneStateSummary = "PhoneStateSummary"
hForegroundProcessSummary = "ForegroundProcessSummary"
hFirstWakelockAfterSuspend = "FirstWakelockAfterSuspend"
hScheduledJobSummary = "ScheduledJobSummary"
)
<file_sep>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package presenter contains the logic to create data structures for
// HTML presentation of Battery Historian analysis.
package presenter
import (
"bytes"
"fmt"
"html/template"
"sort"
"strconv"
"time"
"github.com/golang/protobuf/proto"
"github.com/google/battery-historian/checkinparse"
"github.com/google/battery-historian/parseutils"
bspb "github.com/google/battery-historian/pb/batterystats_proto"
)
type mDuration struct {
V time.Duration
L string // Low, Medium, High
}
type mFloat32 struct {
V float32
L string // Low, Medium, High
}
// HTMLData is the main structure passed to the frontend HTML template containing all analysis items.
type HTMLData struct {
SDKVersion int
DeviceModel string
HistorianCsv string
Historian template.HTML
Count int
UnplugSummaries []UnplugSummary
CheckinSummary checkin
Error string
Warning string
Filename string
AppStats []*bspb.BatteryStats_App
}
// WakelockData contains stats about wakelocks.
type WakelockData struct {
Name string
UID int32
Count float32
Duration time.Duration
Level int // Low, Medium, High
}
// PowerUseData contains percentage battery consumption for apps and system elements.
type PowerUseData struct {
Name string
UID int32
Percent float32 // Percentage of total consumption
}
// byPercent sorts applications by percentage battery used.
type byPercent []*PowerUseData
func (a byPercent) Len() int { return len(a) }
func (a byPercent) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// Less sorts by decreasing time order then increasing alphabetic order to break the tie.
func (a byPercent) Less(i, j int) bool {
if x, y := a[i].Percent, a[j].Percent; x != y {
return x > y
}
return a[i].Name < a[j].Name
}
// MobileActiveData contains the total amount of time an application actively used the mobile network.
type MobileActiveData struct {
Name string
UID int32
Duration time.Duration
}
// byTime sorts MobileActiveData by the time used.
type byTime []*MobileActiveData
func (m byTime) Len() int { return len(m) }
func (m byTime) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
// Less sorts by decreasing time order then increasing alphabetic order to break the tie.
func (m byTime) Less(i, j int) bool {
if x, y := m[i].Duration, m[j].Duration; x != y {
return x > y
}
return m[i].Name < m[j].Name
}
// NetworkTrafficData contains the total amount of bytes transferred over mobile and wifi.
type NetworkTrafficData struct {
Name string
UID int32
WifiMegaBytes, MobileMegaBytes float32
}
// byMobileBytes sorts NetworkTrafficData by the amount of bytes transferred over mobile.
type byMobileBytes []*NetworkTrafficData
func (n byMobileBytes) Len() int { return len(n) }
func (n byMobileBytes) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
// Less sorts in decreasing order.
func (n byMobileBytes) Less(i, j int) bool {
return n[i].MobileMegaBytes > n[j].MobileMegaBytes
}
// byWifiBytes sorts NetworkTrafficData by the amount of bytes transferred over mobile.
type byWifiBytes []*NetworkTrafficData
func (n byWifiBytes) Len() int { return len(n) }
func (n byWifiBytes) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
// Less sorts in decreasing order.
func (n byWifiBytes) Less(i, j int) bool {
return n[i].WifiMegaBytes > n[j].WifiMegaBytes
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
// CheckinSummary contains the aggregated batterystats data for a bugreport.
type checkin struct {
Device string
Build string
BuildFingerprint string
ReportVersion int32
ScreenOffDischargePoints float32
ScreenOnDischargePoints float32
MiscPercentage float32
BatteryCapacity float32 // mAh
ActualDischarge float32 // mAh
EstimatedDischarge float32 // mAh
WifiDischargePoints float32
BluetoothDischargePoints float32
Realtime time.Duration
ScreenOffRealtime time.Duration
Uptime mDuration
ScreenOffUptime mDuration
ScreenOnTime mDuration
PartialWakelockTime mDuration
KernelOverheadTime mDuration
SignalScanningTime mDuration
MobileActiveTime mDuration
WifiOnTime mDuration
WifiIdleTime mDuration
WifiTransmitTime mDuration // tx + rx
BluetoothIdleTime mDuration
BluetoothTransmitTime mDuration // tx + rx
ScreenOffDichargeRatePerHr mFloat32
ScreenOnDichargeRatePerHr mFloat32
MobileKiloBytesPerHr mFloat32
WifiKiloBytesPerHr mFloat32
WifiDischargeRatePerHr mFloat32
BluetoothDischargeRatePerHr mFloat32
UserspaceWakelocks []WakelockData
KernelWakelocks []WakelockData
SyncTasks []WakelockData
TopMobileActiveApps []MobileActiveData
TopMobileTrafficApps []NetworkTrafficData
TopWifiTrafficApps []NetworkTrafficData
TopBatteryConsumingEntities []PowerUseData
}
// UnplugSummary contains stats processed from battery history during discharge intervals.
type UnplugSummary struct {
Date string
Reason string
SummaryStart string
SummaryEnd string
Duration string
LevelDrop int32
LevelDropPerHour float64
SystemStats []DurationStats
BreakdownStats []MultiDurationStats
}
// DurationStats contain stats on the occrurence frequency and activity duration of a metric present in history.
type DurationStats struct {
Name string
NumRate float64
DurationRate float64
Num int32
TotalDuration time.Duration
MaxDuration time.Duration
NumLevel string
DurationLevel string
}
// MultiDurationStats contains named DurationStats.
type MultiDurationStats struct {
Metric string
Stats []DurationStats
}
type internalDist struct {
parseutils.Dist
}
func (d internalDist) print(device, name string, duration time.Duration) DurationStats {
ds := DurationStats{
Name: name,
NumRate: float64(d.Num) / duration.Hours(),
DurationRate: d.TotalDuration.Seconds() / duration.Hours(),
Num: d.Num,
TotalDuration: d.TotalDuration,
MaxDuration: d.MaxDuration,
}
return ds
}
func mapPrint(device, name string, m map[string]parseutils.Dist, duration time.Duration) MultiDurationStats {
var stats []parseutils.MultiDist
for k, v := range m {
stats = append(stats, parseutils.MultiDist{Name: k, Stat: v})
}
sort.Sort(sort.Reverse(parseutils.SortByTimeAndCount(stats)))
var ds []DurationStats
for _, s := range stats {
if s.Stat.TotalDuration > 0 {
d := DurationStats{
Name: s.Name,
NumRate: float64(s.Stat.Num) / duration.Hours(),
DurationRate: s.Stat.TotalDuration.Seconds() / duration.Hours(),
Num: s.Stat.Num,
TotalDuration: s.Stat.TotalDuration,
MaxDuration: s.Stat.MaxDuration,
}
ds = append(ds, d)
}
}
return MultiDurationStats{Metric: name, Stats: ds}
}
func parseCheckinData(c *bspb.BatteryStats) checkin {
if c == nil {
return checkin{}
}
realtime := time.Duration(c.System.Battery.GetBatteryRealtimeMsec()) * time.Millisecond
out := checkin{
Device: c.Build.GetDevice(),
Build: c.Build.GetBuildId(),
BuildFingerprint: c.Build.GetFingerprint(),
ReportVersion: c.GetReportVersion(),
Realtime: realtime,
ScreenOffRealtime: time.Duration(c.System.Battery.GetScreenOffRealtimeMsec()) * time.Millisecond,
ScreenOffDischargePoints: c.System.BatteryDischarge.GetScreenOff(),
ScreenOnDischargePoints: c.System.BatteryDischarge.GetScreenOn(),
BatteryCapacity: c.System.PowerUseSummary.GetBatteryCapacityMah(),
EstimatedDischarge: c.System.PowerUseSummary.GetComputedPowerMah(),
ActualDischarge: (c.System.PowerUseSummary.GetMinDrainedPowerMah() + c.System.PowerUseSummary.GetMaxDrainedPowerMah()) / 2,
// Uptime is the same as screen-off uptime + screen on time
Uptime: mDuration{
V: (time.Duration(c.System.Battery.GetBatteryUptimeMsec()) * time.Millisecond),
},
ScreenOffUptime: mDuration{
V: (time.Duration(c.System.Battery.GetScreenOffUptimeMsec()) * time.Millisecond),
},
ScreenOnTime: mDuration{
V: (time.Duration(c.System.Misc.GetScreenOnTimeMsec()) * time.Millisecond),
},
PartialWakelockTime: mDuration{
V: (time.Duration(c.System.Misc.GetPartialWakelockTimeMsec()) * time.Millisecond),
},
KernelOverheadTime: mDuration{
V: (time.Duration(c.System.Battery.GetScreenOffUptimeMsec()-c.System.Misc.GetPartialWakelockTimeMsec()) * time.Millisecond),
},
SignalScanningTime: mDuration{
V: (time.Duration(c.System.SignalScanningTime.GetTimeMsec()) * time.Millisecond),
},
MobileActiveTime: mDuration{
V: (time.Duration(c.System.Misc.GetMobileActiveTimeMsec()) * time.Millisecond),
},
}
out.MiscPercentage = 100 * (out.ActualDischarge - out.EstimatedDischarge) / out.BatteryCapacity
out.MobileKiloBytesPerHr = mFloat32{V: (c.System.GlobalNetwork.GetMobileBytesRx() + c.System.GlobalNetwork.GetMobileBytesTx()) / (1024 * float32(realtime.Hours()))}
out.WifiKiloBytesPerHr = mFloat32{V: (c.System.GlobalNetwork.GetWifiBytesRx() + c.System.GlobalNetwork.GetWifiBytesTx()) / (1024 * float32(realtime.Hours()))}
if c.GetReportVersion() >= 14 {
out.WifiOnTime = mDuration{V: time.Duration(c.System.GlobalWifi.GetWifiOnTimeMsec()) * time.Millisecond}
out.WifiIdleTime = mDuration{V: time.Duration(c.System.GlobalWifi.GetWifiIdleTimeMsec()) * time.Millisecond}
out.WifiTransmitTime = mDuration{V: time.Duration(c.System.GlobalWifi.GetWifiRxTimeMsec()+c.System.GlobalWifi.GetWifiTxTimeMsec()) * time.Millisecond}
out.WifiDischargePoints = 100 * c.System.GlobalWifi.GetWifiPowerMah() / c.GetSystem().GetPowerUseSummary().GetBatteryCapacityMah()
out.WifiDischargeRatePerHr = mFloat32{
V: 100 * c.System.GlobalWifi.GetWifiPowerMah() / c.GetSystem().GetPowerUseSummary().GetBatteryCapacityMah() / float32(realtime.Hours()),
}
out.BluetoothIdleTime = mDuration{V: time.Duration(c.System.GlobalBluetooth.GetBluetoothIdleTimeMsec()) * time.Millisecond}
out.BluetoothTransmitTime = mDuration{V: time.Duration(c.System.GlobalBluetooth.GetBluetoothRxTimeMsec()+c.System.GlobalBluetooth.GetBluetoothTxTimeMsec()) * time.Millisecond}
out.BluetoothDischargePoints = 100 * c.System.GlobalBluetooth.GetBluetoothPowerMah() / c.GetSystem().GetPowerUseSummary().GetBatteryCapacityMah()
out.BluetoothDischargeRatePerHr = mFloat32{
V: 100 * c.System.GlobalBluetooth.GetBluetoothPowerMah() / c.GetSystem().GetPowerUseSummary().GetBatteryCapacityMah() / float32(realtime.Hours()),
}
}
if s := c.System.Battery.GetScreenOffRealtimeMsec(); s > 0 {
out.ScreenOffDichargeRatePerHr = mFloat32{V: 60 * 60 * 1000 * c.System.BatteryDischarge.GetScreenOff() / s}
}
if s := c.System.Misc.GetScreenOnTimeMsec(); s > 0 {
out.ScreenOnDichargeRatePerHr = mFloat32{V: 60 * 60 * 1000 * c.System.BatteryDischarge.GetScreenOn() / s}
}
// Top Partial Wakelocks by time and count
var pwl []*checkinparse.WakelockInfo
for _, app := range c.App {
for _, pw := range app.Wakelock {
if pw.GetPartialTimeMsec() >= 0.01 {
pwl = append(pwl, &checkinparse.WakelockInfo{
Name: fmt.Sprintf("%s : %s", app.GetName(), pw.GetName()),
UID: app.GetUid(),
Duration: time.Duration(pw.GetPartialTimeMsec()) * time.Millisecond,
Count: pw.GetPartialCount(),
})
}
}
}
// Top Partial Wakelocks by time
checkinparse.SortByTime(pwl)
for _, pw := range pwl {
out.UserspaceWakelocks = append(out.UserspaceWakelocks, WakelockData{
Name: pw.Name,
UID: pw.UID,
Count: pw.Count,
Duration: pw.Duration,
})
}
// Top 5 Kernel Wakelocks
var kwl []*checkinparse.WakelockInfo
for _, kw := range c.System.KernelWakelock {
if kw.GetName() != "PowerManagerService.WakeLocks" && kw.GetTimeMsec() >= 0.01 {
kwl = append(kwl, &checkinparse.WakelockInfo{
Name: kw.GetName(),
Duration: time.Duration(kw.GetTimeMsec()) * time.Millisecond,
Count: kw.GetCount(),
})
}
}
// Top Kernel Wakelocks by time
checkinparse.SortByTime(kwl)
for _, kw := range kwl {
out.KernelWakelocks = append(out.KernelWakelocks, WakelockData{
Name: kw.Name,
Count: kw.Count,
Duration: kw.Duration,
})
}
// Top SyncTasks by time and count
var stl []*checkinparse.WakelockInfo
for _, app := range c.App {
for _, st := range app.Sync {
if st.GetTotalTimeMsec() >= 0.01 {
stl = append(stl, &checkinparse.WakelockInfo{
Name: fmt.Sprintf("%s : %s", app.GetName(), st.GetName()),
UID: app.GetUid(),
Duration: time.Duration(st.GetTotalTimeMsec()) * time.Millisecond,
Count: st.GetCount(),
})
}
}
}
// Top SyncTasks by time
checkinparse.SortByTime(stl)
for _, st := range stl {
out.SyncTasks = append(out.SyncTasks, WakelockData{
Name: st.Name,
UID: st.UID,
Count: st.Count,
Duration: st.Duration,
})
}
// Top power consumers and network users
var e []*PowerUseData
var m []*MobileActiveData
var n []*NetworkTrafficData
for _, app := range c.App {
if mah := app.PowerUseItem.GetComputedPowerMah(); mah >= 0.01 {
e = append(e, &PowerUseData{
Name: app.GetName(),
UID: app.GetUid(),
Percent: 100 * mah / c.GetSystem().GetPowerUseSummary().GetBatteryCapacityMah(),
})
}
if mat := app.Network.GetMobileActiveTimeMsec(); mat >= 0.01 {
m = append(m, &MobileActiveData{
Name: app.GetName(),
UID: app.GetUid(),
Duration: time.Duration(mat) * time.Millisecond,
})
}
wr := app.Network.GetWifiBytesRx()
wt := app.Network.GetWifiBytesTx()
mt := app.Network.GetMobileBytesTx()
mr := app.Network.GetMobileBytesRx()
if wr+wt+mt+mr >= 0.01 {
n = append(n, &NetworkTrafficData{
Name: app.GetName(),
UID: app.GetUid(),
WifiMegaBytes: (wr + wt) / (1024 * 1024),
MobileMegaBytes: (mr + mt) / (1024 * 1024),
})
}
}
for _, pwi := range c.System.PowerUseItem {
if pwi.GetName() == bspb.BatteryStats_System_PowerUseItem_APP {
// We have the apps split up in the preceding for loop, and the APP entry is just the sum of all of them, so we skip it here.
continue
}
if mah := pwi.GetComputedPowerMah(); mah >= 0.01 {
e = append(e, &PowerUseData{
Name: pwi.GetName().String(),
Percent: 100 * mah / c.GetSystem().GetPowerUseSummary().GetBatteryCapacityMah(),
})
}
}
sort.Sort(byPercent(e))
for _, ent := range e {
out.TopBatteryConsumingEntities = append(out.TopBatteryConsumingEntities, *ent)
}
sort.Sort(byTime(m))
for _, mad := range m {
out.TopMobileActiveApps = append(out.TopMobileActiveApps, *mad)
}
sort.Sort(byMobileBytes(n))
for _, ntd := range n {
if ntd.MobileMegaBytes >= 0.01 {
out.TopMobileTrafficApps = append(out.TopMobileTrafficApps, *ntd)
}
}
sort.Sort(byWifiBytes(n))
for _, ntd := range n {
if ntd.WifiMegaBytes >= 0.01 {
out.TopWifiTrafficApps = append(out.TopWifiTrafficApps, *ntd)
}
}
return out
}
// byName sorts applications by name in ascending order.
type byName []*bspb.BatteryStats_App
func (a byName) Len() int { return len(a) }
func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byName) Less(i, j int) bool { return a[i].GetName() < a[j].GetName() }
func parseAppStats(checkin *bspb.BatteryStats) []*bspb.BatteryStats_App {
var as []*bspb.BatteryStats_App
unknown := 1
for _, a := range checkin.GetApp() {
if a.GetName() == "" {
a.Name = proto.String("UNKNOWN_" + strconv.Itoa(unknown))
unknown++
}
as = append(as, a)
}
// Sort by name so that we can display the apps in alphabetical order in the dropdown.
sort.Sort(byName(as))
return as
}
// Data returns a single structure (HTMLData) containing aggregated battery stats in html format.
func Data(sdkVersion int, model, csv, fname string, summaries []parseutils.ActivitySummary, checkinOutput *bspb.BatteryStats, historianOutput string, warnings []string, errs []error) HTMLData {
var output []UnplugSummary
ch := parseCheckinData(checkinOutput)
dev := ch.Device
for _, s := range summaries {
duration := time.Duration(s.EndTimeMs-s.StartTimeMs) * time.Millisecond
if duration == 0 {
errs = append(errs, fmt.Errorf("error! Invalid duration equals 0"))
continue
}
t := UnplugSummary{
Date: s.Date,
Reason: s.Reason,
SummaryStart: time.Unix(0, s.StartTimeMs*int64(time.Millisecond)).String(),
SummaryEnd: time.Unix(0, s.EndTimeMs*int64(time.Millisecond)).String(),
Duration: (time.Duration(s.EndTimeMs-s.StartTimeMs) * time.Millisecond).String(),
LevelDrop: int32(s.InitialBatteryLevel - s.FinalBatteryLevel),
LevelDropPerHour: float64(s.InitialBatteryLevel-s.FinalBatteryLevel) / duration.Hours(),
SystemStats: []DurationStats{
internalDist{s.ScreenOnSummary}.print(dev, hScreenOn, duration),
internalDist{s.CPURunningSummary}.print(dev, hCPURunning, duration),
internalDist{s.TotalSyncSummary}.print(dev, hTotalSync, duration),
internalDist{s.MobileRadioOnSummary}.print(dev, hRadioOn, duration),
internalDist{s.PhoneCallSummary}.print(dev, hPhoneCall, duration),
internalDist{s.GpsOnSummary}.print(dev, hGpsOn, duration),
internalDist{s.WifiFullLockSummary}.print(dev, hWifiFullLock, duration),
internalDist{s.WifiScanSummary}.print(dev, hWifiScan, duration),
internalDist{s.WifiMulticastOnSummary}.print(dev, hWifiMulticastOn, duration),
internalDist{s.WifiOnSummary}.print(dev, hWifiOn, duration),
internalDist{s.PhoneScanSummary}.print(dev, hPhoneScan, duration),
internalDist{s.SensorOnSummary}.print(dev, hSensorOn, duration),
internalDist{s.PluggedInSummary}.print(dev, hPluggedIn, duration),
internalDist{s.IdleModeOnSummary}.print(dev, hIdleModeOn, duration),
// Disabled as they were not found to be very useful.
/*
internalDist{s.WifiRunningSummary}.print("WifiRunning", duration),
*/
},
BreakdownStats: []MultiDurationStats{
mapPrint(dev, hDataConnectionSummary, s.DataConnectionSummary, duration),
mapPrint(dev, hConnectivitySummary, s.ConnectivitySummary, duration),
mapPrint(dev, hPerAppSyncSummary, s.PerAppSyncSummary, duration),
mapPrint(dev, hWakeupReasonSummary, s.WakeupReasonSummary, duration),
mapPrint(dev, hFirstWakelockAfterSuspend, s.WakeLockSummary, duration),
mapPrint(dev, hForegroundProcessSummary, s.ForegroundProcessSummary, duration),
mapPrint(dev, hPhoneStateSummary, s.PhoneStateSummary, duration),
mapPrint(dev, hScheduledJobSummary, s.ScheduledJobSummary, duration),
// Disabled as they were not found to be very useful.
/*
mapPrint("HealthSummary", s.HealthSummary, duration),
mapPrint("PlugTypeSummary", s.PlugTypeSummary, duration),
mapPrint("ChargingStatusSummary", s.ChargingStatusSummary, duration),
mapPrint("TopApplicationSummary", s.TopApplicationSummary, duration),
*/
},
}
output = append(output, t)
}
// We want each error and warning to be seen on separate lines for clarity
var errorB, warnB bytes.Buffer
for _, e := range errs {
fmt.Fprintln(&errorB, e.Error())
}
for _, w := range warnings {
fmt.Fprintln(&warnB, w)
}
return HTMLData{
SDKVersion: sdkVersion,
DeviceModel: model,
HistorianCsv: csv,
Historian: template.HTML(historianOutput),
Filename: fname,
Count: len(output),
UnplugSummaries: output,
CheckinSummary: ch,
Error: errorB.String(),
Warning: warnB.String(),
AppStats: parseAppStats(checkinOutput),
}
}
<file_sep>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package analyzer runs the Historian state machine code on the uploaded bugreport.
package analyzer
import (
"bufio"
"bytes"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"github.com/golang/protobuf/proto"
"github.com/google/battery-historian/checkinparse"
"github.com/google/battery-historian/checkinutil"
"github.com/google/battery-historian/packageutils"
"github.com/google/battery-historian/parseutils"
"github.com/google/battery-historian/presenter"
bspb "github.com/google/battery-historian/pb/batterystats_proto"
sessionpb "github.com/google/battery-historian/pb/session_proto"
)
const (
maxFileSize = 50 * 1024 * 1024 // 50 MB Limit
minSupportedSDK = 21 // We only support Lollipop bug reports and above
)
var (
// Initialized in InitTemplates()
uploadTempl *template.Template
resultTempl *template.Template
isOptimizedJs bool
)
type historianData struct {
html string
err error
}
type summariesData struct {
summaries []parseutils.ActivitySummary
historianCsv string
errs []error
}
type checkinData struct {
batterystats *bspb.BatteryStats
warnings []string
err []error
}
// InitTemplates initializes the HTML templates.
func InitTemplates() {
uploadTempl = template.Must(template.ParseFiles(
"templates/base.html", "templates/body.html", "templates/upload.html"),
)
// base.html is intentionally excluded from resultTempl. resultTempl is loaded into the HTML
// generated by uploadTempl, so attempting to include base.html here causes some of the
// javascript files to be imported twice, which causes things to start blowing up.
resultTempl = template.Must(template.ParseFiles(
"templates/body.html", "templates/summaries.html"),
)
}
// SetIsOptimized sets whether the JS will be optimized.
func SetIsOptimized(optimized bool) {
isOptimizedJs = optimized
}
func closeConnection(w http.ResponseWriter, s string) {
if flusher, ok := w.(http.Flusher); ok {
w.Header().Set("Connection", "close")
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(s)))
w.WriteHeader(http.StatusExpectationFailed)
io.WriteString(w, s)
flusher.Flush()
}
fmt.Println(s, " Closing connection.")
conn, _, _ := w.(http.Hijacker).Hijack()
conn.Close()
}
// UploadHandler is the main analysis function.
func UploadHandler(w http.ResponseWriter, r *http.Request) {
// If false, the upload template will load closure and js files in the header.
uploadData := struct {
IsOptimizedJs bool
}{
isOptimizedJs,
}
switch r.Method {
//GET displays the upload form.
case "GET":
if err := uploadTempl.Execute(w, uploadData); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//POST takes the uploaded file(s) and saves it to disk.
case "POST":
// Do not accept files that are greater than 50 MBs
if r.ContentLength > maxFileSize {
closeConnection(w, "File too large (>50MB).")
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxFileSize)
//get the multipart reader for the request.
reader, err := r.MultipartReader()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Printf("Trace Starting reading uploaded file. %d bytes", r.ContentLength)
//copy each part to destination.
for {
part, err := reader.NextPart()
if err == io.EOF {
break
}
//if part.FileName() is empty, skip this iteration.
if part == nil || part.FileName() == "" {
continue
}
b, err := ioutil.ReadAll(part)
if err != nil {
http.Error(w, "Failed to read file. Please try again.", http.StatusInternalServerError)
return
}
contentType := http.DetectContentType(b)
if !strings.Contains(contentType, "text/plain") {
http.Error(w, "Incorrect file format detected", http.StatusInternalServerError)
return
}
log.Printf("Trace started analyzing file.")
// Generate the Historian plot and parsing simultaneously.
historianCh := make(chan historianData)
summariesCh := make(chan summariesData)
checkinCh := make(chan checkinData)
contents := string(b)
// Create a temporary file to save bug report, for the Historian script.
tmpFile, err := ioutil.TempFile("", "historian")
historianOutput := historianData{"", err}
if err == nil {
// Don't run the Historian script if could not create temporary file.
fname := tmpFile.Name()
defer os.Remove(fname)
tmpFile.WriteString(contents)
tmpFile.Close()
go func() {
html, err := generateHistorianPlot(w, part.FileName(), fname)
historianCh <- historianData{html, err}
log.Printf("Trace finished generating Historian plot.")
}()
}
var errs []error
sdk, err := sdkVersion(contents)
if sdk < minSupportedSDK {
errs = append(errs, errors.New("unsupported bug report version"))
}
if err != nil {
errs = append(errs, err)
}
if sdk >= minSupportedSDK {
// No point running these if we don't support the sdk version since we won't get any data from them.
go func() {
o, c, errs := analyze(contents)
summariesCh <- summariesData{o, c, errs}
log.Printf("Trace finished processing summary data.")
}()
go func() {
var ctr checkinutil.IntCounter
/* Extract Build Fingerprint from the bugreport. */
s := &sessionpb.Checkin{
Checkin: proto.String(contents),
BuildFingerprint: proto.String(extractBuildFingerprint(contents)),
}
pkgs, pkgErrs := packageutils.ExtractAppsFromBugReport(contents)
stats, warnings, pbsErrs := checkinparse.ParseBatteryStats(&ctr, checkinparse.CreateCheckinReport(s), pkgs)
checkinCh <- checkinData{stats, warnings, append(pkgErrs, pbsErrs...)}
}()
}
if historianOutput.err == nil {
historianOutput = <-historianCh
}
if historianOutput.err != nil {
historianOutput.html = fmt.Sprintf("Error generating historian plot: %v", historianOutput.err)
}
var summariesOutput summariesData
var checkinOutput checkinData
if sdk >= minSupportedSDK {
summariesOutput = <-summariesCh
checkinOutput = <-checkinCh
errs = append(errs, append(summariesOutput.errs, checkinOutput.err...)...)
}
log.Printf("Trace finished generating Historian plot and summaries.")
data := presenter.Data(sdk, modelName(contents), summariesOutput.historianCsv, part.FileName(), summariesOutput.summaries, checkinOutput.batterystats, historianOutput.html, checkinOutput.warnings, errs)
if err := resultTempl.Execute(w, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
log.Printf("Trace ended analyzing file.")
}
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func analyze(bugreport string) ([]parseutils.ActivitySummary, string, []error) {
var b bytes.Buffer
rep := parseutils.AnalyzeHistory(bugreport, parseutils.FormatTotalTime, &b, false)
// Exclude summaries with no change in battery level
var a []parseutils.ActivitySummary
for _, s := range rep.Summaries {
if s.InitialBatteryLevel != s.FinalBatteryLevel {
a = append(a, s)
}
}
return a, b.String(), rep.Errs
}
// generateHistorianPlot calls the Historian python script to generate html charts.
func generateHistorianPlot(w http.ResponseWriter, reportName, filepath string) (string, error) {
cmd := exec.Command("./historian.py", "-c", "-m", "-r", reportName, filepath)
// Stdout pipe for reading the generated Historian output.
cmdStdout, stdoutErr := cmd.StdoutPipe()
if stdoutErr != nil {
return "", stdoutErr
}
// Run the Historian script.
if err := cmd.Start(); err != nil {
return "", err
}
outputCh := make(chan string)
go getStdout(w, cmdStdout, outputCh)
// Read the output generated by historian.
output := <-outputCh
if err := cmd.Wait(); err != nil {
return "", err
}
return output, nil
}
// getStdout reads the output generated by Historian.
func getStdout(w http.ResponseWriter, stdout io.ReadCloser, outputChan chan string) {
scanner := bufio.NewScanner(stdout)
var buffer bytes.Buffer
for scanner.Scan() {
buffer.WriteString(scanner.Text() + "\n")
}
outputChan <- buffer.String()
}
func sdkVersion(input string) (int, error) {
// Found in the System Properties section of a bug report.
re := regexp.MustCompile(`.*\[ro.build.version.sdk\]:\s+\[(?P<sdkVersion>\d+)\].*`)
if match, result := parseutils.SubexpNames(re, input); match {
return strconv.Atoi(result["sdkVersion"])
}
return -1, errors.New("unable to find device SDK version")
}
// modelName returns the device's model name (ie. Nexus 5).
func modelName(input string) string {
// Found in the System Properties section of a bug report.
re := regexp.MustCompile(`.*\[ro.product.model\]:\s+\[(?P<modelName>.*)\].*`)
if match, result := parseutils.SubexpNames(re, input); match {
return result["modelName"]
}
// We should only get to this point in the case of a bad (malformed) bug report.
return "unknown device"
}
func extractBuildFingerprint(input string) string {
// A regular expression to match any build fingerprint line in the bugreport.
re := regexp.MustCompile("Build\\s+fingerprint:\\s+'(?P<build>\\S+)'")
var out string
for _, line := range strings.Split(input, "\n") {
if match, result := parseutils.SubexpNames(re, line); match {
out = result["build"]
break
}
}
return out
}
<file_sep>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package csv contains functions to store EntryState events,
// and print them in CSV format.
package csv
import (
"fmt"
"io"
)
// FileHeader is outputted as the first line in csv files.
const FileHeader = "metric,type,start_time,end_time,value,opt"
// Entry contains the details of the start of a state.
type Entry struct {
Desc string
Start int64
Type string
Value string
// Additional data associated with the entry.
// Currently this is used to hold the UID (string) of a service (ServiceUID),
// and is an empty string for other types.
Opt string
}
// State holds the csv writer, and the map from metric key to active entry.
type State struct {
// For printing the CSV entries to.
writer io.Writer
entries map[Key]Entry
rebootEvent *Entry
}
// Key is the unique identifier for an entry.
type Key struct {
Metric, Identifier string
}
// NewState returns a new State.
func NewState(csvWriter io.Writer) *State {
// Write the csv header.
if csvWriter != nil {
fmt.Fprintln(csvWriter, FileHeader)
}
return &State{
writer: csvWriter,
entries: make(map[Key]Entry),
}
}
// HasRebootEvent returns true if a reboot event is currently stored, false otherwise.
func (s *State) HasRebootEvent() bool {
return (s.rebootEvent != nil)
}
// AddRebootEvent stores the entry for the reboot event,
// using the given curTime as the start time.
func (s *State) AddRebootEvent(curTime int64) {
s.rebootEvent = &Entry{
"Reboot",
curTime,
"bool",
"true",
"",
}
}
// PrintRebootEvent prints out the stored reboot event,
// using the given curTime as the end time.
func (s *State) PrintRebootEvent(curTime int64) {
if e := s.rebootEvent; e != nil {
s.print(e.Desc, e.Type, e.Start, curTime, e.Value, e.Opt)
s.rebootEvent = nil
}
}
// AddEntry adds the given entry into the existing map.
// If the entry already exists, it prints out the entry and deletes it.
func (s *State) AddEntry(desc string, newState EntryState, curTime int64) {
s.AddEntryWithOpt(desc, newState, curTime, "")
}
// AddEntryWithOpt adds the given entry into the existing map, with the optional
// value set.
// If the entry already exists, it prints out the entry and deletes it.
func (s *State) AddEntryWithOpt(desc string, newState EntryState, curTime int64, opt string) {
key := newState.GetKey(desc)
if e, ok := s.entries[key]; ok {
s.print(e.Desc, e.Type, e.Start, curTime, e.Value, e.Opt)
delete(s.entries, key)
return
}
if newState.GetStartTime() == 0 || newState.GetValue() == "" {
return
}
s.entries[key] = Entry{
desc,
curTime,
newState.GetType(),
newState.GetValue(),
opt,
}
}
func (s *State) print(desc, metricType string, start, end int64, value, opt string) {
if s.writer != nil {
fmt.Fprintf(s.writer, "%s,%s,%d,%d,%s,%s\n", desc, metricType, start, end, value, opt)
}
}
// PrintAllReset prints all active entries and resets the map.
func (s *State) PrintAllReset(curTime int64) {
for _, e := range s.entries {
s.print(e.Desc, e.Type, e.Start, curTime, e.Value, e.Opt)
}
s.entries = make(map[Key]Entry)
}
// EntryState is a commmon interface for the various types,
// so the Entries can access them the same way.
type EntryState interface {
// GetStartTime returns the start time of the entry.
GetStartTime() int64
// GetType returns the type of the entry:
// "string", "bool", "int" or "service".
GetType() string
// GetValue returns the stored value of the entry.
GetValue() string
// GetKey returns the unique identifier for the entry.
GetKey(string) Key
}
<file_sep>/**
*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Time related helper functions to format time
* into readable formats, and calculate durations.
*/
goog.provide('historian.time');
/** @const {number} */
historian.time.MSECS_IN_SEC = 1000;
/** @const {number} */
historian.time.SECS_IN_MIN = 60;
/** @const {number} */
historian.time.MINS_IN_HOUR = 60;
/**
* Returns the date formatted in "Month Day Year".
* @param {number} t The Unix timestamp to format.
* @return {string} The formatted date "Month Day Year".
*/
historian.time.getDate = function(t) {
var d = new Date(t);
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return months[d.getMonth()] + ' ' + d.getDate() + ' ' + d.getFullYear();
};
/**
* Returns the time formatted in 'hh:mm:ss'.
* @export
* @param {number} t The Unix timestamp to format.
* @return {string} The formatted time 'hh:mm:ss'.
*/
historian.time.getTime = function(t) {
var d = new Date(t);
return (
historian.time.padTime_(d.getUTCHours()) + ':' +
historian.time.padTime_(d.getUTCMinutes()) + ':' +
historian.time.padTime_(d.getUTCSeconds()));
};
/**
* Pads the unit to two digits by prepending a 0 if the length is 1.
* @param {number} u The number to format.
* @return {string} The formatted number as two digits in a string.
* @private
*/
historian.time.padTime_ = function(u) {
if ((u + '').length === 1) {
return '0' + u;
}
return '' + u;
};
/**
* Returns the ms duration formatted as a human readable string.
* Format is "1h 3m 4s 30ms".
* @export
* @param {number} duration The time duration in ms.
* @return {string} The formatted duration.
*/
historian.time.formatDuration = function(duration) {
var ms = duration % historian.time.MSECS_IN_SEC;
var s = Math.floor(
(duration / historian.time.MSECS_IN_SEC) % historian.time.SECS_IN_MIN);
var m = Math.floor((duration /
(historian.time.MSECS_IN_SEC * historian.time.SECS_IN_MIN)) %
historian.time.MINS_IN_HOUR);
var h = Math.floor((duration / (historian.time.MSECS_IN_SEC *
historian.time.SECS_IN_MIN * historian.time.MINS_IN_HOUR)));
var formatted = '';
if (h > 0) {
formatted += h + 'h ';
}
if (m > 0 || h > 0) {
formatted += m + 'm ';
}
if (s > 0 || m > 0 || h > 0) {
formatted += s + 's ';
}
if (ms > 0 || formatted.length === 0) {
// Some of the ms would have been converted from microseconds and would
// therefore have fractional components. Only show decimals if there is
// a fractional component.
if (Math.round(ms) !== ms) {
ms = ms.toFixed(2);
}
formatted += ms + 'ms';
}
return formatted.trim();
};
<file_sep>#!/bin/bash
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
CLOSURE_COMPILER_URL="http://dl.google.com/closure-compiler/compiler-20150315.zip"
ERROR="
wget is not installed, could not download the closure compiler. Please install wget and rerun this script.
For downloading the closure compiler without wget,
please manually download the closure compiler code from $CLOSURE_COMPILER_URL
and unzip into the third_party/closure-compiler/ directory, then rerun this script.
"
if [ "$1" == "--rebuild_all" ];
then
rm -r third_party
rm -r compiled
fi
mkdir -p third_party
mkdir -p compiled
# Download closure library.
if [ ! -d "third_party/closure-library" ]; then
git clone https://github.com/google/closure-library third_party/closure-library
fi
# Download closure compiler.
if [ ! -d "third_party/closure-compiler" ]; then
wget --directory-prefix=third_party/closure-compiler "$CLOSURE_COMPILER_URL"
if [ $? -ne 0 ]; then
echo "$ERROR"
else
unzip third_party/closure-compiler/compiler-20150315.zip -d third_party/closure-compiler
fi
fi
# Generate compiled Javascript runfiles.
third_party/closure-library/closure/bin/build/depswriter.py --root="third_party/closure-library/closure/goog" --root_with_prefix="js ../../../../js" > compiled/historian_deps-runfiles.js
# Generate optimized version of the Javascript runfiles.
java -jar third_party/closure-compiler/compiler.jar --closure_entry_point historian.Historian \
--js js/*.js \
--js third_party/closure-library/closure/goog/base.js \
--js third_party/closure-library/closure/goog/**/*.js \
--only_closure_dependencies \
--generate_exports \
--js_output_file compiled/historian-optimized.js \
--compilation_level SIMPLE_OPTIMIZATIONS
| c5ddb4f4c507cd585bc82e281650e3ca716b043d | [
"JavaScript",
"Go",
"Markdown",
"Shell"
] | 18 | Go | recoverlee/battery-historian | 593d011dd7dc086026c6f135204111ef7d5350bc | 95425423b3a578b71958ba4794ab7852151643ba |
refs/heads/master | <file_sep>import inputs
import functions as f
def main():
print(' ----------- Cartola ----------- ')
sair = 'n'
while sair != 's':
print('1) Listar todos os clubes')
print('2) Serie A')
print('3) Outros clubes')
print('4) Classificação brasileirão')
print('5) Próximas partidas')
print('6) Esquemas tácitos')
opc = inputs.opcoes(['1', '2', '3', '4', '5', '6'], 'Digite a opção desejada: ')
if opc == '1':
f.listarClubes()
elif opc == '2':
f.serieA()
elif opc == '3':
f.serieB()
elif opc == '4':
f.classificacao()
elif opc == '5':
f.partidas()
elif opc == '6':
f.esquemas()
if __name__ == '__main__':
main()
<file_sep>import requests
URL_BASE = 'https://api.cartolafc.globo.com/'
def get(params):
response = requests.get(URL_BASE + params)
if response.status_code == 200:
return response.json()
else:
return 'Erro ao cunsumir API.'<file_sep>import rest_http as http
def listarClubes():
data = dict(http.get('clubes'))
print('---------- Clubes ----------')
for i in data:
print(data[i]['nome'])
print('-------------------------------------------')
def serieA():
data = dict(http.get('clubes'))
print('---------- Serie A ----------')
for i in data:
if data[i].get('posicao', '') == '':
continue
else:
print(data[i]['nome'])
print('-------------------------------------------')
def serieB():
data = dict(http.get('clubes'))
print('---------- Serie B ----------')
for i in data:
if data[i].get('posicao', '') != '':
continue
else:
print(data[i]['nome'])
print('-------------------------------------------')
def classificacao():
data = dict(http.get('clubes'))
print('---------- Classificação Serie A ----------')
clubes = []
for i in data:
if data[i].get('posicao', '') == '':
continue
else:
clubes.append(data[i])
clubes = sorted(clubes, key=lambda k: k['posicao'])
for i in clubes:
print(str(i['posicao']) + 'º - ' + i['nome'])
print('-------------------------------------------')
def partidas():
data = dict(http.get('partidas'))
clubes = []
times = data['clubes']
for i in times:
time = {}
time['nome'] = times[i]['nome']
time['id'] = times[i]['id']
clubes.append(time)
partidas = data['partidas']
print('---------- Partidas ----------')
for i in partidas:
mandante = equipe(clubes, i['clube_casa_id'])
pos_mandante = i['clube_casa_posicao']
visitante = equipe(clubes, i['clube_visitante_id'])
pos_visitante = i['clube_visitante_posicao']
local = i['local']
print(str(pos_mandante) + 'º ' + mandante + ' x ' + str(pos_visitante) + 'º ' + visitante)
data_partida = i['partida_data'][:-3]
dataHora = data_partida.split(' ')
num_datas = dataHora[0].split('-')
data_partida = '(' + num_datas[2] + '/' + num_datas[1] + '/' + num_datas[0] + ' ' + dataHora[1] + ')'
print('local:', local, data_partida)
print('- - - - - - - - - - - - - ')
print('------------------------------------------')
def equipe(clubes, id):
for i in clubes:
if id == i['id']:
return i['nome']
def esquemas():
data = http.get('esquemas')
print('---------- Esquemas ----------')
for i in data:
print('Esquema:', i['nome'])
taticas(i['nome'])
print('-------------------------------------------')
def taticas(tatica):
if tatica == '3-4-3':
print('ATA ATA ATA')
print('')
print('MEI MEI')
print('')
print(' MEI MEI')
print('')
print(' ZAG ZAG ZAG')
print('')
print(' GOL')
print('---------------')
elif tatica == '3-5-2':
print(' ATA ATA')
print('')
print('MEI MEI')
print('')
print(' MEI MEI')
print('')
print(' MEI')
print('')
print(' ZAG ZAG ZAG')
print('')
print(' GOL')
print('---------------')
elif tatica == '4-3-3':
print('ATA ATA ATA')
print('')
print('MEI MEI MEI')
print('')
print('ZAG ZAG ZAG ZAG')
print('')
print(' GOL')
print('---------------')
elif tatica == '4-4-2':
print(' ATA ATA')
print('')
print('MEI MEI MEI MEI')
print('')
print('ZAG ZAG ZAG ZAG')
print('')
print(' GOL')
print('---------------')
elif tatica == '4-5-1':
print(' ATA')
print('')
print('MEI MEI MEI MEI')
print('')
print(' MEI')
print('')
print('ZAG ZAG ZAG ZAG')
print('')
print(' GOL')
print('---------------')
elif tatica == '5-3-2':
print(' ATA ATA')
print('')
print(' MEI MEI MEI')
print('')
print('ZAG ZAG ZAG ZAG ZAG')
print('')
print(' GOL')
print('---------------')
elif tatica == '5-4-1':
print(' ATA')
print('')
print(' MEI MEI MEI MEI')
print('')
print('ZAG ZAG ZAG ZAG ZAG')
print('')
print(' GOL')
print('---------------')<file_sep>import operator
def flotas(text):
validacao = True
while validacao:
try:
num = input(text)
if operator.contains(num, ','):
print("Use '.' ao invés de ','")
continue
num = float(num)
validacao = False
except:
print('Formato não suportado, digite somente números.')
return num
def ints(text):
validacao = True
while validacao:
try:
num = input(text)
if operator.contains(num, ',') or operator.contains(num, '.'):
print('Digite somente números inteiros.')
continue
num = int(num)
validacao = False
except:
print('Formato não suportado, digite somente números.')
return num
def opcoes(list, text):
while True:
if text == '':
text = 'Digite a opção desejada: '
opc = input(text)
if opc in list:
return opc
else:
print('Não é uma opção valida')
continue
| 12b4109435ca67d4421b8cf816269ddbf68c7700 | [
"Python"
] | 4 | Python | felipe-rosa94/consumindo-api-cartola-fc | f51aa548399c07e9d6ce1cc94cccdf844fde5a81 | 78e139af98685fb1e8bed778547d045d80731642 |
refs/heads/master | <repo_name>Messoras/Live2017Links<file_sep>/script/c8512558.lua
--希望皇オノマトピア
--Utopic Onomatopeia
--Scripted by Logical Nonsense and AlphaKretin
local s,id=GetID()
function s.initial_effect(c)
--Special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetCountLimit(1,id)
e1:SetRange(LOCATION_MZONE)
e1:SetTarget(s.sptg)
e1:SetOperation(s.spop)
c:RegisterEffect(e1)
--Add setcode
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e2:SetCode(EFFECT_ADD_SETCODE)
e2:SetValue(0x54)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetValue(0x59)
c:RegisterEffect(e3)
local e4=e2:Clone()
e4:SetValue(0x82)
c:RegisterEffect(e4)
local e5=e2:Clone()
e5:SetValue(0x8f)
c:RegisterEffect(e5)
end
function s.spfilter(c,e,tp)
return c:IsType(TYPE_MONSTER) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE)
and (c:IsSetCard(0x54) or c:IsSetCard(0x59) or c:IsSetCard(0x82) or c:IsSetCard(0x8f)) and not c:IsCode(id)
end
--used for counting "too many" of each set, so exclude
--this card which you can summon multiples of
function s.resfilter(c,set)
return c:IsSetCard(set) and not c:IsCode(id)
end
function s.rescon(sg,e,tp,mg)
return aux.ChkfMMZ(#sg)(sg,e,tp,mg)
and sg:FilterCount(s.resfilter,nil,0x54)<2
and sg:FilterCount(s.resfilter,nil,0x59)<2
and sg:FilterCount(s.resfilter,nil,0x82)<2
and sg:FilterCount(s.resfilter,nil,0x8f)<2
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local g=Duel.GetMatchingGroup(s.spfilter,tp,LOCATION_HAND,0,nil,e,tp)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if chk==0 then return ft>0 and aux.SelectUnselectGroup(g, e, tp, 1, math.min(ft,4), s.rescon, chk)
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(s.spfilter,tp,LOCATION_HAND,0,nil,e,tp)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if #g>0 and ft>0 then
if Duel.IsPlayerAffectedByEffect(tp,CARD_BLUEEYES_SPIRIT) then ft=1 end
local sg=aux.SelectUnselectGroup(g, e, tp, 1, math.min(ft,4), s.rescon, 1, tp, HINTMSG_SPSUMMON)
if #sg>0 then
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP_DEFENSE)
end
end
local ge1=Effect.CreateEffect(e:GetHandler())
ge1:SetType(EFFECT_TYPE_FIELD)
ge1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
ge1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
ge1:SetTargetRange(1,0)
ge1:SetTarget(s.splimit)
ge1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(ge1,tp)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CLIENT_HINT+EFFECT_FLAG_OATH)
e2:SetDescription(aux.Stringid(id,5))
e2:SetReset(RESET_PHASE+PHASE_END)
e2:SetTargetRange(1,0)
Duel.RegisterEffect(e2,tp)
end
function s.splimit(e,c,sump,sumtype,sumpos,targetp,se)
return not c:IsType(TYPE_XYZ) and c:IsLocation(LOCATION_EXTRA)
end
| 02b9bb8584020c4b3f06bf274d04ee82d5b96aa0 | [
"Lua"
] | 1 | Lua | Messoras/Live2017Links | 6cf27c798bb086a2de0c57a8b039704e5c37f8d3 | 031c4ea4277eb5176dda97ce4b953d1799a1dd7b |
refs/heads/main | <repo_name>travelbeeee/java-subwayMapPjt<file_sep>/src/main/java/subway/domain/Validator.java
package subway.domain;
public class Validator {
}
<file_sep>/src/main/java/subway/domain/Station.java
package subway.domain;
import java.util.ArrayList;
public class Station {
private String name;
private ArrayList<Line> lines = new ArrayList<>();
public Station(String name) {
this.name = name;
}
public String getName() {
return name;
}
public ArrayList<Line> getLines(){
return lines;
}
// 추가 기능 구현
public void addLine(Line line) {
this.lines.add(line);
}
public void removeLine(Line line) {
this.lines.remove(line);
}
}
<file_sep>/src/main/java/subway/domain/View.java
package subway.domain;
public class View {
public static void printMainMenu(){
System.out.println("## 메인 화면");
System.out.println("1. 역 관리");
System.out.println("2. 노선 관리");
System.out.println("3. 구간 관리");
System.out.println("4. 지하철 노선도 출력");
System.out.println("Q 종료");
System.out.println();
}
public static void printStationManageMenu(){
System.out.println("## 역 관리 화면");
System.out.println("1. 역 등록");
System.out.println("2. 역 삭제");
System.out.println("3. 역 조회");
System.out.println("B. 돌아가기");
System.out.println();
}
public static void printLineManageMenu(){
System.out.println("## 노선 관리 화면");
System.out.println("1. 노선 등록");
System.out.println("2. 노선 삭제");
System.out.println("3. 노선 조회");
System.out.println("B. 돌아가기");
System.out.println();
}
public static void printSectionManageMenu(){
System.out.println("## 구간 관리 화면");
System.out.println("1. 구간 등록");
System.out.println("2. 구간 삭제");
System.out.println("B. 돌아가기");
System.out.println();
}
}
<file_sep>/src/main/java/subway/Application.java
package subway;
import subway.domain.LineRepository;
import subway.domain.StationRepository;
import subway.domain.View;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
// TODO: 프로그램 구현
LineRepository lineRepository = new LineRepository();
StationRepository stationRepository = new StationRepository();
init(lineRepository, stationRepository);
String choice;
}
private static void init(LineRepository lineRepository, StationRepository stationRepository) {
String[] nameList = {"교대역", "강남역", "역삼역", "남부터미널역", "양재역", "양재시민의숲역", "매봉역"};
for (String s : nameList) {
stationRepository.addStation(s);
}
}
}
<file_sep>/src/main/java/subway/domain/LineRepository.java
package subway.domain;
import java.util.*;
public class LineRepository {
private static final List<Line> lines = new ArrayList<>();
public static List<Line> lines() {
return Collections.unmodifiableList(lines);
}
public static void addLine(String name, Station startStation, Station endStation) {
Optional<Line> findLine = findLineByName(name);
if (findLine.isPresent()) {
Logger.error("이미 존재하는 노선 이름입니다.");
return;
}
if(name.length() < 2){
Logger.error("노선 이름은 2글자 이상이어야합니다.");
return;
}
Line newLine = new Line(name);
newLine.addStation(startStation); // 양방향 추가
newLine.addStation(endStation); // 양방향 추가
lines.add(newLine);
}
public static boolean deleteLineByName(String name) {
Optional<Line> findLine = findLineByName(name);
if (findLine.isEmpty()) {
Logger.error("존재하지 않는 노선입니다.");
return false;
}
Line line = findLine.get();
line.getStations().stream().forEach(s -> line.removeStation(s)); // 역에서도 노선을 삭제
return lines.remove(line);
}
public static Optional<Line> findLineByName(String name){
return lines.stream().filter(l -> l.getName().equals(name)).findAny();
}
}
| 405fa9f2595c5010b087194b1db9854cb3fd2506 | [
"Java"
] | 5 | Java | travelbeeee/java-subwayMapPjt | 541d5d2450c55e57b45a504f6e28fea128759352 | d70eba096accd56148ccde2b8b0dc7405a02cb1b |
refs/heads/master | <repo_name>AShar97/Python-Codes<file_sep>/sort.py
#! /usr/bin/python3
import time
import random
def insertsort(a):
for j in range(1, len(a)):
key = a[j]
i = j - 1
while i >= 0 and a[i] > key:
a[i+1] = a[i]
i = i - 1
a[i+1] = key
def mergesort(a,p,q):
if p < q:
r = (p+q)//2
mergesort(a, p, r)
mergesort(a, r+1, q)
merge(a, p, r, q)
def merge(a,p,r,q):
f = a[p:r+1]
s = a[r+1:q+1]
f.append(float("inf"))
s.append(float("inf"))
i,j = 0,0
for k in range(p,q+1):
if f[i] <= s[j]:
a[k] = f[i]
i = i+1
else:
a[k] = s[j]
j = j+1
size = int(input('Size? '))
a = []
b = []
for i in range(size):
a.append(random.randint(0,1000))
b.append(a[i])
timei = time.time()
insertsort(a)
timei = time.time() - timei
timem = time.time()
mergesort(b, 0, size-1)
timem = time.time() - timem
print('Time for insert sort = ', timei)
print(a)
print('Time for merge sort = ', timem)
print(b)
<file_sep>/README.md
# Python-Codes
This repository comprises of all the python codes practiced in Data-Structure and Algorithms Laboratory with Object Oriented Programming.
<file_sep>/test_sort.py
from time import time
from random import randint
import matplotlib.pyplot as plt
def insertsort(a):
for j in range(1, len(a)):
key = a[j]
i = j - 1
while i >= 0 and a[i] > key:
a[i+1] = a[i]
i = i - 1
a[i+1] = key
def mergesort(a,p,q):
if p < q:
r = (p+q)//2
mergesort(a, p, r)
mergesort(a, r+1, q)
merge(a, p, r, q)
def merge(a,p,r,q):
f = a[p:r+1]
s = a[r+1:q+1]
f.append(float("inf"))
s.append(float("inf"))
i,j = 0,0
for k in range(p,q+1):
if f[i] <= s[j]:
a[k] = f[i]
i = i+1
else:
a[k] = s[j]
j = j+1
# size = int(input('Size difference? '))
case = int(input('#Cases? '))
trial = int(input('#Trials? '))
time_i = []
time_m = []
for n in range(case+1):
# timei, timem = 0, 0
time_i.append(0)
time_m.append(0)
for m in range(trial):
a = []
b = []
c = []
d = []
for i in range(n):
key = randint(0,1000)
a.append(key)
b.append(key)
c.append(key)
d.append(key)
del(key)
timei1 = time()
insertsort(a)
timei1 = (time() - timei1)
timem1 = time()
mergesort(b, 0, n-1)
timem1 = (time() - timem1)
timem2 = time()
mergesort(c, 0, n-1)
timem2 = (time() - timem2)
timei2 = time()
insertsort(d)
timei2 = (time() - timei2)
time_i[n] += ((timei1+timei2)/(2*trial))
time_m[n] += ((timem1+timem2)/(2*trial))
del(timei1,timei2,timem1,timem2)
# time_i.append((timei1+timei2)/(2*trial))
# time_m.append((timem1+timem2)/(2*trial))
# print('Length= ',n,' : Time(insert)= ',time_i[n],' ; Time (merge)= ',time_m[n])
plt.plot(time_i, 'r-')
plt.plot(time_m, 'b-')
plt.title('Time of Sorting\tR:Insert\tB:Merge')
plt.xlabel('Size')
plt.ylabel('Time')
plt.grid(True)
plt.show()
<file_sep>/heap_2.py
#heap module for priority-queue
def parent(i):
return (i - 1)//2
def left(i):
return (2*i + 1)
def right(i):
return (2*i + 2)
def max_heapify(a, i, length):
l = left(i)
r = right(i)
largest = i
if (l < length and a[largest] < a[l]):
largest = l
if (r < length and a[largest] < a[r]):
largest = r
if (largest != i):
a[i],a[largest] = a[largest],a[i]
max_heapify(a, largest, length)
def build_max_heap(a, length):
for i in range(parent(length - 1), -1, -1):
max_heapify(a, i, length)
def heap_sort(a):
length = len(a)
build_max_heap(a, length)
for i in range(length - 1):
a[0],a[length - 1 - i] = a[length - 1 - i],a[0]
# {decrease size} len(a)--
# max_heapify(a[:(len(a) - 1 - i)],0)
# a_ = a[:(len(a) - 1 - i)]
# max_heapify(a_,0)
# a[:(len(a) - 1 - i)] = a_
max_heapify(a, 0, (length - 1 - i))
'''
a = [1,3,5,2,7,4,0]
heap_sort(a)
print(a)<file_sep>/oop.py
class Matrix(object):
#Construction
def __init__(self, h, w):
if (h == 1):
self.data = [0 for x in range(w)]
elif (w == 1):
self.data = [0 for x in range(h)]
else:
self.data = [[0 for x in range(w)] for y in range(h)]
self.h = h
self.w = w
def __add__(self, mat): # self + mat
# if (self.h, self.w == mat.h, mat.w):
ret = Matrix(self.h, self.w)
for i in range(self.h):
for j in range(self.w):
ret.data[i][j] = (self.data[i][j] + mat.data[i][j])
return ret
def __mul__(self, mat): # self * mat
ret = Matrix(self.h, mat.w)
for i in range(self.h):
for j in range(mat.w):
for k in range(self.w):
ret.data[i][j] += (self.data[i][k] * mat.data[k][j])
return ret
m1 = Matrix(2,2)
m2 = Matrix(2,2)
m1.data = [[1,2],[3,4]]
m2.data = [[5,6],[7,8]]
m_sum = Matrix(2,2)
m_sum = m1 + m2
print(m_sum.data)
'''
m3 = Matrix(2,1)
m4 = Matrix(1,2)
m3.data = [1,2]
m4.data = [1,2]
'''
m3 = Matrix(2,2)
m4 = Matrix(2,2)
m3.data = [[1,0],[0,1]]
m4.data = [[1,0],[0,1]]
m_product = Matrix(2,2)
m_product = m3 * m4
print(m_product.data)
<file_sep>/eg.py
def left(i):
return (2*i+1)
def right(i):
return (2*i+2)
def max_heapify(a,i):
l=left(i)
r=right(i)
largest=i
if l<len(a) and a[i]<a[l]:
largest=l
if r<len(a) and a[largest]<a[r]:
largest=r
if(largest!=i):
a[i],a[largest]=a[largest],a[i]
max_heapify(a,largest)
def build_max_heap(a):
for i in range((len(a)//2)-1,-1,-1):
max_heapify(a,i)
def heap_sort(a):
build_max_heap(a)
for i in range(len(a)-1):
a[0],a[len(a)-1-i]=a[len(a)-1-i],a[0]
b=list()
b=a[0:len(a)-1-i]
max_heapify(b,0)
a[0:len(a)-1-i]=b
return a
a = [1,3,5,2,7,4,0]
r = heap_sort(a)
print(r)<file_sep>/priority_queue.py
from heap_2 import *
#import heap_2
class prq():
def __init__(self, a):
self.heap = a
self.n = len(a)
build_max_heap(self.heap, self.n)
def maximum(self):
return self.heap[0]
def remove_maximum(self): #may include list.pop()
if len(self.heap) < 1:
raise Exception ("Heap underflow")
else:
self.heap[0], self.heap[self.n - 1] = self.heap[self.n - 1], self.heap[0]
self.n -= 1
max_heapify(self.heap, 0, self.n)
return self.heap[self.n]
def increase_key(self, i):
while (i > 0 and self.heap[i] > self.heap[parent(i)]):
#if (self.heap[i] > self.heap[parent(i)]):
self.heap[i], self.heap[parent(i)] = self.heap[parent(i)], self.heap[i]
i = parent(i)
def insert(self, x):
if (self.n < len(self.heap)):
self.heap[self.n] = x
elif(self.n == len(self.heap)):
self.heap.append(x)
self.n += 1
self.increase_key(self.n - 1)
def print_heap(self):
print(self.heap[:self.n])
'''
a = prq([1,2,3,4,5,6,7,8,9])
a.insert(0)
a.print_heap()
print(a.maximum())
a.insert(11)
a.print_heap()
build_max_heap(a.heap, a.n)
a.print_heap()
print(a.maximum())
a.remove_maximum()
a.print_heap()<file_sep>/mult.py
import cmath
import math
def vmult(a,b):
c = []
for i in range(len(a)):
c.append(a[i]*b[i])
return c
def omult(a,b):
c = [0] * ((len(a)-1)+(len(b)-1)+1)
for i in range(len(a)):
for j in range(len(b)):
c[i+j] = c[i+j] + (a[i]*b[j])
return c
def fft(a,w):
if (len(a) == 1):
return a
s = fft(a[::2],(w*w))
s1 = fft(a[1::2],(w*w))
r = [0] * (len(a))
for j in range(int(len(a)/2)):
r[j] = s[j] + ((w**j)*s1[j])
r[j+int(len(a)/2)] = s[j] - ((w**j)*s1[j])
return r
a = eval(input('Polynomial a: '))
b = eval(input('Polynomial b: '))
#Ordinary multiplication of polynomial
c_o = omult(a,b)
print('c_o: ', c_o)
#FFT
size = (len(a)-1)+(len(b)-1)+1
'''
if (len(a) >= len(b)):
key = len(a)
b.extend([0] * (key-len(b)))
else:
key = len(b)
a.extend([0] * (key-len(a)))
i = 1
while key < i:
i = i * 2
i = i * 2
'''
#i = 2 * key
i = 2**(math.ceil(math.log2(max(len(a), len(b)))) + 1)
print(i)
a.extend([0] * (i - len(a)))
b.extend([0] * (i - len(b)))
print(a)
print(b)
w = cmath.exp((2 * cmath.pi * 1j) / (i))
a1 = fft(a, w)
b1 = fft(b, w)
c1 = vmult(a1,b1)
#w1 = cmath.exp((-2 * cmath.pi * 1j) / (i))
c_fft = fft(c1, 1/w)[:size]
c_fft = [x/i for x in c_fft]
print('c_fft: ', c_fft)
<file_sep>/test_mult.py
from time import time
from random import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import cmath
import math
def vmult(a,b):
c = []
for i in range(len(a)):
c.append(a[i]*b[i])
return c
def omult(a,b):
c = [0] * ((len(a)-1)+(len(b)-1)+1)
for i in range(len(a)):
for j in range(len(b)):
c[i+j] = c[i+j] + (a[i]*b[j])
return c
def fft(a,w):
if (len(a) == 1):
return a
s = fft(a[::2],(w*w))
s1 = fft(a[1::2],(w*w))
r = [0] * (len(a))
for j in range(int(len(a)/2)):
r[j] = s[j] + ((w**j)*s1[j])
r[j+int(len(a)/2)] = s[j] - ((w**j)*s1[j])
return r
def fftmult(a,b):
size = (len(a)-1)+(len(b)-1)+1
i = 2**(math.ceil(math.log2(max(len(a),len(b)))) + 1)
a.extend([0] * (i - len(a)))
b.extend([0] * (i - len(b)))
w = cmath.exp((2 * cmath.pi * 1j) / i)
c = fft(vmult(fft(a, w),fft(b, w)), 1/w)[:size]
c = [x/i for x in c]
return c
l = int(input('Max-degree : ')) + 1
t_o = [x[:] for x in [[0] * l] * l]
t_fft = [x[:] for x in [[0] * l] * l]
for i in range(1,l):
for j in range(1,l):
a = []
b = []
for m in range(i):
a.append(random())
for n in range(j):
b.append(random())
#Ordinary multiplication of polynomial
t_o[i][j] = time()
c_o = omult(a,b)
t_o[i][j] = time() - t_o[i][j]
#FFT multiplication of polynomial
t_fft[i][j] = time()
c_fft = fftmult(a,b)
t_fft[i][j] = time() - t_fft[i][j]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X = [x[:] for x in [[0] * l] * l]
Y = [x[:] for x in [[0] * l] * l]
for i in range(l):
for j in range(l):
X[i][j] = i
Y[i][j] = j
Z = t_o
Axes3D.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
Z = t_ttf
Axes3D.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
plt.title('Time of Multiplying')
plt.tight_layout()
plt.show()
'''
#X, Y, Z = axes3d.get_test_data(0.05)
print(X)
print(Y)
#print(Z)
'''
print(t_o)
print('\n\n\n\n\n\n')
print(t_fft)
| 3267d108b559733167b90f4bb02a19dea5d41ff0 | [
"Markdown",
"Python"
] | 9 | Python | AShar97/Python-Codes | 24407f24c93f46197e784aefce5fb8e7d5f769a6 | 3c1bdae6c45a26dd373f7ea24e5cae653d1688f3 |
refs/heads/master | <file_sep><?php
namespace App\Form;
use App\Entity\Tweet;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
class TweetType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('tweet', TextareaType::class, [
'attr' => [
'rows' => 4
],
'constraints' => [
new NotBlank([
'message' => 'Your tweet may not be blank.'
]),
new Length([
'max' => 255,
'min' => 5,
'maxMessage' => 'Your tweet can only be {{ limit }} character long',
'minMessage' => 'Your tweet must be at least {{ limit }} characters long'
]),
]
])
->add('submit', SubmitType::class, [
'label' => "Tweet!"
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Tweet::class,
]);
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Repository\TweetRepository;
use App\Repository\UserRepository;
use Knp\Component\Pager\PaginatorInterface;
class MainController extends AbstractController
{
/**
* @Route("/", name="main")
*/
public function index(Request $request, TweetRepository $tweetRepository, PaginatorInterface $paginator) {
//$entityManager = $this->getDoctrine()->getManager();
$tweetsQuery = $tweetRepository->findBy([], ['created' => 'DESC']);
$tweets = $paginator->paginate(
$tweetsQuery, /* query NOT result */
$request->query->getInt('page', 1)/*page number*/,
5/*limit per page*/
);
return $this->render('main/index.html.twig', [
'tweets' => $tweets,
]);
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\Tweet;
use App\Entity\Comment;
use App\Entity\User;
use App\Form\CommentType;
use App\Form\TweetType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Repository\TweetRepository;
use Knp\Component\Pager\PaginatorInterface;
class TweetController extends AbstractController
{
/**
* @Route("/tweet/{id}", name="app_tweet", requirements={"id"="\d+"})
*/
public function index(Tweet $tweet, Request $request)
{
$entityManager = $this->getDoctrine()->getManager();
$renderedForm = null;
if($this->isGranted("IS_AUTHENTICATED_FULLY"))
{
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$comment->setUser($this->getUser());
$comment->setTweet($tweet);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
return $this->redirectToRoute("app_tweet", ['id' => $tweet->getId()]);
}
$renderedForm = $form->createView();
}
$tweet->setViews($tweet->getViews() + 1);
$entityManager->persist($tweet);
$entityManager->flush();
return $this->render('tweet/index.html.twig', [
'tweet' => $tweet,
'commentForm' => $renderedForm,
]);
}
/**
* @Route("/my_tweets", name="app_my_tweets", requirements={"id"="\d+"})
*/
public function myTweets(Request $request, UserInterface $user, TweetRepository $tweetRepository, PaginatorInterface $paginator)
{
$userId = $user->getId();
if($this->isGranted("IS_AUTHENTICATED_FULLY"))
{
$tweetsQuery = $tweetRepository->findBy(['user' => $userId], ['created' => 'DESC']);
$tweets = $paginator->paginate(
$tweetsQuery, /* query NOT result */
$request->query->getInt('page', 1)/*page number*/,
5/*limit per page*/
);
return $this->render('main/index.html.twig', [
'tweets' => $tweets,
]);
}
return $this->redirectToRoute("main");
}
/**
* @Route("/tweets/{user.id}", name="app_user_tweets", requirements={"id"="\d+"})
*/
public function userTweets(TweetRepository $tweetRepository, Request $request, PaginatorInterface $paginator)
{
$userId = $request->query->get('id');
$tweets = $tweetRepository->findBy(['user' => $userId], ['created' => 'DESC']);
$tweets = $paginator->paginate(
$tweets, /* query NOT result */
$request->query->getInt('page', 1)/*page number*/,
5/*limit per page*/
);
return $this->render('main/index.html.twig', [
'tweets' => $tweets,
]);
}
/**
* @Route("/tweet/post", name="app_tweet_post")
* @IsGranted("IS_AUTHENTICATED_FULLY")
*/
public function postTweet(Request $request)
{
$tweet = new Tweet();
$form = $this->createForm(TweetType::class, $tweet);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$tweet->setUser($this->getUser());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($tweet);
$entityManager->flush();
return $this->redirectToRoute("app_tweet", ['id' => $tweet->getId()]);
}
return $this->render('tweet/tweet.html.twig', [
'tweetForm' => $form->createView(),
]);
}
/**
* @Route("/tweet/delete/{id}/{userId}", name="delete_tweet" )
*/
public function deleteTweet($id, $userId, AuthorizationCheckerInterface $authChecker, UserInterface $user)
{
$user = $this->getUser()->getId();
$entityManager = $this->getDoctrine()->getManager();
$tweet = $entityManager->getRepository(Tweet::class)->find($id);
if ($authChecker->isGranted('ROLE_ADMIN') || (int)$userId === (int)$user) {
if (!$tweet) {
throw $this->createNotFoundException(
'No tweet found for id '.$id
);
}
$entityManager->remove($tweet);
$entityManager->flush();
}
return $this->redirectToRoute("main");
}
}
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: May 29, 2019 at 12:33 AM
-- Server version: 10.1.40-MariaDB
-- PHP Version: 7.3.5
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `twitter-test`
--
-- --------------------------------------------------------
--
-- Table structure for table `comment`
--
CREATE TABLE `comment` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`tweet_id` int(11) NOT NULL,
`body` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`created` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `migration_versions`
--
CREATE TABLE `migration_versions` (
`version` varchar(14) COLLATE utf8mb4_unicode_ci NOT NULL,
`executed_at` datetime NOT NULL COMMENT '(DC2Type:datetime_immutable)'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `migration_versions`
--
INSERT INTO `migration_versions` (`version`, `executed_at`) VALUES
('20190528104915', '2019-05-28 21:56:50'),
('20190528130139', '2019-05-28 21:56:50'),
('20190528132954', '2019-05-28 21:56:50');
-- --------------------------------------------------------
--
-- Table structure for table `tweet`
--
CREATE TABLE `tweet` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`tweet` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`views` int(11) NOT NULL,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `tweet`
--
INSERT INTO `tweet` (`id`, `user_id`, `tweet`, `views`, `created`) VALUES
(8, 1, 'I am Groot. I am Groot. I am Groot. I am Groot. I am Groot. We are Groot. I am Groot. We are Groot. I am Groot. I am Groot. We are Groot. We are Groot. We are Groot. I am Groot. We are Groot. We are Groot.', 6, '2019-05-29 00:04:19'),
(9, 1, 'I am Groot. I am Groot. I am Groot.', 2, '2019-05-29 00:04:34'),
(10, 1, 'Hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor.', 5, '2019-05-29 00:06:36'),
(11, 2, 'Hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor', 7, '2019-05-29 00:07:08'),
(12, 2, 'Yes. Why? Why is this still under discussion? No, no no no no no, I don\'t like him. I don\'t care who he knows. We\'re supposed to trust him with our product? Big Man. Big Generalissimo! Big fry cook is more like it...', 3, '2019-05-29 00:08:48'),
(13, 2, 'Did you not plan for this contingency? I mean the Starship Enterprise had a self-destruct button. I\'m just saying. Yeah, you do seem to have a little \'shit creek\' action going. Hey, nobody appreciates a passionate woman more than I do.', 2, '2019-05-29 00:09:31'),
(14, 2, 'We are Groot. I am Groot. I am Groot. We are Groot. We are Groot. We are Groot. We are Groot. I am Groot. We are Groot. We are Groot. I am Groot. I am Groot. We are Groot. We are Groot.', 3, '2019-05-29 00:10:04'),
(15, 1, 'I am Groot. I am Groot. I am Groot. I am Groot. I am Groot. We are Groot. I am Groot. We are Groot. I am Groot. I am Groot. We are Groot. We are Groot. We are Groot. I am Groot. We are Groot. We are Groot.', 6, '2019-05-29 00:04:19'),
(16, 1, 'I am Groot. I am Groot. I am Groot.', 2, '2019-05-29 00:04:34'),
(17, 1, 'Hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor.', 5, '2019-05-29 00:06:36'),
(18, 2, 'Hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor hodor hodor hodor hodor hodor hodor hodor hodor. Hodor', 7, '2019-05-29 00:07:08'),
(19, 2, 'Yes. Why? Why is this still under discussion? No, no no no no no, I don\'t like him. I don\'t care who he knows. We\'re supposed to trust him with our product? Big Man. Big Generalissimo! Big fry cook is more like it...', 3, '2019-05-29 00:08:48'),
(20, 2, 'Did you not plan for this contingency? I mean the Starship Enterprise had a self-destruct button. I\'m just saying. Yeah, you do seem to have a little \'shit creek\' action going. Hey, nobody appreciates a passionate woman more than I do.', 2, '2019-05-29 00:09:31'),
(21, 2, 'We are Groot. I am Groot. I am Groot. We are Groot. We are Groot. We are Groot. We are Groot. I am Groot. We are Groot. We are Groot. I am Groot. I am Groot. We are Groot. We are Groot.', 3, '2019-05-29 00:10:04');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`email` varchar(180) COLLATE utf8mb4_unicode_ci NOT NULL,
`roles` longtext COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '(DC2Type:json)',
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`id`, `email`, `roles`, `password`) VALUES
(1, '<EMAIL>', '[\"ROLE_USER\"]', '$argon2i$v=19$m=1024,t=2,p=2$YVNkZUVZLmlzOGJvQXoyQw$bMYDnxbFLruoXbtiSK58PLbzbW7AmNsJ8Njfk3wzeIE'),
(2, '<EMAIL>', '[\"ROLE_USER\"]', '$argon2i$v=19$m=1024,t=2,p=2$emRaU1l5WEptbnU4Z0Q3ZA$x5vYENNtL7QYlPpv4GTO+EaKvvtaVMjBEUfk8FUn4dQ');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `comment`
--
ALTER TABLE `comment`
ADD PRIMARY KEY (`id`),
ADD KEY `IDX_9474526CA76ED395` (`user_id`),
ADD KEY `IDX_9474526C1041E39B` (`tweet_id`);
--
-- Indexes for table `migration_versions`
--
ALTER TABLE `migration_versions`
ADD PRIMARY KEY (`version`);
--
-- Indexes for table `tweet`
--
ALTER TABLE `tweet`
ADD PRIMARY KEY (`id`),
ADD KEY `IDX_3D660A3BA76ED395` (`user_id`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `UNIQ_8D93D649E7927C74` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `comment`
--
ALTER TABLE `comment`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `tweet`
--
ALTER TABLE `tweet`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `comment`
--
ALTER TABLE `comment`
ADD CONSTRAINT `FK_9474526C1041E39B` FOREIGN KEY (`tweet_id`) REFERENCES `tweet` (`id`),
ADD CONSTRAINT `FK_9474526CA76ED395` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`);
--
-- Constraints for table `tweet`
--
ALTER TABLE `tweet`
ADD CONSTRAINT `FK_3D660A3BA76ED395` FOREIGN KEY (`user_id`) REFERENCES `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><?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\TweetRepository")
*/
class Tweet
{
public function __construct()
{
$this->comments = new ArrayCollection();
$this->created = new \DateTime();
}
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $tweet;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="tweets")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* @ORM\Column(type="integer")
*/
private $views = 0;
/**
* @ORM\Column(type="datetime", options={"default": "CURRENT_TIMESTAMP"})
*/
private $created;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="tweet", orphanRemoval=true, fetch="EXTRA_LAZY")
*/
private $comments;
public function getId(): ?int
{
return $this->id;
}
public function getTweet(): ?string
{
return $this->tweet;
}
public function setTweet(string $tweet): self
{
$this->tweet = $tweet;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getViews(): ?int
{
return $this->views;
}
public function setViews(int $views): self
{
$this->views = $views;
return $this;
}
public function getCreated(): ?\DateTimeInterface
{
return $this->created;
}
public function setCreated(\DateTimeInterface $created): self
{
$this->created = $created;
return $this;
}
/**
* @return Collection|Comment[]
*/
public function getComments(): Collection
{
return $this->comments;
}
public function addComment(Comment $comment): self
{
if (!$this->comment->contains($comment)) {
$this->comments[] = $comment;
$comment->setComment($this);
}
return $this;
}
public function removeTweet(Comment $comment): self
{
if ($this->comments->contains($comment)) {
$this->comments->removeElement($comment);
// set the owning side to null (unless already changed)
if ($comment->getTweet() === $this) {
$comment->setTweet(null);
}
}
return $this;
}
}
<file_sep># TwitterApp
## Instalation
Git clone this project and run command in Command-line interface in the project folder.
```
https://github.com/VukasinBabic/twitterApp.git
```
After cloning, Run composer install in Command-line interface:
```
composer update
```
EDIT ENV file, here is the ENV example, change DB name, user, password etc for your environment.
ENV example:
DATABASE_URL=mysql://root:''@127.0.0.1:3306/twitter-test
###< doctrine/doctrine-bundle ###
when you create ENV file, run:
```
php bin/console doctrine:database:create
```
If you are importing database, you dont need to migrate.
```
php bin/console make:migration
php bin/console doctrine:migrations:migrate
```
After that import Database Records, from twitter-test.sql file
You can skip this part, but You need to manually set admin user in the Db:
```
ROLES: "ROLE_ADMIN"
```
If you import the database admin user is:
```
email: <EMAIL>
password: <PASSWORD>
```
After that the project should be set and working.
| bf90f535324e5c058d64a114ff2089efddd60799 | [
"Markdown",
"SQL",
"PHP"
] | 6 | PHP | VukasinBabic/twitterApp | 574e041450ccc596e102e918eb113fb652c4f7bf | 102790284f2ad97d1ed836cb30389c508834839e |
refs/heads/master | <file_sep># Hypotenuse-Calculator
takes two arguments and calculates the hypotenuse
<file_sep>/**
*
* This file produces the length of the hypotnuse when given two numbers.
*
* @author <NAME>
* Course: COMP B13
* Created: Jan 31, 2017
* Source File: Hypotenuse.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[]){
double inputOne, inputTwo, hypotenuse = 0.0;
inputOne = atof(argv[1]);
inputTwo = atof(argv[2]);
hypotenuse = sqrt(pow(inputOne,2) + pow(inputTwo,2));
printf("%.6lf", hypotenuse);
return 0;
}
| f249b9e6da0bdbc84f3389533e7b4bfd80b0ff17 | [
"Markdown",
"C"
] | 2 | Markdown | Adarksoul/Hypotenuse-Calculator | 4ebceb75e98d44fe2c75764347a8a084da61e408 | 1408e5430b2de8d419bf58466f1eb0aa8252981f |
refs/heads/master | <repo_name>ShivaniSingh1501/Aspireathon-WasteBuster<file_sep>/storyqube-dev-mobile-app-master/component/Styles.js
import { StyleSheet, Dimensions, PixelRatio, Platform } from 'react-native'
let { height, width } = Dimensions.get('window');
console.log(height);
console.log(width);
const styles = StyleSheet.create({
container: {
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (100) / 100),
flex: 1,
backgroundColor: '#0A0A22',
// ...Platform.select({
// ios: {
// marginTop: '6%',
// },
// android: {
// marginTop: 0,
// },
// }),
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignSelf: 'center'
},
containerRegistration: {
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (40) / 100),
},
leaderboardContainer: {
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
flex: 1,
//backgroundColor: '#650722',
// ...Platform.select({
// ios: {
// marginTop: '6%',
// },
// android: {
// marginTop: 0,
// },
// }),
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignSelf: 'center'
},
backgroundImage: {
position: 'absolute',
flex: 1,
resizeMode:'stretch',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (100) / 100),
},
storyContainer: {
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
flex: 1,
// backgroundColor: '#027284',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignSelf: 'center'
},
gameContainer: {
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (178) / 100),
},
reviewContainer:{
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
flex:1,
display:'flex',
flexDirection:'column',
justifyContent:'flex-start',
alignSelf:'center',
},
storyImage: {
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (100) / 100),
},
rowCenter: {
flexDirection: 'row',
justifyContent: 'center'
},
cardContainer: {
//backgroundColor:"red",
borderRadius: 20,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (14) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (36) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (75) / 100)
},
cardContent: {
flexDirection: 'column',
justifyContent: 'flex-start',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
cardHeader: {
color: 'white',
fontSize: 20,
fontWeight: 'bold',
// backgroundColor:'red',
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)
},
savedCardBlackLine: {
backgroundColor: 'black',
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (5) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
},
savedCardDown: {
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (6) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
},
savedCardDownText: {
color: '#C4C4C4',
fontWeight: 'bold',
fontSize: 14,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
savedCarddownInput: {
color: '#888888',
fontSize: 16,
textAlign: 'center',
borderWidth: 1,
height: 28,
width: 56,
borderRadius: 4,
borderColor: '#888888',
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
savedCardSave: {
height: 20,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
},
saveCardSaveBox: {
height: 17,
width: 17,
// backgroundColor:'red',
borderWidth: 1,
marginRight: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (2) / 100),
borderRadius: 1,
borderColor: 'white',
},
saveCardSaveText: {
color: 'white',
fontSize: 16,
lineHeight: 20
},
inputContainer: {
//backgroundColor:"blue",
borderBottomWidth: 1,
borderBottomColor: '#747686',
flexDirection: 'row',
justifyContent: 'space-between',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (8) / 100),
},
inputBlankContainer: {
flexDirection: 'row',
justifyContent: 'space-between'
},
inputContent: {
//backgroundColor:'yellow',
color: 'white',
fontSize: 14,
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (5.5) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (54) / 100)
},
RegistrationFatherhoodContent: {
// backgroundColor:'yellow',
color: 'white',
fontSize: 14,
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100)
},
RegistrationinputContainer: {
//backgroundColor:"blue",
borderBottomWidth: 1,
borderBottomColor: '#747686',
flexDirection: 'row',
justifyContent: 'space-between',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (9.5) / 100),
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (0) / 100)
},
RegistrationinputContent: {
//backgroundColor:'yellow',
color: 'white',
fontSize: 16,
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (69) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100)
},
RegistrationSubmitButton: {
flexDirection: 'row',
justifyContent: 'center',
alignSelf: 'center',
alignContent:'center',
backgroundColor: '#0E8EE3',
borderRadius: 10,
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (14) / 100),
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (75) / 100)
},
forgotPasswordRight: {
flexDirection: 'row',
justifyContent: 'flex-end',
// backgroundColor:'red',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)
},
cardSignButton: {
flexDirection: 'row',
justifyContent: 'center',
alignSelf: 'center',
backgroundColor: '#0E8EE3',
borderBottomLeftRadius: 20,
borderBottomRightRadius: 20,
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (14) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (75) / 100)
},
cardCreateButton: {
flexDirection: 'row',
justifyContent: 'center',
alignSelf: 'center',
backgroundColor: '#9C1941',
borderBottomLeftRadius: 20,
borderBottomRightRadius: 20,
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (14) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (75) / 100)
},
cardDown: {
flexDirection: 'row',
justifyContent: 'center',
alignSelf: 'center',
backgroundColor: '#171B35',
borderBottomLeftRadius: 20,
borderBottomRightRadius: 20,
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (14) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (65) / 100)
},
cardUp: {
flexDirection: 'row',
justifyContent: 'center',
alignSelf: 'center',
backgroundColor: '#171B35',
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (14) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (65) / 100)
},
/*************************Home styles */
flexColStart: {
flexDirection: 'column',
justifyContent: 'flex-start'
},
flexColEnd: {
flexDirection: 'column',
justifyContent: 'flex-end'
},
flexRowStart: {
flexDirection: 'row',
justifyContent: 'flex-start'
},
flexColCenter: {
flexDirection: 'column',
justifyContent: 'center'
},
flexRowCenter: {
flexDirection: 'row',
justifyContent: 'center'
},
flexColBetween: {
flexDirection: 'column',
justifyContent: 'space-between'
},
flexRowBetween: {
flexDirection: 'row',
justifyContent: 'space-between'
},
flexRowEnd: {
flexDirection: 'row',
justifyContent: 'flex-end'
},
homeTitle: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
},
homeHeader: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (5) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (88) / 100),
},
homeTitleText: {
color: 'white',
fontSize: 20,
fontWeight: 'bold',
color:"black"
},
homeRating: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
},
homeRatingText: {
color: 'white',
fontSize: 14,
marginRight: 5
},
homeGenreSeparator: {
borderRightWidth: 1,
borderRightColor: '#845136',
marginRight: 5
},
skillText: {
color: '#7BCFF0',
fontSize: 24,
fontWeight: 'bold'
},
homeCard: {
zIndex: 2,
position: 'absolute',
...Platform.select({
ios: {
shadowOffset: { height: 3 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 3,
},
}),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (50) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (70) / 100)
},
homeCard1: {
position: 'absolute',
zIndex: 1,
...Platform.select({
ios: {
shadowOffset: { height: 2 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 2,
},
}),
// opacity:.8,
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (5) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (15) / 100),
// height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (50) / 100),
// width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (60) / 100)
},
homeCard2: {
position: 'absolute',
zIndex: 0,
...Platform.select({
ios: {
shadowOffset: { height: 1 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 1,
},
}),
// opacity:.8,
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (22) / 100),
// height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (44) / 100),
// width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (42) / 100)
},
/***************************************** */
profileScreenHeader: {
flexDirection: 'row',
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (5) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (88) / 100),
justifyContent: 'space-between',
},
profileIcon: {
backgroundColor: 'white',
borderRadius: 50,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100)
},
profileName: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (5) / 100),
fontSize: 26,
lineHeight: 32,
color: 'black',
fontWeight: 'bold'
},
profileEmail: {
fontSize: 14,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (5) / 100),
lineHeight: 16,
color: 'black',
},
profileRecCard: {
// backgroundColor: '#447AC6',
borderRadius: 10,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (23) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (40) / 100),
},
profileSqCard: {
// backgroundColor: '#790462',
flexDirection: 'column',
justifyContent: 'space-between',
borderRadius: 10,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (11) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (40) / 100),
},
profileRecCardR: {
// backgroundColor: '#447AC6',
borderRadius: 10,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (4) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (23) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (40) / 100),
},
profileSqCardRU: {
// backgroundColor: '#790462',
flexDirection: 'column',
justifyContent: 'space-between',
borderRadius: 10,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (4) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (11) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (40) / 100),
},
profileSqCardRD: {
// backgroundColor: '#790462',
flexDirection: 'column',
justifyContent: 'space-between',
borderRadius: 10,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (4) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (11) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (40) / 100),
},
profileCardText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
margin: 15,
},
profileSignOut: {
flexDirection: 'column',
justifyContent: 'space-between',
borderRadius: 10,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (8) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (84) / 100),
},
subscriptionHeading: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
},
subscriptionMonthlyCard: {
// backgroundColor: '#505C7A',
borderRadius: 16,
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (27) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
resizeMode: 'stretch',
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
subscriptionYearlyCard: {
backgroundColor: '#DB383C',
borderRadius: 16,
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (27) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
resizeMode: 'stretch',
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
subscriptionTitle: {
color: 'white',
fontSize: 12,
fontWeight: 'bold',
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (7) / 100)
},
subscriptionPrice: {
color: 'white',
fontSize: 32,
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1.5) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (7) / 100),
// width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width* 70/100)
},
subscriptionPriceStrikeThrough: {
color: '#EFAFB1',
lineHeight: 45,
textDecorationLine: 'line-through',
fontSize: 16,
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1.5) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (2) / 100)
},
subscriptionPoints: {
color: 'white',
fontSize: 14,
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (0.5) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (7) / 100)
},
subscriptionText: {
color: '#0E8EE3',
fontSize: 14,
fontWeight: 'bold'
},
subscriptionContainer: {
backgroundColor: '#171B35',
position: 'absolute',
bottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
borderRadius: 8,
flexDirection: 'row',
justifyContent: 'space-between',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (8) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (84) / 100),
},
subscriptionLinkText: {
color: 'white',
fontSize: 16,
textAlign: 'left',
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
},
subscriptionLinkTextSmall: {
color: 'grey',
fontSize: 8,
textAlign: 'left',
},
subscriptionButton: {
borderRadius: 3,
marginRight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
backgroundColor: '#0E8EE3',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (30) / 100)
},
subscriptionLinkButtonText: {
color: 'white',
//lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100)
},
/********************************* */
referralHeader: {
flexDirection: 'row',
...Platform.select({
ios: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (5) / 100),
shadowOffset: { height: 2 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
elevation: 2,
},
}),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
justifyContent: 'flex-start',
},
referralBack: {
color: 'white',
fontSize: 20,
fontWeight:"bold",
marginLeft: 10,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
fontWeight: '500',
},
referralCard: {
// backgroundColor: '#B6C5D0',
...Platform.select({
ios: {
shadowOffset: { height: 2 },
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (60) / 100),
},
android: {
elevation: 2,
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (78) / 100)
},
}),
borderRadius: 16,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (9) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (84) / 100)
},
referralCardHeader: {
fontSize: 20,
textAlign: 'left',
fontWeight: 'bold',
marginTop: 25,
marginHorizontal: 15,
},
referralLogo: {
alignSelf: 'center',
marginTop: 15
},
referralText: {
fontSize: 16,
marginTop: 24,
marginHorizontal: 15,
alignSelf: 'center'
},
referralLinkContainer: {
backgroundColor: 'white',
borderRadius: 8,
flexDirection: 'row',
justifyContent: 'space-between',
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (5) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (5.5) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (74) / 100),
},
referralLinkText: {
fontSize: 14,
textAlign: 'left',
marginLeft: 10,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (5) / 100)
},
referralLinkButton: {
margin: 4.5,
borderRadius: 3,
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
backgroundColor: 'black',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (20) / 100)
},
referralLinkButtonText: {
color: 'white',
textAlign: 'center',
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100)
},
referralShare: {
fontSize: 20,
textAlign: 'left',
fontWeight: 'bold',
margin: 15
},
referralSocial: {
backgroundColor: 'white',
borderRadius: 8,
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (13) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (13) / 100)
},
referralIcon: {
alignSelf: 'center',
marginTop: 5
},
/************************ */
paymnetPayUsing: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (9) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
},
TextCenterWhite24: {
color: 'white',
fontSize: 24,
alignSelf: 'center'
},
paymentCard: {
backgroundColor: 'white',
borderRadius: 8,
flexDirection: 'row',
alignSelf: 'center',
justifyContent: 'space-around',
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
},
paymnetText: {
fontSize: 14,
alignSelf: 'center',
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
},
paymentCardHeader: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
},
cardButton: {
borderWidth: 1,
borderRadius: 8,
borderColor: 'white',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (25) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
},
cardText: {
fontSize: 12,
color: 'white',
textAlign: 'center',
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
cardFormText: {
color: 'white',
fontSize: 14,
// backgroundColor:'red',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)
},
cardInputField: {
borderWidth: 1,
borderColor: 'white',
borderRadius: 8,
color: 'white',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
marginTop: 5,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100)
},
cardInputDate: {
borderWidth: 1,
borderColor: 'white',
color: 'white',
borderRadius: 8,
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (23) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
marginTop: 5,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100)
},
addCardButton: {
backgroundColor: '#0E8EE3',
borderRadius: 8,
position: 'absolute',
bottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
alignSelf: 'center',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100)
},
/************************* */
searchTitleText: {
color: 'white',
fontSize: 24,
fontWeight: 'bold'
},
searchRating: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (0.5) / 100),
},
searchRatingText: {
color: 'white',
fontSize: 12,
marginRight: 5
},
/*********************** */
currentPlanHeader: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (8) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
},
planCard: {
...Platform.select({
ios: {
shadowOffset: { height: 2 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 2,
},
}),
borderRadius: 16,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (60) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (84) / 100),
},
planCardHeaderContainer: {
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
backgroundColor: '#3E4966',
height: 30,
width: 116,
borderRadius: 4,
},
planCardHeaderContainerY: {
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
backgroundColor: '#b32c39',
height: 30,
width: 116,
borderRadius: 4,
},
planCardHeader: {
color: 'white',
fontSize: 16,
textAlign: 'center',
lineHeight: 30,
fontWeight: 'bold',
},
planCurrencyText:{
fontSize: 32, lineHeight: 37, color: 'white'
},
planCurrencyTextR:{
fontSize: 20, lineHeight: 37, color: 'white' , paddingLeft: 5
},
planPointsText:{
fontSize: 14, lineHeight: 17, color: 'white'
},
planPointsDate:{
fontSize: 14,
lineHeight: 17,
color: 'white',
opacity:0.5
},
/********************** */
notificationTitleText: {
color: 'grey',
fontSize: 24,
fontWeight: 'bold'
},
notificationRating: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (0.5) / 100),
},
notificationRatingText: {
color: 'white',
fontWeight:"bold",
fontSize: 12,
marginRight: 5
},
notificationContentRow: {
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (12) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (16) / 100),
},
notificationContentRowLeft: {
alignSelf: 'center',
marginRight: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (6) / 100),
},
notificationContentRowCenter: {
paddingTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4.5) / 100),
alignSelf: 'flex-start'
},
notificationContentRowCenterNew: {
height: 38,
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (60) / 100),
color: 'yellow',
fontSize: 16,
textAlign: 'left',
lineHeight: 19,
},
notificationContentRowCenterWhite: {
height: 38,
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (60) / 100),
color: 'white',
fontSize: 16,
fontWeight:"bold",
textAlign: 'left',
lineHeight: 19,
},
notificationContentRowCenterText: {
color: 'white',
fontSize: 16,
},
aboutHeader: {
...Platform.select({
ios: {
shadowOffset: { height: 2 },
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 2,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
},
}),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
},
aboutText: {
color: 'white',
fontSize: 20,
marginLeft: 10,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
fontWeight: 'bold',
},
aboutCard: {
backgroundColor: 'black',
opacity: 0.7,
...Platform.select({
ios: {
shadowOffset: { height: 2 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 2,
},
}),
borderRadius: 16,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (11) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (80) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (84) / 100),
},
aboutCardText: {
color: 'white',
fontSize: 28,
textAlign: 'center',
fontWeight: 'bold',
margin: 10,
},
aboutCardContent: {
color: 'white',
fontSize: 16,
textAlign: 'justify',
marginTop: 20,
marginHorizontal: 15
},
atmCard: {
borderRadius: 16,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (24) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
},
atmCardNumber: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (6) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (66) / 100),
},
atmCardText: {
color: 'white',
fontSize: 24,
textAlign: 'center',
lineHeight: 30
},
atmBottomContent: {
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (6) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
},
atmCardHolder: {
color: '#C4C4C4',
fontWeight: 'bold',
fontSize: 14,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
atmCardName: {
color: '#888888',
fontSize: 14,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
atmBottomButton: {
color: 'white',
fontSize: 14,
textAlign: 'center',
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
},
/****************************** */
SelectCard: {
borderRadius: 16,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (24) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
},
selectCardContent: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (6) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (66) / 100),
},
selectCardName: {
color: 'white',
fontSize: 14,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
selectCardBottomContent: {
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (6) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
deletedCard: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (0.5) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (13) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
deletedIcon: {
alignSelf: 'center',
marginRight: 5
},
deleteText: {
color: '#84848F',
fontSize: 12,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
/******************************************* */
leaderBoardHeader: {
...Platform.select({
ios: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
shadowOffset: { height: 2 },
},
android: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
elevation: 2,
},
}),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
},
leaderBoardCard1: {
backgroundColor: '#ffffff',
borderRadius: 8,
alignSelf: 'center',
flexDirection: 'row',
justifyContent: 'flex-start',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (9) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (84) / 100),
},
leaderBoardImage: {
alignSelf: 'center', marginLeft: 5, height: 56, width: 56
},
leaderBoardCol: {
flexDirection: 'column', justifyContent: 'center', marginLeft: 10
},
leaderBoardRight: {
// color: 'white',
fontWeight: 'bold',
position: 'absolute',
right: 20,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (9) / 100),
fontSize: 24
},
/********************************************** */
reviewHeader: {
...Platform.select({
ios: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
android: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
},
}),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
},
/********************************************** */
storyScreenHeader: {
position:'absolute',
...Platform.select({
ios: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
android: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
},
}),
flexDirection: 'row',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
justifyContent: 'flex-start',
},
storyScreenPlayButton: {
flexDirection: 'row',
position: 'absolute',
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (62) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (13) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
justifyContent: 'flex-start',
},
storyScreenPlayText:{
color:"white",
fontFamily : "Helvetica Neue",
fontSize: 12,
lineHeight: 12,
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (10) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
marginHorizontal : PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (-1) / 100)
},
storyScreenContainer: {
position: 'absolute',
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (75) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
},
storyScreenCard1: {
position: 'relative',
//backgroundColor: 'red',
...Platform.select({
ios: {
zIndex:5,
shadowOffset: { height: 5 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 5,
},
}),
//opacity:0.6,
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (55) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
borderBottomRightRadius: 40,
borderBottomLeftRadius: 40
},
storyScreenCard1Header: {
flexDirection: 'row',
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
justifyContent: 'space-between',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (5) / 100),
},
storyScreenCard1Text: {
color: 'white',
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (5) / 100),
fontSize: 30,
fontWeight: 'bold',
},
storyScreenCard1Enable: {
alignSelf: 'center',
position: 'absolute',
right: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
},
storyScreenCard1EnabledButton: {
width: 70,
height: 28,
borderRadius: 20
},
storyScreenCard1EnableButton: {
backgroundColor: 'grey',
width: 70,
height: 28,
borderRadius: 20
},
storyScreenCard1EnabledButtonText: {
color: 'white',
position: 'absolute',
left: 8,
lineHeight: 30,
fontSize: 8,
fontWeight: 'bold',
},
storyScreenCard1EnableButtonText: {
color: 'white',
position: 'absolute',
right: 10,
lineHeight: 30,
fontSize: 8,
fontWeight: 'bold',
},
storyParrotCircle: {
backgroundColor: 'black',
...Platform.select({
ios: {
zIndex:1,
shadowOffset: { height: 1 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 1,
},
}),
borderRadius: 20,
position: 'absolute',
alignSelf: 'center',
right: 0,
height: 32,
width: 32
},
storyParrotCircleEnable: {
backgroundColor: 'black',
...Platform.select({
ios: {
zIndex:1,
shadowOffset: { height: 1 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 1,
},
}),
borderRadius: 20,
position: 'absolute',
alignSelf: 'center',
height: 32,
width: 32
},
storyBuyNowButton:{
...Platform.select({
ios: {
zIndex:1,
shadowOffset: { height: 1 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 1,
},
}),
backgroundColor: '#0E8EE3',
borderRadius: 10,
justifyContent: 'center',
position:'relative',
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (30) / 100)
},
storyBuyNowButtonText:{
color: 'white',
fontSize:14,
fontFamily:'Helvetica Neue',
lineHeight:14,
marginTop:3,
fontWeight:'bold',
textAlign:'center',
position:'relative'
},
NoSubscriptionButton: {
// dark button
backgroundColor:'#171B35',
flexDirection: 'row',
justifyContent: 'center',
alignSelf: 'center',
borderRadius: 8,
borderWidth:2,
borderColor:'#0E8EE3',
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (14) / 100),
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (8) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (85) / 100)
},
SubscriptionBuyButton: {
// dark button
backgroundColor:'#0E8EE3',
flexDirection: 'row',
justifyContent: 'center',
alignSelf: 'center',
borderRadius: 8,
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (14) / 100),
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (8) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (85) / 100)
},
OrSeperation: {
color: 'rgba(255,255,255,0.08)',
//marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1.5) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (0) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (40) / 100),
borderRadius:0,
borderWidth:0.4,
borderColor:'#FFFFFF',
},
MonthlySubscriptionButton: {
// grey button
flexDirection: 'row',
justifyContent: 'center',
alignSelf: 'center',
borderRadius: 8,
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (14) / 100),
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (8) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (85) / 100)
},
YearlySubscriptionButton: {
// red button
flexDirection: 'row',
justifyContent: 'center',
alignSelf: 'center',
borderRadius: 8,
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (14) / 100),
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (8) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (85) / 100)
},
SubscriptionText: {
opacity:0.6,
fontFamily: 'Helvetica Neue',
fontWeight: 'bold',
fontSize: 12,
lineHeight: 15,
color: '#FFFFFF',
},
storyPriceText:{
color: 'white',
fontSize:32,
fontFamily:'Helvetica Neue',
lineHeight:38,
fontWeight:'500',
justifyContent: 'center',
alignSelf: 'center',
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (50) / 100)
},
storyStrikePriceText:{
color: 'white',
fontSize:16,
fontFamily:'Helvetica Neue',
lineHeight:19,
fontWeight:'500',
justifyContent: 'center',
alignSelf: 'center',
textDecorationLine:'line-through',
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (30) / 100)
},
storyOverview: {
color: 'white',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
fontSize: 20,
fontWeight: '500'
},
storyOverviewText: {
color: 'white',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (30) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
// marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
fontSize: 14,
textAlign: 'justify',
},
storyEpisodesCard: {
...Platform.select({
ios: {
zIndex:4,
shadowOffset: { height: 4 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 4,
},
}),
position: 'absolute',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
borderBottomRightRadius: 40,
borderBottomLeftRadius: 40
},
storyEpisodesText: {
color: 'white',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (1) / 100),
fontSize: 20,
fontWeight: '500'
},
storyEpisodeRow: {
flexDirection: 'row',
//backgroundColor:"red",
justifyContent: 'space-between',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6.5) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
},
storyEpisodeRow1: {
flexDirection: 'row',
justifyContent: 'space-between',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6.5) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
},
storyEpisodeImage: {
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (10) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (10) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (0.5) / 100),
backgroundColor: '#F4E1A6'
},
storyEpisodeList: {
flexDirection: 'row',
justifyContent: 'space-between',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6.5) / 100),
// backgroundColor:'red'
},
storyEpisodeNumber: {
color: 'white',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (64) / 100),
// marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
fontSize: 14,
textAlign: 'justify',
},
storyEpisodeDescription: {
color: 'white',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (65) / 100),
// marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
fontSize: 12,
textAlign: 'justify',
},
storyEpisodeNumberLock: {
color: 'white',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (70) / 100),
// marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
fontSize: 14,
textAlign: 'justify',
},
storyEpisodeDescriptionLock: {
color: 'white',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (70) / 100),
// marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
fontSize: 12,
textAlign: 'justify',
},
storyReviewsCard: {
...Platform.select({
ios: {
zIndex:3,
shadowOffset: { height: 3 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 3,
},
}),
position: 'absolute',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
borderBottomRightRadius: 40,
borderBottomLeftRadius: 40
},
storyReview: {
marginVertical:PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (5) / 100),
},
storyReviewsText: {
color: 'white',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (0) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (1) / 100),
fontSize: 20,
fontWeight: '500'
},
storyReviewPopUpText: {
color: 'white',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (0) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (1) / 100),
fontSize: 20,
fontWeight: '500',
lineHeight: 23
},
storyReviewsRow: {
flexDirection: 'row',
justifyContent: 'space-between',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6.5) / 100),
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
},
storyWriteReviews: {
color: 'white',
fontSize: 14,
fontWeight: '300',
borderRadius:8,
borderColor:'#FFFFFF',
borderWidth:1,
padding:10
},
storyWriteReviewsYellow: {
color: 'white',
fontSize: 14,
fontWeight: '300',
borderRadius:8,
borderColor:'#FFCC00',
borderWidth:1,
padding:10
},
storyReviewComment: {
color: 'white',
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (1) / 100),
fontSize: 14,
fontWeight: '300',
},
storyReviewsSeperation: {
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (0.1) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (84) / 100),
borderRadius:4,
borderColor:'#FFFFFF',
borderWidth:1,
},
storyRevieweeName:{
color: 'white',
fontFamily: 'Helvetica Neue',
fontWeight: "500",
lineHeight:19,
},
storyReviewDescription: {
color: 'white',
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (80) / 100),
// marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
fontSize: 12,
textAlign: 'justify',
},
storyRevieweeImage: {
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (10) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (10) / 100),
backgroundColor: '#F4E1A6',
borderRadius:20,
},
storyLeaderboardCard: {
position: 'absolute',
...Platform.select({
ios: {
zIndex:2,
shadowOffset: { height: 2 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 2,
},
}),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
borderBottomRightRadius: 40,
borderBottomLeftRadius: 40
},
storyLeaderboardContent: {
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (40) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (10) / 100),
},
storyLeaderboardHeader: {
color: 'white',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
fontSize: 20,
fontWeight: '500'
},
storyLeaderboardCardList: {
// backgroundColor: '#E5AD0E',
borderRadius: 8,
alignSelf: 'center',
flexDirection: 'row',
justifyContent: 'flex-start',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (84) / 100),
},
storyLeaderboardCardListImage: {
alignSelf: 'center', marginLeft: 5, height: 40, width: 40
},
storyLeaderboardCardListName: {
flexDirection: 'column', justifyContent: 'center', marginLeft: 10
},
storyLeaderboardCardListText: {
color: 'white',
fontWeight: 'bold',
position: 'absolute',
right: 20,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
fontSize: 24
},
storyInstructionsCard: {
position: 'absolute',
...Platform.select({
ios: {
zIndex:1,
shadowOffset: { height: 1 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 1,
},
}),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
borderBottomRightRadius: 40,
borderBottomLeftRadius: 40
},
seeMoreButton: {
...Platform.select({
ios: {
zIndex:5,
shadowOffset: { height: 5 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 5,
},
}),
borderRadius: 40,
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
},
seeMoreButtonText: {
color: 'white',
fontSize: 16,
textAlign: 'center',
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
marginTop:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * 2/100)
},
seeMoreButtonTextLeaderboard: {
color: 'white',
fontSize: 16,
textAlign: 'center',
marginTop:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * 1.5 /100)
},
instructionText: {
color: 'white',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
fontSize: 20,
fontWeight: '500'
},
instructionTextContent: {
color: 'white',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (20) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
marginBottom: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
fontSize: 14,
},
storyTagsCard: {
position: 'absolute',
...Platform.select({
ios: {
zIndex:0,
shadowOffset: { height: 0 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 0,
},
}),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
},
storyTagsButton: {
alignSelf: 'stretch',
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-evenly',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (4) / 100),
},
storyTagsButtonText: {
color: 'white',
backgroundColor: '#39111B',
borderRadius: 18,
lineHeight: 30,
paddingHorizontal: 15,
height: 30,
textAlign: 'center',
marginVertical: 8,
fontSize: 14,
fontWeight: '500'
},
/********************************* */
RegisterChildButton:{
flexDirection: 'row',
justifyContent: 'flex-start',
//alignSelf: 'center',
borderRadius: 10,
// marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (14) / 100),
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (13) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (85) / 100)
},
/*************************************** */
gameProgressCard: {
...Platform.select({
ios: {
zIndex:4,
shadowOffset: { height: 4 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 4,
},
}),
position: 'absolute',
backgroundColor: '#01444F',
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (20) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (43) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
borderBottomRightRadius: 40,
borderBottomLeftRadius: 40
},
gameProgressCardHeader: {
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (16) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (27) / 100),
},
gameProgressCardText: {
color: 'white',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
fontSize: 20,
fontWeight: '500'
},
gameProgressCardPercent: {
color: 'white',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
fontSize: 16,
textAlign: 'right',
fontWeight: '300'
},
gameProgressBarFull: {
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (84) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
backgroundColor: '#727272',
height: 12
},
gameProgressBar: {
width: `72%`,
backgroundColor: '#ffffff',
height: 12
},
gameInstructionCard: {
position: 'absolute',
backgroundColor: '#015C6B',
...Platform.select({
ios: {
shadowOffset: { height: 3 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 3,
},
}),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (40) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (43) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
borderBottomRightRadius: 40,
borderBottomLeftRadius: 40
},
gameInstructionCardHeader: {
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (16) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (27) / 100),
},
gameInstructionCardTitle: {
color: 'white',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
fontSize: 20,
fontWeight: '500'
},
gameInstructionCardText: {
color: 'white',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
fontSize: 16,
},
gameTagsCard: {
position: 'absolute',
backgroundColor: '#028095',
...Platform.select({
ios: {
zIndex:2,
shadowOffset: { height: 2 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 2,
},
}),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (60) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (43) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
},
gameTagsCardContent: {
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (16) / 100),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (27) / 100),
},
gameTagsCardButton: {
alignSelf: 'stretch',
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-evenly',
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (4) / 100),
},
gameTagsCardButtonText: {
color: 'white',
backgroundColor: '#01333C',
borderRadius: 18,
lineHeight: 30,
paddingHorizontal: 15,
height: 30,
textAlign: 'center',
marginVertical: 8,
fontSize: 14,
fontWeight: '500'
},
/*********************************************** */
PayUsingHeader: {
flexDirection: 'row',
...Platform.select({
ios: {
shadowOffset: { height: 2 },
// shadowColor: 'grey',
// shadowOpacity: 1
},
android: {
elevation: 2,
},
}),
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (8) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
justifyContent: 'flex-start',
},
payUsingAmount: {
backgroundColor: 'black',
opacity: 0.5,
borderRadius: 8,
borderColor: 'grey',
borderWidth: 1,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (9) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (17) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
},
payUsingAmountHeader: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (6) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (66) / 100),
},
payUsingAmountHeaderText: {
color: 'white',
fontWeight: 'bold',
fontSize: 14,
lineHeight: 17
},
payUsingAmountContent: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (2) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (6) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (6) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (66) / 100),
},
payUsingAmountDollar: {
color: '#7BCFF0',
fontWeight: 'bold',
fontSize: 40,
lineHeight: 47
},
payUsingAmountNumber: {
marginLeft: 10,
color: 'white',
fontWeight: 'bold',
fontSize: 40,
lineHeight: 47
},
payUsingAmountText: {
color: '#7BCFF0',
fontWeight: 'bold',
fontSize: 14,
lineHeight: 47
},
payUsingAlignLogo: {
alignSelf: 'center',
flexDirection: 'row'
},
payUsingButtonText: {
fontSize: 20,
lineHeight: 25
},
/********************************** */
searchBar: {
...Platform.select({
ios: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
},
android: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (0) / 100),
},
}),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (5) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (8) / 100),
borderBottomWidth: 1,
borderBottomColor: '#041c05',
},
searchBar1: {
// marginTop:10,
// marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (5) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (15) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (80) / 100),
borderBottomWidth: 1,
borderBottomColor: 'white',
backgroundColor:"white"
},
searchBarText: {
marginLeft: '5%', fontSize: 20, color: 'white', textAlign: 'left', width: '75%'
},
searchBarLogo: {
alignSelf: 'center', position: 'absolute', right: 10
},
searchHorizontalContent: {
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (4) / 100)
},
searchHorizontalContentImage: {
height: 160,
width: 120,
marginLeft: 20,
resizeMode: 'stretch'
},
searchResultContent: {
flexDirection: 'row',
justifyContent: 'flex-start',
marginLeft: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (12) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (16) / 100),
},
searchResultContentLeft: {
alignSelf: 'center',
marginRight: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (6) / 100),
},
searchResultContentCenter: {
paddingTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4.5) / 100),
alignSelf: 'flex-start'
},
searchResultContentCenterText: {
height: 19,
color: 'white',
fontSize: 16,
lineHeight: 19,
},
TextStyle: {
color: "#000000",
fontWeight: 'bold',
fontSize: 28,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),
},
/************************ */
// searchContainer: {
// marginVertical: 20,
// height: 50,
// width: '92%',
// borderRadius: 10,
// backgroundColor: '#404260',
// marginHorizontal: '4%',
// },
// categoryContainer: {
// marginVertical: 22,
// height: 80,
// width: '70%',
// borderRadius: 10,
// backgroundColor: '#303147',
// marginHorizontal: '4%',
// },
// searchText: {
// width: '100%',
// height: '100%',
// fontSize: 18,
// fontWeight: '400',
// textAlignVertical: 'center',
// paddingLeft: 20,
// color: '#F4C5D6',
// },
// categoryText: {
// width: '100%',
// height: '100%',
// fontSize: 18,
// fontWeight: '400',
// textAlignVertical: 'center',
// paddingLeft: 20,
// color: '#FCF5CA',
// },
// highlight: {
// fontWeight: '700',
// },
// button: {
// backgroundColor: 'green',
// paddingHorizontal: 20,
// paddingVertical: 15,
// marginTop: 15,
// },
// buttonText: {
// color: '#fff',
// fontWeight: 'bold',
// },
});
export default styles;<file_sep>/storyqube-dev-mobile-app-master/component/home/Home.js
import React from 'react';
import {
Text,
TouchableOpacity,
PixelRatio,
Dimensions,
Image,
View,
ScrollView,
Animated,
PanResponder,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import styles from '../Styles';
import ParrotLogo from '../assets/logoH.svg';
import Notification from '../assets/notification.svg';
import Arrow from '../assets/arrow2.svg'
import Star from '../assets/star.svg';
import Star1 from '../assets/star1.svg';
const screen_width=Dimensions.get("window").width;
const screen_height =Dimensions.get("window").height;
const images=[
{ id:1, uri: require('../assets/cards/1.png'),name: "first_image"},
{ id:2, uri: require('../assets/cards/2.png'),name: "sec_image"},
{ id:3, uri: require('../assets/cards/3.png'),name: "third_image"},
];
export default class HomeScreen extends React.Component {
constructor(props){
super(props);
this.renderImages=this.renderImages.bind(this);
this.position = new Animated.ValueXY();
this.state ={
currentIndex:1
}
}
componentwillMount(){
this.PanResponder = PanResponder.create({
onStartShouldSetPanResponder:(evt, gestureState) => true,
onPanResponderMove:(eve,gestureState) => {
this.position.setValue({ x: gestureState.dx, y: gestureState.dy})
},
onPanResponderRelease:(eve,gestureState) => {
}
})
}
renderImages = () => {
return images.map((item,i) => {
if(i< this.state.currentIndex)
{
return null
}
else if(i == this.state.currentIndex)
{
return(
<Animated.View
{...PanResponder.panHandlers}
key={item.id}
style={[{transform: this.position.getTranslateTransform()},{height: screen_height, width: screen_width , padding:10 }]}>
<Image
style={{flex:1,borderRadius:20}}
source= {item.uri}/>
</Animated.View>
)
}
else{
return(
<Animated.View
key={item.id}
style={[{height: screen_height, width: screen_width , padding:10 }]}>
<Image
style={{flex:1,borderRadius:20}}
source= {item.uri}/>
</Animated.View>
)
}
})
}
render() {
return (
<View style={styles.container}>
<Image style={styles.backgroundImage} source={require('../assets/HomeScreen.png') }/>
<View style={[styles.flexRowBetween, styles.homeHeader]}>
<View style={styles.flexRowStart}>
<Image style={{
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (12) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (32) / 100),
marginLeft: -20}}
source={require('../assets/logo1.png')} />
<Text style={[styles.homeTitleText,{marginTop: 20, height: 50}]}>Waste Busterzz..</Text>
</View>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Notification')}
style={[styles.flexColCenter,{marginTop:25}]}>
<Notification width={20} height={24} />
</TouchableOpacity>
</View>
<View style={[styles.flexRowBetween,{marginLeft:14,marginBottom:12, height:20}]}/>
<ScrollView contentInsetAdjustmentBehavior="automatic" style={styles.backgroundStyle}>
<View style ={{
//marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (5) / 100),
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (12) / 100),
width:PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (90) / 100),
alignSelf: "center",
zIndex: 2,
borderRadius: 20,
elevation: 5
}}>
<Text style={{alignSelf:"center", color: 'black',fontSize: 22,fontWeight: 'bold',marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
}}>Guardians of the Garbage...</Text>
</View>
<View style={[styles.flexRowBetween,{marginLeft:14,marginBottom:12, height:20}]}/>
<View style={{}}>
<Text style={{color: 'white', fontSize: 15,fontWeight: 'bold', alignSelf:"center", textAlign:"center"}}>
We as Waste Busterzz.. are here to help you find out the optimal location to setup you Waste Mamangement Plant and minimise your waste collection time.
Don't know what to do with those plastic items and electric wires piling ?
We come to your rescue. Give us your Plastic and E-waste and earn rewards in return. Wanna know how ?
Look down : )
</Text>
</View>
<View style={[styles.flexRowBetween,{marginLeft:14,marginBottom:12, height:20}]}/>
<View style={{
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (20) / 100),
paddingHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (7) / 100),
}}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Story')}
>
<LinearGradient
useAngle={true}
angle={259.04}
start={{x: 0.0, y: 0.25}}
end={{x: 0.5, y: 1.0}}
locations={[0.0,0.9962]}
colors={['#f0e00a', '#29BBBB']}
style={styles.RegisterChildButton} >
<View style={[styles.flexRowCenter,{width:PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (82/100)),
// backgroundColor:"red",
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height* 13 / 100),
}]}>
<View style={styles.flexColCenter}>
<Text style={{
fontFamily: 'Helvetica Neue',
fontWeight: 'bold',
fontSize: 16,
letterSpacing: 0.04,
color:'#000000',
}}>Optimise time, Minimize location</Text>
</View>
</View>
</LinearGradient>
</TouchableOpacity>
</View>
<View style={{
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (100) / 100),
marginTop:-20,
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (20) / 100),
paddingHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (7) / 100),
}}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Leaderboard')}
>
<LinearGradient
useAngle={true}
angle={259.04}
start={{x: 0.0, y: 0.25}}
end={{x: 0.5, y: 1.0}}
locations={[0.0,0.9962]}
colors={['#f0e00a', '#29BBBB']}
style={styles.RegisterChildButton} >
<View style={[styles.flexRowCenter,{width:PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (82/100)),
height:PixelRatio.roundToNearestPixel(Dimensions.get('window').height* 13 / 100),
}]}>
<View style={styles.flexColCenter}>
<Text style={{
fontFamily: 'Helvetica Neue',
fontWeight: 'bold',
fontSize: 16,
letterSpacing: 0.04,
color:'#000',
}}>Submit Waste</Text>
</View>
</View>
</LinearGradient>
</TouchableOpacity>
</View>
</ScrollView>
</View>
);
}
} <file_sep>/storyqube-dev-mobile-app-master/component/home/SavedCard.js
import React from 'react';
import {
NativeModules,
TextInput,
Text,
TouchableOpacity,
PixelRatio,
Dimensions,
ScrollView,
Platform,
Image,
View,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient'
import AsyncStorage from '@react-native-community/async-storage';
import styles from '../Styles'
import Back from '../assets/notification/back.svg'
import Amex from '../assets/AMEX.svg'
import Delete from '../assets/Delete.svg'
import Card from '../assets/Card.svg'
import More from '../assets/more.svg'
import Support from '../assets/myAccount/support.svg'
import About from '../assets/myAccount/about.svg'
import SignOut from '../assets/myAccount/signout.svg'
import SubscriptionCard from '../assets/myAccount/SubscriptionCard.svg'
import ReferralCard from '../assets/myAccount/ReferralCard.svg'
import LearningCard from '../assets/myAccount/LearningCard.svg'
import RateCard from '../assets/myAccount/RateCard.svg'
import SupportCard from '../assets/myAccount/SupportCard.svg'
import AboutCard from '../assets/myAccount/AboutCard.svg'
import SignOutCard from '../assets/myAccount/SignOutCard.svg'
import Star from '../assets/star.svg'
import Star1 from '../assets/star1.svg'
const { UIManager } = NativeModules;
if (
Platform.OS === "android" &&
UIManager.setLayoutAnimationEnabledExperimental
) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
export default class SavedCardScreen extends React.Component {
state = {
};
clearAll = async () => {
try {
await AsyncStorage.clear()
} catch (e) {
// remove error
}
console.log('Done.')
}
handleSignOut = () => {
this.clearAll()
console.log('signout')
}
render() {
return (
<ScrollView>
<View style={styles.container}>
<Image style={styles.backgroundImage} source={require('../assets/Login_background.png')} />
<TouchableOpacity
onPress={() => this.props.navigation.goBack()}
style={[styles.flexRowStart, styles.aboutHeader]}>
<Back width={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)}
height={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)} />
</TouchableOpacity>
<View style={styles.flexRowStart}>
<View style={styles.paymentCardHeader}>
<Text style={styles.homeTitleText}>NEW CARD</Text>
</View>
</View>
<LinearGradient
useAngle={true}
angle={90}
// angleCenter= {{ x: 0.5, y: 0.5}}
// start={{ x: 0.0, y: 0.0 }}
// end={{ x: 0.0, y: 0.32 }}
locations={[0.0, 1.0]}
colors={['#232526', '#414345']}
style={[styles.flexColBetween, styles.atmCard]}>
<View style={styles.savedCardBlackLine} >
</View>
<View style={styles.savedCardDown}>
<View style={styles.flexRowBetween}>
<View style={styles.flexColCenter}>
<Text style={styles.savedCardDownText}>CVV</Text>
<Text style={styles.savedCarddownInput}>XXX</Text>
</View>
</View>
</View>
</LinearGradient>
<View style={styles.flexRowStart}>
<View style={styles.paymentCardHeader}>
<Text style={styles.cardFormText}>CVV</Text>
</View>
</View>
<TextInput
style={styles.cardInputDate}
// placeholder='email'
// placeholderTextColor='#747686'
// onChangeText={text => onChangeText(text)}
/>
<View style={[styles.flexRowStart,styles.savedCardSave]}>
<View style={styles.saveCardSaveBox} >
</View>
<Text style={styles.saveCardSaveText} >Save this card</Text>
</View>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('YearlyPlan')}
style={styles.addCardButton}>
<Text style={styles.atmBottomButton}>Pay Now</Text>
</TouchableOpacity>
</View >
</ScrollView>
);
}
}
<file_sep>/storyqube-dev-mobile-app-master/component/home/About.js
import React from 'react';
import {
Text,
TouchableOpacity,
PixelRatio,
Dimensions,
Platform,
Image,
View,
} from 'react-native';
import styles from '../Styles'
import Back from '../assets/notification/back.svg'
export default class AboutScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<Image style={styles.backgroundImage} source={require('../assets/Group.png')} />
<TouchableOpacity
onPress={() => this.props.navigation.goBack()}
style={[
styles.flexRowStart,
styles.aboutHeader
]}>
<Back width={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)}
height={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)} />
<Text
style={styles.aboutText} >
Back
</Text>
</TouchableOpacity>
<View
style={[styles.flexColBetween, styles.aboutCard]}>
<View >
<Text style={styles.aboutCardText}>
About
</Text>
<Text style={styles.aboutCardContent}>
Esse ipsum laboris sit ut adipisicing proident veniam irure exercitation laborum et fugiat
voluptate. Elit non et qui veniam incididunt do ut exercitation excepteur aute id.
Nisi cupidatat proident anim laboris ad veniam duis dolore irure consequat adipisicing ea.
Consectetur ut sunt excepteur velit non quis tempor sit fugiat non occaecat cupidatat id velit.
Mollit exercitation excepteur duis veniam adipisicing incididunt aliqua voluptate nisi deserunt
sit irure proident esse. Exercitation ut ad id irure tempor.
Est irure cillum aliquip labore est reprehenderit consectetur id mollit excepteur irure ex ex.
Aliquip labore est reprehenderit consectetur id mollit excepteur
</Text>
<Text style={styles.aboutCardContent}>
www.voiceqube.com
</Text>
</View>
</View>
</View >
);
}
}
<file_sep>/storyqube-dev-mobile-app-master/component/home/MonthlyPlan.js
import React from 'react';
import {
Text,
TouchableOpacity,
PixelRatio,
Dimensions,
Platform,
Image,
View,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient'
import styles from '../Styles'
import Back from '../assets/notification/back.svg'
export default class MonthlyPlanScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<TouchableOpacity
onPress={() => this.props.navigation.goBack()}
style={[
styles.flexRowStart,
styles.aboutHeader
]}>
<Back width={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)}
height={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)} />
<Text
style={styles.aboutText} >
Back
</Text>
</TouchableOpacity>
<View style={styles.flexRowStart}>
<View style={styles.currentPlanHeader}>
<Text style={styles.homeTitleText}>CURRENT PLAN</Text>
</View>
</View>
<LinearGradient
useAngle={true}
angle={110}
// angleCenter= {{ x: 0.5, y: 0.5}}
// start={{ x: 0.11, y: 0.95 }}
// end={{ x: 0.0, y: 0.95 }}
locations={[0.03, 0.98]}
colors={['#3F4C6B', '#606C88']}
style={[styles.flexColStart, styles.planCard]}>
<View style={{
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
}}>
<View style={styles.planCardHeaderContainer}>
<Text style={styles.planCardHeader}>
MONTHLY
</Text>
</View>
<View style={{
position:'absolute',
right:0,
flexDirection:'row',
justifyContent:'center'
}}>
<Text style={styles.planPointsText}>Renew</Text>
<View style={{
height:17,
marginLeft:5,
width:30,
borderRadius:10,
backgroundColor:'white'
}}>
<View style={{
height:10,
width:10,
position:'absolute',
marginTop:3.5,
right:2,
borderRadius:6,
backgroundColor:'#3E4966'
}}></View>
</View>
</View>
<View style={styles.flexRowStart} >
<Text style={styles.planCurrencyText}>
$9.99
</Text>
<Text style={styles.planCurrencyTextR}>
/month
</Text>
</View>
<View style={{...styles.flexRowCenter, marginTop : PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (4) / 100),}}>
<View style={{
alignSelf: 'flex-end'
}}>
<Text style={styles.planPointsDate}>28/04/2020</Text>
</View>
<View style={{
backgroundColor: '#313a52',
borderRadius: 100,
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (15) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (15) / 100),
}}>
<View style={{
borderRadius: 100,
borderWidth: 8,
borderColor: 'white',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (15) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (15) / 100),
}}>
<View>
<Text style={{
color:'white',
textAlign:'center',
fontSize:18,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (15) / 100),
}}>
28 days
Left
</Text>
</View>
</View>
</View>
<View style={{ alignSelf: 'flex-end' }}>
<Text style={styles.planPointsDate}>28/05/2020</Text>
</View>
</View>
<View style={{
...styles.flexColStart,
marginTop: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (5) / 100),
}} >
<Text style={styles.planPointsText}>
• Browse free original content.
</Text>
<Text style={styles.planPointsText}>
• Premium content upto 60% discount.
</Text>
<Text style={styles.planPointsText}>
• Billed monthly.
</Text>
</View>
</View>
</LinearGradient>
</View >
);
}
}
<file_sep>/storyqube-dev-mobile-app-master/component/home/Leaderboard.js
import React from 'react';
import {
NativeModules,
LayoutAnimation,
Text,
TouchableOpacity,
PixelRatio,
Dimensions,
Platform,
Image,
View,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient'
import styles from '../Styles'
import Back from '../assets/notification/back.svg'
export default class LeaderboardScreen extends React.Component {
render() {
return (
<View style={styles.leaderboardContainer}>
<Image style={styles.backgroundImage} source={require('../assets/HomeScreen.png') }/>
<TouchableOpacity
onPress={() => this.props.navigation.goBack()}
style={[styles.flexRowStart, styles.leaderBoardHeader]}>
<Back width={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)}
height={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)} />
<Text
style={{
color: 'white',
fontSize: 20,
marginLeft: 10,
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100),
fontWeight: 'bold',
}} >
SubmitWaste
</Text>
</TouchableOpacity>
<Text style={{marginBottom:5,color: 'black', fontSize: 18,fontWeight: 'bold', alignSelf:"center", textAlign:"center"}}>
Making the best out of Waste : )
</Text>
<Text style={{marginBottom:10,color: 'black', fontSize: 15,fontWeight: 'bold', alignSelf:"center", textAlign:"center"}}>
Choose the type of waste
</Text>
<TouchableOpacity onPress={() => this.props.navigation.navigate('Game')}>
<LinearGradient
useAngle={true}
angle={105}
// angleCenter= {{ x: 0.5, y: 0.5}}
// start={{ x: 0.11, y: 0.95 }}
// end={{ x: 0.0, y: 0.95 }}
locations={[0.0, 1.0]}
colors={['#FCC201', '#DBA514']}
style={styles.leaderBoardCard1}>
<View style={[styles.leaderBoardCol,{width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (84) / 100), alignContent:"center"}]} >
<Text style={{fontWeight:"bold", fontSize:20, alignSelf:"center"}}>Plastic Waste</Text>
</View>
</LinearGradient>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('Game')}>
<LinearGradient
useAngle={true}
angle={103}
// angleCenter= {{ x: 0.5, y: 0.5}}
// start={{ x: 0.11, y: 0.95 }}
// end={{ x: 0.0, y: 0.95 }}
locations={[0.0, 1.0]}
colors={['#E7E8EB', '#C0BEC6']}
style={styles.leaderBoardCard1}>
<View style={[styles.leaderBoardCol,{width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (84) / 100), alignContent:"center"}]} >
<Text style={{fontWeight:"bold", fontSize:20, alignSelf:"center"}}>E-Waste</Text>
</View>
</LinearGradient>
</TouchableOpacity>
<Text style={{marginTop:10,color: 'black', fontSize: 18,fontWeight: 'bold', alignSelf:"center", textAlign:"center"}}>
Being the bridge between you and our partners.
</Text>
<Text style={{marginBottom:5,color: 'black', fontSize: 18,fontWeight: 'bold', alignSelf:"center", textAlign:"center"}}>
Look at our partners.
</Text>
<View style={styles.flexRowCenter}>
<Image style={{
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (20) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (32) / 100),
marginLeft: -20}}
source={require('../assets/1.png')} />
<Image style={{
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (20) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (32) / 100),
marginLeft: -20}}
source={require('../assets/Facebook.svg')} />
<Image style={{
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (20) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (32) / 100),
marginLeft: -20}}
source={require('../assets/2.png')} />
</View>
<View style={[styles.flexRowCenter,{marginTop:20}]}>
<Image style={{
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (20) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (32) / 100),
marginLeft: -20}}
source={require('../assets/3.png')} />
<Image style={{
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (20) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (32) / 100),
marginLeft: -20}}
source={require('../assets/Facebook.svg')} />
<Image style={{
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (20) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (32) / 100),
marginLeft: -20}}
source={require('../assets/4.png')} />
</View>
</View >
);
}
}
<file_sep>/storyqube-dev-mobile-app-master/component/home/Payment.js
import React from 'react';
import {
Text,
TouchableOpacity,
PixelRatio,
Dimensions,
Platform,
Image,
View,
} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import styles from '../Styles'
import Back from '../assets/notification/back.svg'
import Apple from '../assets/Apple.svg'
import Google from '../assets/Google.svg'
import Card from '../assets/Card.svg'
import More from '../assets/more.svg'
export default class PaymentScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<Image style={styles.backgroundImage} source={require('../assets/Login_background.png')} />
<TouchableOpacity
onPress={() => this.props.navigation.goBack()}
style={styles.PayUsingHeader}>
<Back width={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)}
height={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)} />
</TouchableOpacity>
<View style={[styles.flexColBetween, styles.payUsingAmount]}>
<View style={styles.flexColStart}>
<View style={styles.payUsingAmountHeader} >
<Text style={styles.payUsingAmountHeaderText}>
AMOUNT
</Text>
</View>
<View style={[styles.flexRowBetween, styles.payUsingAmountContent]} >
<View style={styles.flexRowStart}>
<Text style={styles.payUsingAmountDollar}>
$
</Text>
<Text style={styles.payUsingAmountNumber}>
50.00
</Text>
</View>
<Text style={styles.payUsingAmountText}>
Annual Plan
</Text>
</View>
</View>
</View>
<View style={styles.paymnetPayUsing} >
<Text style={styles.TextCenterWhite24}>
Pay Using
</Text>
</View>
<View style={styles.paymentCard} >
<View style={styles.payUsingAlignLogo}>
<Apple />
<Text style={styles.payUsingButtonText}>Pay</Text>
</View>
<Text style={styles.paymnetText}>
APPLE PAY
</Text>
<View style={{
alignSelf: 'center'
}}>
<More />
</View>
</View>
<View style={styles.paymentCard} >
<View style={styles.payUsingAlignLogo}>
<Google />
<Text style={styles.payUsingButtonText}>Pay</Text>
</View>
<Text style={styles.paymnetText}>
GOOGLE PAY
</Text>
<View style={{
alignSelf: 'center'
}}>
<More />
</View>
</View>
<View style={{
marginVertical: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (1) / 100),
marginHorizontal: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (11) / 100),
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (78) / 100),
}} >
<Text style={{
color: 'white',
fontSize: 16,
alignSelf: 'center',
lineHeight: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
}}>
or
</Text>
</View>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Card')}
style={styles.paymentCard} >
<View style={styles.payUsingAlignLogo}>
<Card />
</View>
<Text style={styles.paymnetText}>
CREDIT CARD
</Text>
<View style={{
alignSelf: 'center'
}}>
<More />
</View>
</TouchableOpacity>
</View >
);
}
}
<file_sep>/storyqube-dev-mobile-app-master/component/home/Referral.js
import React from 'react';
import {
NativeModules,
LayoutAnimation,
Text,
TouchableOpacity,
PixelRatio,
Dimensions,
Platform,
Image,
View,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient'
import AsyncStorage from '@react-native-community/async-storage';
import styles from '../Styles'
import Back from '../assets/notification/back.svg'
import Instagram from '../assets/Instagram.svg'
import Facebook from '../assets/Facebook.svg'
import Message from '../assets/Message.svg'
import Twitter from '../assets/Twitter.svg'
import InviteLogo from '../assets/InviteLogo.svg'
import About from '../assets/myAccount/about.svg'
import SignOut from '../assets/myAccount/signout.svg'
import SubscriptionCard from '../assets/myAccount/SubscriptionCard.svg'
import ReferralCard from '../assets/myAccount/ReferralCard.svg'
import LearningCard from '../assets/myAccount/LearningCard.svg'
import RateCard from '../assets/myAccount/RateCard.svg'
import SupportCard from '../assets/myAccount/SupportCard.svg'
import AboutCard from '../assets/myAccount/AboutCard.svg'
import SignOutCard from '../assets/myAccount/SignOutCard.svg'
import Star from '../assets/star.svg'
import Star1 from '../assets/star1.svg'
const { UIManager } = NativeModules;
if (
Platform.OS === "android" &&
UIManager.setLayoutAnimationEnabledExperimental
) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
export default class AboutScreen extends React.Component {
state = {
};
clearAll = async () => {
try {
await AsyncStorage.clear()
} catch (e) {
// remove error
}
console.log('Done.')
}
handleSignOut = () => {
this.clearAll()
console.log('signout')
}
render() {
return (
<View style={{ ...styles.container, backgroundColor: 'black' }}>
<TouchableOpacity
onPress={() => this.props.navigation.goBack()}
style={styles.referralHeader}>
<Back width={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)}
height={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)} />
<Text
style={styles.referralBack} >
Back
</Text>
</TouchableOpacity>
<LinearGradient
useAngle={true}
angle={328}
// angleCenter= {{ x: 0.5, y: 0.5}}
// start={{ x: 0.11, y: 0.95 }}
// end={{ x: 0.0, y: 0.95 }}
locations={[0.03, 0.99]}
colors={['#A9BAC8', '#EEF2F3']}
style={styles.referralCard}>
<View >
<Text style={styles.referralCardHeader}>
Invite Friends
</Text>
<View style={styles.referralLogo}>
<InviteLogo />
</View>
<Text style={styles.referralText}>
Send your friends an invite to find out how cool games and stories are in the Storycube app.
</Text>
<View style={styles.referralLinkContainer}>
<Text style={styles.referralLinkText}>
https://www.wastebusterzz./...
</Text>
<View style={styles.referralLinkButton}>
<Text style={styles.referralLinkButtonText}>Copy Link</Text>
</View>
</View>
<Text style={styles.referralShare}>
Share via
</Text>
<View style={{
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').width * (13) / 100),
marginHorizontal: 15,
...styles.flexRowBetween
}}>
<View style={styles.referralSocial}>
<View style={styles.referralIcon}>
<Facebook />
</View>
</View>
<View style={styles.referralSocial}>
<View style={styles.referralIcon}>
<Twitter />
</View>
</View>
<View style={styles.referralSocial}>
<View style={styles.referralIcon}>
<Instagram />
</View>
</View>
<View style={styles.referralSocial}>
<View style={styles.referralIcon}>
<Message />
</View>
</View>
</View>
</View>
</LinearGradient>
</View >
);
}
}
<file_sep>/storyqube-dev-mobile-app-master/App.js
import 'react-native-gesture-handler';
import React from 'react';
import {
SafeAreaView,
View,
Text,
StatusBar,
} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage'
const STATUSBAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight;
console.log(STATUSBAR_HEIGHT)
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from "@react-navigation/stack";
import AuthenticationScreen from './component/authentication/Authentication'
import HomeScreen from './component/home/Home'
import ProfileScreen from './component/home/Profile'
import SearchScreen from './component/home/Search'
import ReferalScreen from './component/home/Referral'
import AboutScreen from './component/home/About'
import SubscriptionScreen from './component/home/Subscription'
import PaymentScreen from './component/home/Payment'
import CardScreen from './component/home/Card'
import AddCardScreen from './component/home/AddCard'
import StoryScreen from './component/home/Story';
import GameScreen from './component/home/Game'
import LeaderboardScreen from './component/home/Leaderboard';
import SavedCardScreen from './component/home/SavedCard';
import NotificationScreen from './component/home/Notification';
import YearlyPlanScreen from './component/home/YearlyPlan';
import MonthlyPlanScreen from './component/home/MonthlyPlan';
import Home from './component/assets/navBar/home.svg'
import Search from './component/assets/navBar/search.svg'
import Account from './component/assets/navBar/account.svg'
import HomeFocused from './component/assets/navBar/home1.svg'
import SearchFocused from './component/assets/navBar/search1.svg'
import AccountFocused from './component/assets/navBar/account1.svg'
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
const Tab = createMaterialBottomTabNavigator();
import { AuthContext } from "./context";
const AuthStack = createStackNavigator();
const AuthStackScreen = () => (
<AuthStack.Navigator>
<AuthStack.Screen
name="Authentication"
component={AuthenticationScreen}
options={{ headerShown: false }}
/>
</AuthStack.Navigator>
);
const HomeStack = createStackNavigator();
const HomeStackScreen = () => (
<HomeStack.Navigator>
<HomeStack.Screen name="Home" component={HomeScreen} options={{ headerShown: false }} />
<HomeStack.Screen name="Notification" component={NotificationScreen} options={{ headerShown: false }} />
</HomeStack.Navigator>
);
const SearchStack = createStackNavigator();
const SearchStackScreen = () => (
<SearchStack.Navigator>
<SearchStack.Screen name="Search" component={SearchScreen} options={{ headerShown: false }} />
</SearchStack.Navigator>
);
const ProfileStack = createStackNavigator();
const ProfileStackScreen = () => (
<ProfileStack.Navigator>
<ProfileStack.Screen name="Profile" component={ProfileScreen} options={{ headerShown: false }} />
<ProfileStack.Screen name="About" component={AboutScreen} options={{ headerShown: false }} />
<ProfileStack.Screen name="YearlyPlan" component={YearlyPlanScreen} options={{ headerShown: false }} />
<ProfileStack.Screen name="MonthlyPlan" component={MonthlyPlanScreen} options={{ headerShown: false }} />
<ProfileStack.Screen name="Referral" component={ReferalScreen} options={{ headerShown: false }} />
</ProfileStack.Navigator>
);
const TabsScreen = () => (
<Tab.Navigator
initialRouteName="Home"
activeColor="white"
inactiveColor='white'
shifting={true}
labeled={false}
barStyle={{ backgroundColor: '#041c05' }}
>
<Tab.Screen
name="Home"
component={HomeStackScreen}
options={{
tabBarLabel: 'Home',
tabBarIcon: ({ focused, color }) => (
focused ?
<HomeFocused width={100} height={30} />
:
<Home width={24} height={24} />
),
}}
/>
<Tab.Screen
name="Notifications"
component={SearchStackScreen}
options={{
tabBarLabel: 'Search',
tabBarIcon: ({ focused, color }) => (
focused ?
<SearchFocused width={100} height={30} />
:
<Search width={24} height={24} />
),
}}
/>
<Tab.Screen
name="Profile"
component={ProfileStackScreen}
options={{
tabBarLabel: 'Profile',
tabBarIcon: ({ focused, color }) => (
focused ?
<AccountFocused width={100} height={30} />
:
<Account width={24} height={24} />
),
}}
/>
</Tab.Navigator>
);
const RootStack = createStackNavigator();
class App extends React.Component {
state = {
userToken: "<PASSWORD>",
status: null
}
render() {
return (
<NavigationContainer>
<StatusBar height={STATUSBAR_HEIGHT} barStyle='light-content' backgroundColor='#0A0A22' />
<RootStack.Navigator >
{
this.state.userToken == null ?
<RootStack.Screen
name="Authentication"
component={AuthStackScreen}
options={{
headerShown: false,
animationEnabled: false
}}
/>
:
<>
<RootStack.Screen name="App" component={TabsScreen} options={{ headerShown: false, animationEnabled: false }}
/>
<ProfileStack.Screen name="Subscription" component={SubscriptionScreen} options={{ headerShown: false }} />
<ProfileStack.Screen name="Payment" component={PaymentScreen} options={{ headerShown: false }} />
<ProfileStack.Screen name="Card" component={CardScreen} options={{ headerShown: false }} />
<ProfileStack.Screen name="AddCard" component={AddCardScreen} options={{ headerShown: false }} />
<ProfileStack.Screen name="SavedCard" component={SavedCardScreen} options={{ headerShown: false }} />
<ProfileStack.Screen name="Story" component={StoryScreen} options={{ headerShown: false }} />
<ProfileStack.Screen name="Game" component={GameScreen} options={{ headerShown: false }} />
<ProfileStack.Screen name="Leaderboard" component={LeaderboardScreen} options={{ headerShown: false }} />
</>
}
</RootStack.Navigator>
</NavigationContainer>
);
};
};
export default App;
<file_sep>/storyqube-dev-mobile-app-master/component/home/Card.js
import React from 'react';
import {
Text,
TouchableOpacity,
PixelRatio,
Dimensions,
Image,
View,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient'
import styles from '../Styles'
import Back from '../assets/notification/back.svg'
import Amex from '../assets/AMEX.svg'
import Delete from '../assets/Delete.svg'
export default class CardScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<Image style={styles.backgroundImage} source={require('../assets/Login_background.png')} />
<TouchableOpacity
onPress={() => this.props.navigation.goBack()}
style={[styles.flexRowStart, styles.aboutHeader]}>
<Back width={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)}
height={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)} />
</TouchableOpacity>
<View style={styles.flexRowStart}>
<View style={styles.paymentCardHeader}>
<Text style={styles.homeTitleText}>SELECT CARD</Text>
</View>
</View>
<View style={styles.flexRowEnd}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('AddCard')}
style={styles.cardButton}>
<Text style={styles.cardText}>+ Add new</Text>
</TouchableOpacity>
</View>
<LinearGradient
useAngle={true}
angle={90}
// angleCenter= {{ x: 0.5, y: 0.5}}
// start={{ x: 0.11, y: 0.95 }}
// end={{ x: 0.0, y: 0.95 }}
locations={[0.0, 1.0]}
colors={['#232526', '#414345']}
style={[styles.flexColBetween, styles.SelectCard]}>
<View style={styles.selectCardContent} >
<Text style={styles.atmCardText}>
54** **** **00 0123
</Text>
</View>
<View style={styles.selectCardBottomContent}>
<View style={styles.flexRowBetween}>
<Text style={styles.selectCardName}><NAME></Text>
<Text style={styles.selectCardName}>12/20</Text>
<View style={{ alignSelf: 'center' }}>
<Amex />
</View>
</View>
</View>
</LinearGradient>
<View style={styles.deletedCard}>
<View style={styles.flexRowStart}>
<View style={styles.deletedIcon}>
<Delete height={10} width={10} />
</View>
<Text style={styles.deleteText}>Delete Card</Text>
</View>
</View>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('MonthlyPlan')}
style={styles.addCardButton}>
<Text style={styles.atmBottomButton}>Pay Now</Text>
</TouchableOpacity>
</View >
);
}
}
<file_sep>/storyqube-dev-mobile-app-master/component/home/Notification.js
import React from 'react';
import {
Text,
PixelRatio,
Dimensions,
TouchableOpacity,
Image,
View,
} from 'react-native';
import styles from '../Styles'
import Back from '../assets/notification/back.svg'
import Close from '../assets/notification/close.svg'
const cards = [
{
id: 1,
source: require(`../assets/cards/1.png`)
},
{
id: 2,
source: require(`../assets/cards/2.png`)
},
{
id: 3,
source: require(`../assets/cards/3.png`)
},
{
id: 4,
source: require(`../assets/cards/4.png`)
}
]
const results = [
{
id: 1,
new: '',
text: ' Your bag of plastic is full and ready to come to us',
time: '3 hours ago'
},
{
id: 2,
new: '',
text: 'You are halfway filling your E-Bag',
time: 'yesterday'
},
{
id: 3,
new: '',
text: 'We have updated our maps. Take a look',
time: 'A week ago'
},
]
export default class NotificationScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<Image style={styles.backgroundImage} source={require('../assets/HomeScreen.png')} />
<TouchableOpacity
onPress={() => this.props.navigation.goBack()}
style={styles.referralHeader}>
<Back width={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)}
height={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)} />
<Text
style={styles.referralBack} >
Notification
</Text>
</TouchableOpacity>
{
results.map((result, index) => {
return (
<View
key={result.id}
style={{
position: 'absolute',
top: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (8 + ((16 * index))) / 100),
width: '100%',
borderBottomWidth: 1,
borderBottomColor: '#20203E',
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (16) / 100),
}}>
<View style={[styles.flexRowStart, styles.notificationContentRow]} >
<View style={[styles.flexColCenter, styles.notificationContentRowLeft]}>
<Image style={{
height: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
width: PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (7) / 100),
}} source={require('../assets/notification/1.png')} />
</View>
<View style={[styles.flexColStart, styles.notificationContentRowCenter]}>
<View>
{
result.new ?
(
result.new === 'story' ?
(
<Text style={styles.notificationContentRowCenterNew} >
New Story:
<Text style={styles.notificationContentRowCenterText} >
{result.text}
</Text>
</Text>) :
(
<Text style={styles.notificationContentRowCenterNew} >
New Episode:
<Text style={styles.notificationContentRowCenterText} >
{result.text}
</Text>
</Text>
)
) :
<Text style={styles.notificationContentRowCenterWhite} >
{result.text}
</Text>
}
</View>
<View style={styles.notificationRating}>
<View style={styles.flexRowStart}>
<Text style={styles.notificationRatingText}>{result.time}</Text>
</View>
</View>
</View>
<View style={{
alignSelf: 'center'
}}>
<Close />
</View>
</View>
</View>
)
})
}
</View >
);
}
}
<file_sep>/storyqube-dev-mobile-app-master/component/home/Search.js
import React from 'react';
import {
NativeModules,
LayoutAnimation,
ScrollView,
Text,
TextInput,
PixelRatio,
Dimensions,
Platform,
TouchableOpacity,
Image,
View,
} from 'react-native';
import Search from '../assets/search.svg'
import AsyncStorage from '@react-native-community/async-storage';
import styles from '../Styles'
import Back from '../assets/notification/back.svg'
import Message from '../assets/Message.svg'
import Twitter from '../assets/Twitter.svg'
import InviteLogo from '../assets/InviteLogo.svg'
import About from '../assets/myAccount/about.svg'
import SignOut from '../assets/myAccount/signout.svg'
import SubscriptionCard from '../assets/myAccount/SubscriptionCard.svg'
import ReferralCard from '../assets/myAccount/ReferralCard.svg'
import LearningCard from '../assets/myAccount/LearningCard.svg'
import RateCard from '../assets/myAccount/RateCard.svg'
import SupportCard from '../assets/myAccount/SupportCard.svg'
import AboutCard from '../assets/myAccount/AboutCard.svg'
import SignOutCard from '../assets/myAccount/SignOutCard.svg'
import Star from '../assets/star.svg'
import Star1 from '../assets/star1.svg'
const { UIManager } = NativeModules;
const cards = [
{
id: 1,
source: require(`../assets/1.png`)
},
{
id: 2,
source: require(`../assets/2.png`)
},
{
id: 3,
source: require(`../assets/3.png`)
},
{
id: 4,
source: require(`../assets/4.png`)
}
]
const results = [
{
id: 1,
name: '<NAME>'
},
{
id: 2,
name: 'Agent 67'
},
{
id: 3,
name: '<NAME>'
},
{
id: 5,
name: 'agent 007'
},
{
id: 4,
name: 'Friday The 13th'
}
]
if (
Platform.OS === "android" &&
UIManager.setLayoutAnimationEnabledExperimental
) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
export default class AboutScreen extends React.Component {
state = {
search: ''
};
onChangeText = (text) => {
LayoutAnimation.configureNext(
LayoutAnimation.create(
300,
LayoutAnimation.Types.easeInEaseOut,
LayoutAnimation.Properties.scaleXY
)
);
this.setState({ search: text })
}
render() {
return (
<View style={styles.container}>
<Image style={styles.backgroundImage} source={require('../assets/HomeScreen.png')} />
<View style={{ backgroundColor: '#041c05' }}>
<View style={[styles.flexRowStart, styles.searchBar]}>
{
this.state.search !== '' &&
<TouchableOpacity
onPress={() => this.setState({ search: '' })}
style={{ alignSelf: 'center' }} >
<Back width={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)}
height={PixelRatio.roundToNearestPixel(Dimensions.get('window').height * (3) / 100)} />
</TouchableOpacity>
}
<TextInput
style={styles.searchBarText}
placeholder='Search Here'
placeholderTextColor='#747686'
onChangeText={text => this.onChangeText(text)}
/>
<View style={styles.searchBarLogo} >
<Search height={25} width={25} />
</View>
</View>
</View>
<ScrollView>
<View style={styles.flexRowStart}>
<View style={styles.homeTitle}>
<Text style={styles.homeTitleText}>Know our Partners</Text>
</View>
</View>
<View style={[styles.flexRowStart, styles.searchHorizontalContent]}>
<ScrollView
horizontal={true}
height={160}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
// contentContainerStyle={{ width: 20 }}
decelerationRate="fast"
>
{
cards.map(card => {
console.log(card.id)
return (
<Image key={card.id} style={styles.searchHorizontalContentImage} source={card.source} />
)
})
}
</ScrollView>
</View>
</ScrollView>
</View>
);
}
}
| ce9ecbddc94cf578b513bdeaada46ae2e5c548b9 | [
"JavaScript"
] | 12 | JavaScript | ShivaniSingh1501/Aspireathon-WasteBuster | 167d5789738639719b68f8e9684cbaff40b47321 | f731c4ccc38a21034263df5d22415f1a60282c2f |
refs/heads/master | <file_sep>"""textutil URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
# path('admin/', admin.site.urls),
# arguments of path first is destination loaction
# path('', views.index, name='home'),
# url(r'^$', TemplateView.as_view(template_name='static_pages/index.html'),
# name='home'),
url(r'^admin/', admin.site.urls),
# the regex ^$ matches empty
url(r'^$', TemplateView.as_view(template_name='static_pages/index.html'),
name='home'),
# arguments of path first is destination loaction this must prest in views.py file
path('amit', views.amit, name='this is amit page'),
path('about', views.about, name='about'),
path('text_analyzer', views.input_area, name='input'),
path('analysed_text', views.output_area, name='output')
]
<file_sep># i have created this file stream_cipher
from django.http import HttpResponse
from django.shortcuts import render
# without template
def amit(requst):
return HttpResponse("this is amit wala page")
# with template
def about(requst):
return render(requst, 'about.html'
)
def index(requst):
return render(requst, 'index.html')
def input_area(requst):
return render(requst, 'input_text.html')
def output_area(requst):
# retriving the input text that was entered by user in input_text.html that we had sent to analysed_text url with form ation with get method
text = requst.GET.get('input_text', 'default')
# storin this string to dictionaly and sending it to the final result page output_text.html
result = {'analysed_text': text}
return render(requst, 'output_text.html', result)
| 24bb01c6f763bc74674aa3eff56c0d93c083ff49 | [
"Python"
] | 2 | Python | StremCipher/crm1 | 7f99fef5475bdc7e16cac798e54fd56023a365af | 90ece6cd17dacf5b6d7489eb2562a8cbe0dbbd26 |
refs/heads/main | <repo_name>linav92/gestor_project<file_sep>/app/controllers/projects_controller.rb
class ProjectsController < ApplicationController
http_basic_authenticate_with name: "desafiovamoscontodo", password: "<PASSWORD>", only: :dashboard
def index
end
def dashboard
if params[:state].present?
@projects=Project.where('state = ?', params[:state])
# @project=Project.where(states:params[:states]).all
else
@projects = Project.all
end
end
def create
@project = Project.create(name: params[:name],
description: params[:description],
start_on: params[:start_on],
finish_on: params[:finish_on],
state: params[:state])
@project.save
end
end
<file_sep>/app/models/project.rb
class Project < ApplicationRecord
validates :name, :description, presence: true
enum state: {Propuesta: 0, En_progreso: 1, Terminado: 2}
before_save :has_states
def has_states
if self.state.nil?
self.state = "Propuesta"
end
end
end
| f7749c496934377af5748d5bf2152e3bb5d73277 | [
"Ruby"
] | 2 | Ruby | linav92/gestor_project | 031a68a9f2e355f0913137d401ed75cc208afd48 | 5338e87a75eea5de91cbd2055a83196d35fdc4df |
refs/heads/master | <repo_name>visiting-scientist-3217/ciat_mtods<file_sep>/unittests.py
#!/usr/bin/python
import utility # must be first cause of monkey-patching
import unittest
import traceback
from unittest_helper import PostgreRestorer as PGR
import chado
import os
import cx_oracle
import cassava_ontology
import getpass
import migration
import table_guru
# Half-Global connections to speed things up a lot.
# Note that the other test will use these connections.
class ConTest(unittest.TestCase):
# Get Chado-,Oracle -DB connections, and the Ontology
chadodb = chado.ChadoPostgres(host='127.0.0.1', usr='drupal7')
linker = chado.ChadoDataLinker(chadodb, 'mcl_pheno', 'mcl_pheno')
oracledb = cx_oracle.Oracledb()
oracledb.connect()
cass_onto = cassava_ontology.CassavaOntology(oracledb.cur)
# Asure we got it.
def test_connections_not_none(self):
self.assertIsNotNone(self.chadodb)
self.assertIsNotNone(self.oracledb)
self.assertIsNotNone(self.oracledb.con)
self.assertIsNotNone(self.oracledb.cur)
self.assertIsNotNone(self.linker)
class PostgreTests(unittest.TestCase):
longMessage = True
tmp = utility.PostgreSQLQueries.select_linked_phenotype
TEST_SQL_ALL_LINKED = tmp.format(select='p.value,s.uniquename,p.uniquename')
# set variables used in tearDown
@classmethod
def setUpClass(cls):
cls.cvts = ['abc', 'def']
cls.stocks = ['12 GM 2319023 z', '12 GM 2319023 lsd', '12 GM 2319023 AAlsd']
cls.sites = [
{'nd_geolocation.description' : 'I am somewhere',
'nd_geolocation.altitude' : '1',
'nd_geolocation.latitude' : '666N',
'nd_geolocation.longitude' : ' 73W'},
{'nd_geolocation.description' : 'I have never been here',
'nd_geolocation.altitude' : '2',
'nd_geolocation.latitude' : ' 038',
'nd_geolocation.longitude' : '87'},
]
cls.sites_clean = [ # used for deletion, and tests
{'nd_geolocation.description' : 'I am somewhere',
'nd_geolocation.altitude' : '1',
'nd_geolocation.latitude' : '666',
'nd_geolocation.longitude' : '-73'},
{'nd_geolocation.description' : 'I have never been here',
'nd_geolocation.altitude' : '2',
'nd_geolocation.latitude' : '38',
'nd_geolocation.longitude' : '87'},
]
cls.pheno_args = [
['GY200922', 'GY200923', 'GY200924'], #uniq
cls.stocks,
[{'some_property' : 777134, 'another_prop' : 'ok well done'},
{'some_property' : 777134},
{'some_property' : 977134},
]
]
cls.pheno_kwargs = {
'others' : [{'pick_date': 12, 'plant_date' : 13},
{'pick_date': 21, 'plant_date' : 31},
{}
]
}
cls.pheno_kwargs['others'][0].update({'site_name' : cls.sites[0]['nd_geolocation.description' ]})
cls.pheno_kwargs['others'][1].update({'site_name' : cls.sites[1]['nd_geolocation.description' ]})
cls.props = [
[cls.stocks[0], 'Avaluuea',],
[cls.stocks[1], 'Bvaluauaeas',],
]
cls.props_type = 'icontain'
# remove all the things
# sadly we cannot: ConTest.chadodb.con.rollback()
#@classmethod
#def tearDownClass(cls):
def tearDown(self):
# get a new cursor in case something went wrong
ConTest.chadodb.con.commit()
ConTest.chadodb.c = ConTest.chadodb.con.cursor()
for c in self.cvts:
ConTest.chadodb.delete_cvterm(c, cv=ConTest.linker.cv,
and_dbxref=True)
for s in self.stocks:
ConTest.chadodb.delete_stock(s)
for g in self.sites_clean:
ConTest.chadodb.delete_geolocation(keys=g)
for sps in self.props:
ConTest.chadodb.delete_stockprop(val=sps[1], type=self.props_type)
for descs,id in zip(self.pheno_args[2], self.pheno_args[0]):
for trait in descs.keys():
p = chado.ChadoDataLinker.make_pheno_unique(id, trait)
ConTest.chadodb.delete_phenotype(uniquename=p, del_attr=True,
del_nd_exp=True)
for spp in self.pheno_kwargs['others']:
ConTest.chadodb.delete_stockprop(keyval=spp)
if hasattr(self, 'oracle'):
self.oracle.get_first_n = self.ora_f1_backup
self.oracle.get_n_more = self.ora_f2_backup
def test_organism_funcs(self):
genus = 'test_genus'
species = 'test_species'
ConTest.chadodb.create_organism(genus, species)
self.assertTrue(ConTest.chadodb.has_species(species))
self.assertTrue(ConTest.chadodb.has_genus(genus))
ConTest.chadodb.delete_organism(genus, species)
self.assertFalse(ConTest.chadodb.has_species(species))
self.assertFalse(ConTest.chadodb.has_genus(genus))
def data_first_n(self):
return self.tableguru_data[0]
def data_next_n(self):
if not hasattr(self, 'i'): self.i = 0
if i < len(self.tableguru_data)-1: return self.tableguru_data[self.i]
def test_table_guru_with_preset_data(self):
self.oracle = ConTest.oracledb
# we override these functions, so the table_guru will gets its data
# from us, and not from the oracledb
self.ora_f1_backup = self.oracle.get_first_n
self.ora_f2_backup = self.oracle.get_n_more
self.oracle.get_first_n = lambda *a,**kw: self.data_first_n()
self.oracle.get_n_more = lambda *a,**kw: self.data_next_n()
#def test_cvterm_tasks(self):
def test_all_tasks_cuz_spreadsheets_wanted_state(self):
ts = ConTest.linker.create_cvterm(self.cvts)
pre_len = len(ConTest.chadodb.get_cvterm())
for t in ts:
t.execute()
post_len = len(ConTest.chadodb.get_cvterm())
msg = 'creation of cvterms failed'
self.assertEqual(pre_len + len(self.cvts), post_len, msg)
cvterms = [i.name for i in ConTest.chadodb.get_cvterm()]
self.assertIn(self.cvts[0], cvterms, msg)
self.assertIn(self.cvts[1], cvterms, msg)
msg = 'creation of dbxref accession failed'
dbxrefs = [i.accession for i in ConTest.chadodb.get_dbxref()]
self.assertIn(self.cvts[0], dbxrefs, msg)
self.assertIn(self.cvts[1], dbxrefs, msg)
#def test_stock_tasks(self):
organism = ConTest.chadodb.get_organism()[0]
ts = ConTest.linker.create_stock(self.stocks, organism)
pre_len = len(ConTest.chadodb.get_stock())
for t in ts:
t.execute()
post_len = len(ConTest.chadodb.get_stock())
msg = 'creation of stocks failed'
self.assertEqual(pre_len + len(self.stocks), post_len, msg)
stocks = [i.uniquename for i in ConTest.chadodb.get_stock()]
for s in self.stocks:
self.assertIn(s, stocks, msg)
#def test_geolocation_tasks(self):
ts = ConTest.linker.create_geolocation(self.sites)
pre_len = len(ConTest.chadodb.get_nd_geolocation())
for t in ts:
t.execute()
post_len = len(ConTest.chadodb.get_nd_geolocation())
msg = 'creation of geolocations failed'
self.assertGreaterEqual(pre_len + len(self.sites), post_len, msg)
msg = 'equal comparison of geolocations failed'
self.assertEqual(pre_len + len(self.sites), post_len, msg)
sts = [i.description for i in ConTest.chadodb.get_nd_geolocation()]
self.assertIn(self.sites[0]['nd_geolocation.description'], sts, msg)
self.assertIn(self.sites[1]['nd_geolocation.description'], sts, msg)
lats = [i.latitude for i in ConTest.chadodb.get_nd_geolocation()]
msg = 'translation of coordinates failed'
self.assertIn(float(self.sites_clean[1]['nd_geolocation.latitude']),
lats, msg)
#def test_stockprop_tasks(self):
vals = ','.join("'"+s+"'" for s in self.stocks)
where = "uniquename = ANY(ARRAY[{}])".format(vals)
stocks = ConTest.chadodb.get_stock(where=where)
if not len(stocks) == len(self.stocks):
msg = 'Cannot execute stockprop test, as stock test failed'
raise RuntimeError(msg)
ts = ConTest.linker.create_stockprop(self.props, self.props_type)
pre_len = len(ConTest.chadodb.get_stockprop())
for t in ts:
t.execute()
post_len = len(ConTest.chadodb.get_stockprop())
msg = 'stockprop creation failed'
self.assertEqual(pre_len + len(self.props), post_len, msg)
stockprops = ConTest.chadodb.get_stockprop()
a = [i for i in stockprops if i.value == self.props[0][1]]
b = [i for i in stockprops if i.value == self.props[1][1]]
msg = 'stockprop value not found'
self.assertTrue(a != [], msg)
self.assertTrue(b != [], msg)
a = a[0]
b = b[0]
stocks = ConTest.chadodb.get_stock()
a_stock = [i for i in stocks if i.uniquename == self.stocks[0]]
b_stock = [i for i in stocks if i.uniquename == self.stocks[1]]
a_id = a_stock[0].stock_id
b_id = b_stock[0].stock_id
msg = 'stockprop ordering failed'
self.assertEqual(a.stock_id, a_id, msg)
self.assertEqual(b.stock_id, b_id, msg)
#def test_phenotype_tasks(self):
ts = ConTest.linker.create_phenotype(*self.pheno_args,
**self.pheno_kwargs)
nphenoes = len(self.pheno_args[2])
for p in self.pheno_args[2]:
if type(p) == dict:
nphenoes += len(p) - 1
print '\n=== Tasks Start (small test suite) ==='
utility.Task.print_tasks(ts)
pre_len = len(ConTest.chadodb.get_phenotype())
utility.Task.parallel_upload(ts)
post_len = len(ConTest.chadodb.get_phenotype())
msg = 'creation of phenotypes failed'
self.assertGreaterEqual(post_len, pre_len + nphenoes, msg)
# check if we linked all the things correctly
sql = self.TEST_SQL_ALL_LINKED
ConTest.chadodb.c.execute(sql)
r = ConTest.chadodb.c.fetchall()
phenoes = set(i[0] for i in r)
pheno_uniqenames = set(i[2] for i in r)
stocks = set(i[1] for i in r)
for s in self.stocks:
self.assertIn(s, stocks)
for descs,id in zip(self.pheno_args[2], self.pheno_args[0]):
for trait in descs.keys():
uniquename = chado.ChadoDataLinker.make_pheno_unique(id, trait)
self.assertIn(uniquename, pheno_uniqenames)
for ps in self.pheno_args[2]:
for v in ps.values():
self.assertIn(str(v), phenoes)
# check geolocation linking
sql = '''
SELECT g.description FROM nd_experiment AS e
JOIN nd_geolocation g
ON g.nd_geolocation_id = e.nd_geolocation_id
WHERE g.nd_geolocation_id != 1
'''
ConTest.chadodb.c.execute(sql)
r = set(i[0] for i in ConTest.chadodb.c.fetchall())
for g in self.sites_clean:
self.assertIn(g['nd_geolocation.description'], r)
class OracleTests(unittest.TestCase):
longMessage = True # Append my msg to default msg.
cass_onto = ConTest.cass_onto
def test_tablegurus_ontology_creation(self):
onto, onto_sp = self.cass_onto.onto, self.cass_onto.onto_sp
cvt0 = 'Numero de plantas cosechadas'
self.assertEqual(onto_sp[0].SPANISH, cvt0, 'First cvt changed, bad!')
self.assertEqual(onto_sp[0].COLUMN_EN, 'NOHAV')
self.assertEqual(len(onto_sp), 24, 'Size changed, interesting.')
self.assertEqual(len(onto), len(set(onto)), 'Double entries, bad!')
class BigTest(unittest.TestCase):
'''Monolitic tests, building up some state.'''
enableThisMonoliticTestWithLongDuration = True
# Append my msg to default msg.
longMessage = True
# Number of Oracle rows used. If 'None' all data will be imported.
NTEST = None
def step10_stateful_setup(self):
self.done_pg_backup = False
self.need_rollback = False
self.done_restore = False
self.oracle = ConTest.oracledb
self.t1 = migration.Migration.TABLES_MIGRATION_IMPLEMENTED[0]
self.tg = table_guru.TableGuru(self.t1, self.oracle, update=True,
verbose=True)
self.pgr = PGR()
self.n_phenos0 = self.__get_pheno_count()
def step11_create_upload_tasks(self):
self.pgr.dump()
print '-- done backup'
self.done_pg_backup = True
self.need_rollback = True
self.ts_gen = self.tg.create_upload_tasks(test=self.NTEST)
def step12_upload_data(self):
print '-- need rollback'
for task_suite in self.ts_gen:
#print '\n=== Tasks Start (big test suite) ==='
#utility.Task.print_tasks(task_suite)
#print '=== Tasks End (big test suite) ==='
utility.Task.non_parallel_upload(task_suite)
# better not let all the data hang around in memory
ConTest.chadodb.con.commit()
def step20_inside_tests(self):
if not self.need_rollback:
print '[-] cannot do inside tests, as no data was uploaded'
return
# ...
def step90_stateful_teardown(self):
if self.need_rollback:
wait=True
else:
wait=False
self.cleanup(wait_for_inp=wait)
def step91_after_tests(self):
# Open connection again to test, if the state reverted properly.
ConTest.chadodb._ChadoPostgres__connect(chado.DB, chado.USER,
chado.HOST, chado.PORT)
msg = 'PG Restore failed! You should restore the DB manually.'
self.assertEqual(self.n_phenos0, self.__get_pheno_count(), msg)
def cleanup(self, wait_for_inp=True):
'''Wait for <Return>, then check if we need and can do a db rollback, if
so: do it.'''
if wait_for_inp:
print 'Press <Return> to restore the database.'
try:
input()
except Exception:
pass
if not self.done_pg_backup and self.need_rollback:
print '[-] Need manual db rollback.. '
if self.done_pg_backup and self.need_rollback and not\
self.done_restore:
# Close all connections before we can restore..
ConTest.chadodb.c.close()
ConTest.chadodb.con.close()
self.tg.chado.c.close()
self.tg.chado.con.close()
# now restore..
print '-- restoring'
if self.pgr.restore():
self.done_restore = True
if self.done_restore:
os.remove(self.pgr.dumpfile)
def _steps(self):
for name in sorted(dir(self)):
if name.startswith("step"):
yield name, getattr(self, name)
def test_steps(self):
if BigTest.enableThisMonoliticTestWithLongDuration:
for name, step in self._steps():
try:
step()
except Exception as e:
traceback.print_exc(e)
self.cleanup(wait_for_inp=True)
break
def __get_pheno_count(self):
return ConTest.chadodb.count_from('phenotype')
class UtilityTests(unittest.TestCase):
def test_uniq_func(self):
a = [1, 2, 3, 1, 2]
b = [1, 32, '1', 'f']
c = [1, 32, '1', 'f', 32]
self.assertNotEqual(utility.uniq(a), a)
self.assertEqual(utility.uniq(b), b)
self.assertNotEqual(utility.uniq(c), c)
d = [[1, 'a'], [3, 'a']]
self.assertEqual(utility.uniq(d, key=lambda x: x[0]), d)
self.assertNotEqual(utility.uniq(d, key=lambda x: x[1]), d)
def run():
ts = unittest.TestSuite()
tl = unittest.TestLoader()
ts.addTest(tl.loadTestsFromTestCase(ConTest))
ts.addTest(tl.loadTestsFromTestCase(UtilityTests))
ts.addTest(tl.loadTestsFromTestCase(PostgreTests))
ts.addTest(tl.loadTestsFromTestCase(OracleTests))
ts.addTest(tl.loadTestsFromTestCase(BigTest))
runner = unittest.TextTestRunner()
runner.run(ts)
if __name__ == '__main__':
run()
<file_sep>/migration.py
'''The Migration-Task-Class'''
import utility # must be first cause of monkey-patching
import os
import table_guru
import threading
from utility import Task
# Note: this v is not the official cx_Oracle library, but a convenient wrapper.
import cx_oracle
class Migration(utility.VerboseQuiet):
'''Handler of the migration/translation task.
The attribute .only_update decides if we get all data, or only the new data
from the Oracle database.
Tasks are selected by following methods:
.full() migrate all known tables
basedir=<default:$PWD>
.single(<table>) migrate <table>
'''
TABLES_MIGRATION_IMPLEMENTED = [
'VM_RESUMEN_EVAL_AVANZADAS',
]
TABLES_MIGRATION_NOT_IMPLEMENTED = [
'VM_RESUMEN_ENFERMEDADES',
'VM_RESUMEN_EVAL_CALIDAD',
'VM_RESUMEN_EVAL_MOSCA_BLANCA',
]
# Default Chado DB and CV names.
DB_NAME = 'mcl_pheno'
CV_NAME = 'mcl_pheno'
BASE_DIR = ''
def __init__(self, verbose=False, quiet=False, basedir=None, **tgargs):
'''We set some configuration, connect to the database, and create a
local cursor object.
Arguments:
verbose print lots of debug info
quiet daemon mode, be silent
'''
super(self.__class__, self).__init__()
if basedir:
self.BASE_DIR = basedir
else:
self.BASE_DIR = os.getcwd()
self.VERBOSE = verbose
self.QUIET = quiet
self.db = cx_oracle.Oracledb()
if self.VERBOSE: self.db.debug = True
self.connection, self.cursor = self.db.connect()
self.vprint('[+] connected')
self.tg = table_guru.TableGuru('', self.db, self.VERBOSE,
basedir=basedir, **tgargs)
def __get_tables(self):
self.cursor.execute(utility.OracleSQLQueries.get_table_names)
table_names = self.cursor.fetchall()
if not table_names:
raise RuntimeError('[.__get_tables] failed to fetch table names')
table_names = [t[0] for t in table_names]
return table_names
def full(self):
'''We call the table migration task for all tables in
TABLES_MIGRATION_IMPLEMENTED.
'''
if not os.path.exists(self.BASE_DIR):
msg = '[.full] non existent path "{}"'
raise RuntimeError(msg.format(self.BASE_DIR))
self.vprint('[+] basedir = "{0}"'.format(self.BASE_DIR))
for table in self.__get_tables():
if table in self.TABLES_MIGRATION_IMPLEMENTED:
self.single(table)
def single(self, table):
'''Migrates a single table, including upload if specified.'''
self.vprint('[+] starting migrate({})'.format(table))
self.tg.table = table
tasks_generator = self.tg.create_upload_tasks()
for suite in tasks_generator:
Task.parallel_upload(suite)
<file_sep>/resetter.py
#!/usr/bin/python
import unittest_helper
try:
p = unittest_helper.PostgreRestorer()
except Exception as e:
raw_input('{}, try again <Return>'.format(e))
p = unittest_helper.PostgreRestorer()
p.dumpfile = 'chado.dump'
p.restore()
<file_sep>/task_storage.py
class TaskStorage:
'''
Global storage for Tasks.
Note that I'd rather rewrite chado.py, but there aint no time for that.
'''
pass
<file_sep>/unittest_helper.py
'''As keeping track of all the data we inter into Chado is tedious, we just
rollback the whole chado schema.'''
import os
import datetime, time
try:
from commands import getstatusoutput
except ImportError:
from subprocess import getstatusoutput
# TODO make that sudo v configurable!
# TODO {db} needs to be configurable too!
class PostgreRestorer():
'''Python Wrapper for the pg_dump and pg_restore cmd-line tools.'''
c_dump = 'sudo -u postgres pg_dump -Fc {db}'
c_drop = 'sudo -u postgres psql {db} -c "DROP SCHEMA chado CASCADE;"'
c_crea = 'sudo -u postgres psql {db} -c "CREATE SCHEMA chado;"'
c_res = 'sudo -u postgres pg_restore -j 16 --dbname={db} --schema=chado '
#c_drop = 'sudo -u postgres dropdb {db}'
#c_crea = 'sudo -u postgres createdb {db}'
#c_res = 'sudo -u postgres pg_restore -j 16 --dbname={db} '
MASTERDUMP = os.path.join(os.path.expanduser('~'), 'ciat', 'ALLDB.dump')
def __init__(self, db='drupal7', basedir='', fname='chado.dump'):
self.basedir = basedir
self.dumpfile = os.path.join(self.basedir, fname)
if os.path.exists(self.dumpfile):
now = time.strftime('%m_%d_%H-%M-%S_', time.localtime())
self.dumpfile = now + self.dumpfile
self.db = db
self.__check_masterdump()
def __check_masterdump(self, days=2):
'''Check for existence of a complete dump in the last <days>.'''
if not os.path.exists(self.MASTERDUMP):
msg = 'FAIL, no masterdump @{}'.format(self.MASTERDUMP)
raise RuntimeError(msg)
stat = os.stat(self.MASTERDUMP)
m_time = datetime.datetime.fromtimestamp(stat.st_mtime)
now = datetime.datetime.now()
if (now - m_time).days > days:
msg = 'Should renew your {}'.format(self.MASTERDUMP)
raise Warning(msg)
def __known_special_case(self, s, o):
'''Check status and output for known (ignorable) values.'''
lines = o.split('\n')
if 'WARNING: errors ignored' in lines[-1]:
return True # no problem
return False
def __exe_c(self, cmd):
'''Print execute, and throw on non-0 return value.'''
cmd = cmd.format(db=self.db)
s, o = getstatusoutput(cmd)
if s != 0:
msg = '[!] cmd $({cmd}) returned "{val}":\n{out}'
msg = msg.format(cmd=cmd, out=str(o)[:1000], val=s)
if self.__known_special_case(s, o):
print '[warning:{0}] {1}'.format(s, msg)
else:
raise RuntimeError(msg)
else:
print '[+] {}'.format(cmd)
return o
def dump(self):
'''Dump current chado data of our DB.'''
o = self.__exe_c(self.c_dump)
fd = open(self.dumpfile, 'w')
fd.write(o)
fd.close()
def restore(self):
'''Restore current chado data of our DB, returns True on success.'''
drop_success, crea_success, res_success = False, False, False
for tries in range(3):
try:
if not drop_success:
self.__exe_c(self.c_drop)
drop_success = True
if not crea_success:
self.__exe_c(self.c_crea)
crea_success = True
if not res_success:
self.__exe_c(self.c_res + self.dumpfile)
res_success = True
break
except Exception as e:
print '[.restore] failed cuz {}'.format(e)
try:
raw_input('[.restore] Try fixit and press <Enter>')
except KeyboardInterrupt:
return False
except EOFError:
continue
else:
return False
return True
<file_sep>/cx_oracle.py
#!/usr/bin/python
'''\
Sample implementation of the cx_Oracle library.
We only handle connection establishment, and return a raw connection/cursor
object.
Usage: {0} <table_name>
Note:
We will ask you for a database password if necessary.
The default user account is {1}.\
'''
import utility
import cx_Oracle
import sys
from getpass import getpass
import os # environ -> db pw
from utility import OracleSQLQueries as OSQL
# Don't worry he said, it's all internal he said.
USR = 'yuca05'
H_KAPPA = 'kappa.ciat.cgiar.org'
H_RESEARCH = 'research.ciat.cgiar.org'
PORT = 1521
SID_KAPPA = 'CIAT'
SID_RESEARCH = 'CIAT'
SCHEMA = 'YUCA05'
class Oracledb():
'''Simple wrapper around cx_Oracle .makedsn, .connect, and some more basic
connection setup handling.'''
debug = False
def __init__(self, usr=USR, host=H_KAPPA, port=PORT, sid=SID_KAPPA, pw='',
schema=SCHEMA, dsn=None):
'''Defaults to initialization with global variables.
Note that if you provide a 'dsn', the 'host', 'port', and 'sid'
argument will be discarded.'''
self.USR = usr
self.HOST = host
self.PORT = port
self.SID = sid
self.__PW = pw
self.SCHEMA = schema
self.DSN = dsn
self.con = None
self.cur = None
self.saved_curs = {}
def connect(self):
'''Returns a tuple(connection_obj, cursor_obj).'''
# The following 3 if-statements MUST be exactly in this order.
if not self.DSN:
self.DSN = cx_Oracle.makedsn(self.HOST, self.PORT, self.SID)
if self.debug:
print '[+] connecting ( usr=%s, pw=1234, dsn=%s )' % (self.USR,
self.DSN)
if not self.__PW:
if os.environ.has_key('ORACLEDB_PW'):
self.__PW = os.environ['ORACLEDB_PW']
else:
self.__PW = getpass(prompt='Oracledb Password: ')
if not self.con:
self.con = cx_Oracle.connect(self.USR, self.__PW, self.DSN)
self.con.current_schema = self.SCHEMA
if not self.cur:
self.cur = self.con.cursor()
return self.con, self.cur
# Tried to find a bug, didn't work..
#@property
#def cur(self):
# print '[ORACLE] accessing cursor @', hex(id(self.c))
# return self.c
def __check_lastheaders(self, table):
if not hasattr(self, 'lasttable'):
self.lasttable = table
if not hasattr(self, 'lastheaders') or (self.lasttable != table):
self.lasttable = table
header_sql = OSQL.get_column_metadata_from.format(table=table)
self.cur.execute(header_sql)
headers = [utility.normalize(i[1]) for i in self.cur.fetchall()]
self.lastheaders = headers
def __format(self, data, table):
'formats data as namedtuples'
self.__check_lastheaders(table)
if hasattr(self, 'lastheaders') and hasattr(self, 'lasttable'):
data = utility.make_namedtuple_with_headers(self.lastheaders,
self.lasttable, data)
else:
raise RuntimeError('table not found')
return data
def get_rows(self, sql, table=None, fetchamount=None, raw=False, save_as=None):
'''Execute a <sql>-statement, returns a namedtuple.
If <table> is not given we return the raw data, else it is used to
fetch the column headers to create the namedtuples.
If <fetchamount> is given, only that amount is fetched and returned.
'''
self.cur.execute(sql.format(table=table))
if fetchamount:
data = self.cur.fetchmany(fetchamount)
else:
data = self.cur.fetchall()
if table and not raw:
self.lastraw = raw
data = self.__format(data, table)
else:
msg = 'need kwarg <table> to return non-raw data'
raise Warning(msg)
if save_as:
self.saved_curs.update({save_as : self.cur})
self.cur = self.con.cursor()
return data
def __get_tab_from_kwargs(self, kwargs):
if kwargs.has_key('table'):
table = kwargs['table']
elif hasattr(self, 'lasttable'):
table = self.lasttable
else:
raise RuntimeError('Don\'t have table, but needed to __format()')
return table
def get_first_n(self, sql, n, **kwargs):
'''additional **kwargs will be used to sql.format(**kwargs)'''
sql = (sql + OSQL.first_N_only).format(N=n, **kwargs)
self.cur.execute(sql)
table = self.__get_tab_from_kwargs(kwargs)
return self.__format(self.cur.fetchall(), table)
def get_n_more(self, sql, n, offset=0, **kwargs):
'''additional **kwargs will be used to sql.format(**kwargs)'''
sql = (sql + OSQL.offset_O_fetch_next_N).format(N=n, O=offset, **kwargs)
self.cur.execute(sql)
table = self.__get_tab_from_kwargs(kwargs)
return self.__format(self.cur.fetchall(), table)
def fetch_more(self, n=None, raw=False, table=None, from_saved=None):
'''Fetch more result from the last query, remembering the last output
format.'''
if from_saved:
c = self.saved_curs[from_saved]
else:
c = self.cur
if not n:
data = c.fetchall()
else:
data = c.fetchmany(n)
if len(data) == 0:
return []
try:
raw = self.lastraw
except AttributeError:
raw = False
if raw:
return data
elif not table:
table = self.lasttable
self.lasttable = table
self.lastraw = raw
if hasattr(self, 'lastheaders'):
return utility.make_namedtuple_with_headers(self.lastheaders,
table, data)
else:
header_sql = OSQL.get_column_metadata_from.format(table=table)
return utility.make_namedtuple_with_query(self.con.cursor(),
header_sql, table, data)
def check_duplicates(self, table, column):
cond = 't.{0} = t1.{0} )'.format(column)
sql = (OSQL.get_all_from_uniq + cond).format(table=table)
self.cur.execute(sql)
return len(self.cur.fetchall)
def main():
'''<nodoc>'''
if len(sys.argv) < 2:
usage()
exit(1)
table = sys.argv[1]
Oracledb.debug = True
db = Oracledb()
con, c = db.connect()
sql = '''SELECT * FROM {}'''.format(table)
try:
print '[+] executing : "{}"'.format(sql)
c.execute(sql)
con.commit()
print '[+] Exito, mirame imprimiendo row[:15] -> '
for name, value in zip(c.description[:16], c.fetchone()[:16]):
print '{0:18} : {1}'.format( name[0], value )
except cx_Oracle.DatabaseError as e:
error, = e.args
print >> sys.stderr, '[f] code: %d\n[f] msg: %s' % (error.code,
error.message)
return 1
return 0
def usage():
'''Prints this file's usage as table dumping test tool.'''
print __doc__.format(sys.argv[0], USR)
def gimme_con():
'''Returns a connection object to the database with all the default
arguments.'''
db = Oracledb()
return db.connect()[0]
if __name__ == '__main__':
main()
<file_sep>/table_guru.py
import utility
from utility import OracleSQLQueries as OSQL
from utility import get_uniq_id as uid
import chado
import cassava_ontology
import ConfigParser
import os
import datetime, time
from task_storage import TaskStorage
# Path to the translation cfg file.
CONF_PATH = 'trans.conf'
GERMPLASM_TYPE = 'cultivar' # constant(3 options) from MCL
class ThisIsBad(RuntimeError): pass
class ThisIsVeryBad(RuntimeError): pass
class TableGuru(utility.VerboseQuiet):
'''This guy understands those spanish Oracle databases.
We get initialized with a table name, and are expected to fill some excel
workbook, such that MainlabChadoLoader understands it.
Keys in the TRANS and COLUMNS_DICT are table names from the
Oracle database, and if existent, they return the corresponding Oracle ->
Chado translation dictionary or the columns of the Oracle table
rspectively.
The TRANS_C dict contains constanst relationships, that have to be
populated by asking chado.
All __check_and_add_*-functions return a list() of created upload-tasks.
If none have to be added an empty list is returned.
'''
TRANS = {}
TRANS_C = {}
COLUMNS = {}
ALL_TABLES = [
'VM_RESUMEN_ENFERMEDADES',
'VM_RESUMEN_EVAL_AVANZADAS',
'VM_RESUMEN_EVAL_CALIDAD',
'VM_RESUMEN_EVAL_MOSCA_BLANCA',
]
def __init__(self, table, oracledb, verbose=False, basedir='', update=True,
chado_db='mcl_pheno', chado_cv='mcl_pheno',
chado_dataset='mcl_pheno'):
'''We initialize (once per session, nor per __init__ call!)
TableGuru.COLUMNS such that:
TableGuru.COLUMNS[<tablename>][0] -> first column name
TableGuru.COLUMNS[<tablename>][1] -> second column name..
And TableGuru.TRANS with empty dict()'s.
'''
super(self.__class__, self).__init__()
self.VERBOSE = verbose
self.QUIET = False
self.basedir = basedir
self.update = update
if not update:
raise Warning('Deprecated flag: "update", only usefull for'\
+ ' spreadsheets.')
self.oracle = oracledb
if not self.oracle.cur:
self.oracle.connect()
self.c = oracledb.cur
self.chado = chado.ChadoPostgres()
self.onto = cassava_ontology.CassavaOntology(self.c)
self.linker = chado.ChadoDataLinker(self.chado, chado_db, chado_cv)
self.table = table
self.dbname = chado_db
self.cvname = chado_cv
self.dataset = chado_dataset
self.__error_checks()
self.__setup_columns()
def __error_checks(self):
msg = 'TableGuru: Mandatory {0} not found: {1}'
if not self.cvname in [i.name for i in self.chado.get_cv()]:
raise RuntimeError(msg.format('cv', self.cvname))
if not self.dbname in [i.name for i in self.chado.get_db()]:
raise RuntimeError(msg.format('db', self.dbname))
if not self.dataset in [i.name for i in self.chado.get_project()]:
raise RuntimeError(msg.format('project/dataset', chado_dataset))
def __setup_columns(self):
if not TableGuru.COLUMNS:
for table in TableGuru.ALL_TABLES:
self.c.execute(
OSQL.get_column_metadata_from.format(table=table)
)
TableGuru.COLUMNS[table] = [
line[1] for line in self.c.fetchall()
]
msg = '[+] TableGuru.COLUMNS[{table}] = {res}'
msg = msg.format(table=table,
res=str(self.COLUMNS[table])[:30]+"... ]")
self.vprint(msg)
def __tostr(self, d):
'''Formatting helper'''
if d == None:
return ''
if type(d) is datetime.datetime:
return d.strftime('%Y-%m-%d')
else:
return str(d)
def __check_column(self, table, conf, entry):
'''Check a single entry in the currently parsed config for correcness.
If we cannot handle <entry> for <table> we return False, otherwise True
is returned.
'''
if not TableGuru.COLUMNS.has_key(table):
# This is one of the ontology tables, no need for translation.
return True
if entry in TableGuru.COLUMNS[table]:
TableGuru.TRANS[table][entry] = conf.get(table, entry)
return True
if entry.lstrip('_') in TableGuru.COLUMNS[table]:
TableGuru.TRANS[table][entry] = conf.get(table, entry)
self.vprint('Note: done lstrip(_) for "{}"'.format(entry))
return True
if TableGuru.TRANS_C.has_key(entry):
return True
value = conf.get(table, entry)
if value[:2] == '/*' and value[-2:] == '*/':
value = value.split('/*')[1].split('*/')[0]
TableGuru.TRANS_C[entry] = value.lstrip().rstrip()
return True
print '[parser-error] {k} = {v}'.format(k=entry, v=value)
return False
def __parse_translation_config(self):
'''We do extensive error checking, and might throw RuntimeError.'''
conf = ConfigParser.RawConfigParser()
if not os.path.exists(CONF_PATH):
missing_file = 'TransConfig path does not exist: {}'
raise RuntimeError(missing_file.format(CONF_PATH))
conf.read(CONF_PATH)
if not conf.has_section(self.table):
missing_sec = 'TransConfig does not have section: {}'
raise RuntimeError(missing_sec.format(self.table))
for table in conf.sections():
for column in conf.options(table):
col = column.upper() # ConfigParser does .lower() somewhere..
if not self.__check_column(table, conf, col):
msg = 'config entry could not be parsed: {0} = {1}'
msg = msg.format(col, conf.get(self.table, col))
raise RuntimeError(msg)
def get_config(self, chado_table=None, oracle_column=None):
'''Returns only the (TRANS, TRANS_C) config that match the given
arguments.'''
if not self.TRANS or not self.TRANS_C or not hasattr(self, 'tr'):
self.tr = self.get_translation()
self.tr_inv = utility.invert_dict(self.tr)
def fill_with_cond(cond, c=None, o=None):
tr = {}
ctr = {}
t_it = self.tr.iteritems()
ct_it = self.TRANS_C.iteritems()
[tr.update({k:v}) for k,v in t_it if eval(cond)]
[ctr.update({k:v}) for k,v in ct_it if eval(cond)]
return tr, ctr
if chado_table and oracle_column:
tr, ctr = fill_with_cond("v.split('.')[0] == c and k == o",
chado_table, oracle_column)
if chado_table:
tr, ctr = fill_with_cond("v.split('.')[0] == c", chado_table)
elif oracle_column:
tr, ctr = fill_with_cond("k == o", oracle_column)
else:
raise RuntimeError('Must supply either chado_table or oracle_column')
return tr, ctr
def create_equal_comparison(self, table, conf, c_conf):
'''Returns functions to compare oracle objects with chado objects.
Functions are created only for the given table, using the given config.
Return-order is:
is_eq, is_in, conf, c_conf
'''
f,f2 = None,None
if table == 'stock':
TaskStorage.known_stock_ids = []
TaskStorage.unknown_stocks = []
conf_inv = utility.invert_dict(conf)
def f(ora, chad):
if getattr(ora, conf_inv['stock.name']) != chad.uniquename:
return False
return True
def f2(ora, chads):
for c in chads:
if f(ora, c):
# it's equal, lets append its name to known names
TaskStorage.known_stock_ids.append(c.stock_id)
return True
ora_stock_name = getattr(ora, conf_inv['stock.name'])
if ora_stock_name in TaskStorage.unknown_stocks:
index = TaskStorage.unknown_stocks.index(ora_stock_name)
dup = utility.Duplicate(index)
TaskStorage.known_stock_ids.append(dup)
else:
TaskStorage.unknown_stocks.append(ora_stock_name)
TaskStorage.known_stock_ids.append(None)
return False
elif table == 'stockprop':
# need to update the mapping every round..
stocks = self.chado.get_stock()
m = {}
for s in stocks: m.update({s.name : s.stock_id})
self.map_stock_name_to_id = m
m = {}
sps = self.chado.get_stockprop()
cvts = self.chado.get_cvterm()
for sp in sps:
spname = [i for i in cvts if i.cvterm_id == sp.type_id]
assert(len(spname) == 1)
spname = spname[0].name
m.update({spname : sp.type_id})
self.map_stockprop_type_to_cvterm_id = m
def f(sp, current):
m_stockid = self.map_stock_name_to_id
m_propid = self.map_stockprop_type_to_cvterm_id
s,p = sp
if not m_stockid.has_key(s) or not m_propid.has_key(p):
return False
s_id = m_stockid[s]
p_id = m_propid[p]
if [s_id, p_id] == current:
return True
return False
def f2(sp, currents):
'''is_in([stock.name, property], [[id1,typ1],[..],..])
Must be usable like:
ids = [[i.stock_id i.type_id] for i in chado.get_stockprop()]
f([stock,prop_t], ids)
-> True if stock,prop_t is already in ids
'''
m_stockid = self.map_stock_name_to_id
m_propid = self.map_stockprop_type_to_cvterm_id
s,p = sp
if not m_stockid.has_key(s):
return False
if not m_propid.has_key(p):
msg = 'No Key: Mapping(:stock_id => :cvterm_id) "{}"'
raise Warning(msg.format(p))
s_id = m_stockid[s]
p_id = m_propid[p]
if [s_id, p_id] in currents:
return True
return False
else:
def f(ora, chad):
if chad in ora: return True
return False
def f2(ora, chads): #set
if ora.intersection(chads): return True
return False
return f,f2
def __get_compare_f(self, table):
'''Using the config file, we create and return compare functions for a
given chado table:
is_equal(oracle_item, chado_item)
is_in(oracle_item, list(chado_item[, ...]))
'''
# TODO[6] use c_conf
conf, c_conf = self.get_config(chado_table=table)
if not conf: return None, None, None, None
is_eq, is_in = self.create_equal_comparison(table, conf, c_conf)
return is_eq, is_in, conf, c_conf
def __get_needed_data(self, tab, mapping='chado', raw=False):
'''Returns data to upload as a list() of dict()'s for chado table
<tab>, a dict() which mapps oracle column to value.
This method uses all the information we have by creating dynamic
comparison functions based on: config files, chado and oracle
connection.
If <mapping> is set to 'oracle', then the returned dictionary returns
OracleDB keys instead of chado ones. This is necessary for
disambiguating phenotypes, as they all reference the 'phenotype.value'
field.
If <raw> is True, we return a second list() of dict()'s with the whole,
unfiltered oracle table entrys.
'''
if not mapping in ['chado', 'oracle']:
msg = 'unknown <mapping> argument: {0}, must be in {1}'
raise RuntimeError(msg.format(mapping, ['chado', 'oracle']))
is_equal, is_in, trg, trg_c = self.__get_compare_f(tab)
if not trg and not trg_c:
msg = '[{}] no CONFIG found => not uploading any related data'
self.qprint(msg.format(tab))
return []
if self.update:
if not is_equal or not is_in:
msg = '[{}] no translation found => not uploading any related'\
+ ' data'
self.qprint(msg.format(tab))
return []
func_name = 'get_'+tab
get_all_func = getattr(self.chado, func_name)
if not get_all_func or not callable(get_all_func):
msg = 'Chado.{} not found'
raise NotImplementedError(msg.format(func_name))
current = get_all_func()
# Default to non-override
# Both _override lists are only used for comparison
data_override = self.data
curr_override = current
if tab == 'stockprop':
curr_override = [[i.stock_id, i.type_id] for i in current]
data_override = []
for attr in dir(self.data[0]):
if self.tr.has_key(attr) and 'stockprop.' in self.tr[attr]:
for d in self.data:
data_override.append(
[getattr(d, self.tr_inv['stock.name']),
self.tr[attr][len('stockprop.'):]]
)
elif tab == 'stock':
pass
else:
curr_override = set(p.uniquename for p in self.chado.get_phenotype())
def tmp(d):
id = uid(d, self.tr_inv)
mkuniq = chado.ChadoDataLinker.make_pheno_unique #returns set
uniqnames = set(mkuniq(id, t) for t in self.pheno_traits)
return uniqnames
data_override = [tmp(d) for d in self.data]
unknown = []
for entry,entry_ovrw in zip(self.data, data_override):
if not is_in(entry_ovrw, curr_override) and not entry in unknown:
unknown.append(entry)
else:
unknown = self.data
if len(unknown) != len(set(unknown)):
if raw: eclass = ThisIsVeryBad
else: eclass = ThisIsBad
msg = '[{}] len(unknown) != len(set(unknown))'.format(tab)
raise eclass(msg)
# Blacklist contains oracle attributes, which we understand according
# to ontology or configuration, but which don't exist the OracleDB.
# This is most likely a mistake in the ontology or configuration.
# So we better pass this list to someone who is able to fix it.
blacklist = []
needed_data = []
if raw: needed_data_raw = []
for whole_entry in unknown:
entry = {}
skip = True
for ora_attr,cha_attr in trg.iteritems():
if ora_attr in blacklist:
continue
try:
# See __doc__
value = getattr(whole_entry, ora_attr)
if value == None: # eq (null) in oracle
continue
if mapping == 'chado':
entry.update(
{cha_attr : value}
)
elif mapping == 'oracle':
entry.update(
{ora_attr : value}
)
skip = False
except AttributeError as e:
blacklist.append(ora_attr)
if not skip:
needed_data.append(entry)
if raw:
needed_data_raw.append(whole_entry)
if blacklist:
msg = '[blacklist:{tab}] Consider fixing these entries in the'\
+ ' config file or the ontology'\
+ ' tables:\n\'\'\'\n{blk}\n\'\'\'\n'
self.qprint(msg.format(tab=tab, blk=blacklist))
if raw: return needed_data, needed_data_raw
return needed_data
# TODO remove this function, and replace its only usage by
# __get_or_create_cvterm
def __check_and_add_cvterms(self, maybe_known, f_ext=''):
'''Check if <maybe_known> cvterm-names already exist in Chado.
We try to find information about the requested cvterms:
-1- We check ontology. If we find information, we might create more
than one cvterm per given cvterm-name, to comply to the chado
relationship schema.
-2- If not found(^), we create raw cvterms without description.
Note that we do a case insensitive comparison while trying to find
Ontology for a term in <maybe_known>.
'''
all_cvt_names = [i.name for i in self.chado.get_cvterm()]
needed_cvts = [i for i in maybe_known if not i in all_cvt_names]
tasks = []
if not needed_cvts:
return []
needed_onto = []
for cvt in needed_cvts:
it = self.onto.mapping.iteritems()
cur = [i[1][0] for i in it if i[1][0].TRAIT_NAME.lower() ==\
cvt.lower()]
if len(cur) == 0:
continue
if len(cur) != 1: # Well crap.
msg = 'Did not find excactly one cvterm, for a single needed'\
+ ' name: {c} -> {d}'
self.qprint(msg.format(c=cvt, d=cur))
cur = [cur[0]]
needed_onto += cur
# Check if we have Ontology for all needed cvterms.
if len(needed_cvts) == len(needed_onto):
cvt_ns = [i.TRAIT_NAME for i in needed_onto]
cvt_ds = ['{cls}: {dsc}'.format(dsc=i.TRAIT_DESCRIPTION,\
cls=i.TRAIT_CLASS) for i in needed_onto]
else:
cvt_ns = needed_cvts
cvt_ds = []
return self.linker.create_cvterm(cvt_ns, definition=cvt_ds,
tname=f_ext)
def __check_and_add_stocks(self):
'''Tasks to upload the genexpression information.
This functions refers to the chado 'stock' table.
'''
stocks = self.__get_needed_data('stock')
self.vprint('[+] stocks: {} rows'.format(len(stocks)))
if stocks:
stock_ns = [i['stock.name'] for i in stocks]
#stock_us = [i['stock.uniquename'] for i in stocks]
stock_us = stock_ns
orga = self.chado.get_organism(where="common_name = 'Cassava'")[0]
germpl_t = GERMPLASM_TYPE # < TODO remove hardcoding ^
t = self.linker.create_stock(stock_ns, orga, stock_uniqs=stock_us,
germplasm_t=germpl_t)
return t
def __check_and_add_stockprops(self):
'''Tasks to upload the stockprop (stock-metadata).
This functions refers to the chado 'stockprop' table.
'''
stockprops, raw = self.__get_needed_data('stockprop', raw=True)
self.vprint('[+] stockprops: {} rows'.format(len(stockprops)))
stocks = [getattr(i, self.tr_inv['stock.name']) for i in raw]
if not stockprops:
return
t_stockprops = []
for ora_attr,chad_attr in self.tr.iteritems():
if not 'stockprop.' in chad_attr: continue
prop_t = chad_attr[len('stockprop.'):]
props = []
fail_counter = 0
for s,o in zip(stocks, stockprops):
try:
props.append([s, o[chad_attr]])
except KeyError:
fail_counter += 1
t = self.linker.create_stockprop(props, prop_t, tname=prop_t)
t_stockprops.append(t)
return t_stockprops
def __check_and_add_sites(self):
'''Creates MCL spreadsheets to upload the geolocation information.
This functions refers to the chado 'nd_geolocation' table.
'''
sites = self.__get_needed_data('nd_geolocation')
if sites:
sites = utility.uniq(sites) # needed! but don't know why
self.vprint('[+] sites: {} rows'.format(len(sites)))
mandatory_cvts = ['type', 'country', 'state', 'region', 'address',
'site_code']
t1 = self.__check_and_add_cvterms(mandatory_cvts, f_ext='pre_sites')
t2 = self.linker.create_geolocation(sites)
return (t1, t2)
else:
self.vprint('[+] sites: {} rows'.format(len(sites)))
def __check_and_add_contacts(self):
'''Creates MCL spreadsheets to upload the contact information.
This functions refers to the chado 'contact' table.
'''
tasks = []
contacts = self.__get_needed_data('contact')
self.vprint('[+] contacts: {} rows'.format(len(contacts)))
if contacts:
names = [i['contact.name'] for i in contacts]
types = [i['contact.type_id'] for i in contacts]
return tasks
def __check_and_add_phenotypes(self):
'''Creates MCL spreadsheets to upload the phenotyping data.
This functions refers to the chado 'phenotype' table.
Ontology comes into the playground here. (self.onto, ..)
'''
phenotypic_data, raw_data = \
self.__get_needed_data('phenotype', mapping='oracle', raw=True)
self.vprint('[+] phenotypes: {} rows'.format(len(phenotypic_data)))
if not phenotypic_data:
return []
# Get metadata, we need to link.
self.tr_inv = utility.invert_dict(self.tr)
# stocks needs to be passed as aditional argument
stocks = [getattr(i, self.tr_inv['stock.name']) for i in raw_data]
ids = [uid(i, self.tr_inv) for i in raw_data]
others = []
for raw_entry in raw_data:
new = {}
for k,ora_attr in self.tr_inv.iteritems():
if k == 'nd_geolocation.description':
name = getattr(raw_entry,
self.tr_inv['nd_geolocation.description'])
new.update({'site_name' : name})
if 'stockprop' in k:
value = self.__tostr(getattr(raw_entry, ora_attr))
new.update({k : value})
others.append(new)
# Get the real phenotyping data into position.
descs = []
attr_blacklist = []
for phenos in phenotypic_data:
new = {}
for k,v in phenos.iteritems():
if k in attr_blacklist:
continue
t_name = self.__get_trait_name(k)
if t_name:
new.update({t_name : v})
else:
attr_blacklist.append(k)
descs.append(new)
if attr_blacklist:
msg = '[blacklist:{tab}] Consider fixing these entries in the'\
+ ' config file or the ontology tables:\n'\
+ '\'\'\'\n{blk}\n\'\'\'\n'
self.qprint(msg.format(tab=self.table, blk=attr_blacklist))
# Note: We create needed cvterms for the descriptors syncronously on
# Task.execution(), as their numbers are low.
# Looking in the first ontology mapping and then Chado, to find the
# genus of Cassava. ('Manihot')
crp = next(self.onto.mapping.iteritems())[1][0].CROP
where = "common_name = '{}'".format(crp)
genus = self.chado.get_organism(where=where)[0].genus
t_phen = self.linker.create_phenotype(ids, stocks, descs, others=others,
genus=genus)
return t_phen
def __get_trait_name(self, trait):
'''Using self.onto.mapping, we create and return a nice trait name.
If we get a trait name, that does not exist in the Ontology, an empty
string is returned.
'''
if not self.onto.mapping.has_key(trait):
return ''
vonto = self.onto.mapping[trait]
if len(vonto) > 1:
msg = 'Warning: We dont use all information we found.'
self.qprint(msg)
vonto = vonto[0]
name = vonto.TRAIT_NAME
return name
def get_translation(self):
'''Returns the translation dictionary for the current self.table.
Note that we save that stuff in static class variables, thus after the
first invocation, we don't access that file again.
We also do extensive error checking of that config file.
'''
# There must be some manual configuration..
if not TableGuru.TRANS[self.table]:
self.__parse_translation_config()
# And the ontology..
TableGuru.TRANS[self.table].update(self.onto.get_translation())
return TableGuru.TRANS[self.table]
def create_upload_tasks(self, max_round_fetch=600000, test=None):
'''Multiplexer for the single rake_{table} functions.
Each create necessary workbooks for the specified table, save them and
returns all their names in an array.
'''
msg = '[create_upload_tasks] max_round_fetch={0}, test={1}'
self.vprint(msg.format(max_round_fetch, test))
self.tr = self.get_translation()
self.tr_inv = utility.invert_dict(self.tr)
self.pheno_traits = []
for ora,chad in self.tr.iteritems():
if 'phenotype.value' == chad:
self.pheno_traits.append(self.__get_trait_name(ora))
if test and (test < max_round_fetch):
max_round_fetch = test
sql = OSQL.get_all_from
primary_key_columns = uid(None, self.tr_inv, only_attrs=True)
uniq_col = ', '.join(primary_key_columns)
self.data = self.oracle.get_first_n(sql, max_round_fetch,
table=self.table, ord=uniq_col)
round_N = -1
fetched = 0
while True:
round_N += 1
fetched_cur = len(self.data)
fetched += fetched_cur
msg = '[+] === upload round {} ({}) ==='
self.vprint(msg.format(round_N, time.ctime()))
t = {}
t.update({'stocks' : self.__check_and_add_stocks()})
t.update({'stockprops' : self.__check_and_add_stockprops()})
t.update({'sites' : self.__check_and_add_sites()})
t.update({'contacts' : self.__check_and_add_contacts()})
t.update({'phenos' : self.__check_and_add_phenotypes()})
# Replace None values with dummies.
for k,v in t.iteritems():
if v is None:
self.vprint('[-] None-Task for {}'.format(k))
t[k] = utility.Task.init_empty()
# the tasks variable is explained in migration.py -> Task.parallel_upload
tasks = (
[ t['stocks'], t['sites'], t['contacts'], ],
[ t['phenos'], t['stockprops'] ],
)
yield tasks
if test and fetched >= test:
break
self.data = self.oracle.get_n_more(sql, max_round_fetch,
offset=fetched,
table=self.table,
ord=uniq_col)
if not self.data:
break
self.vprint('[+] === the end ({}) ==='.format(time.ctime()))
# Just fill in some empty dict()'s.
for table in TableGuru.ALL_TABLES:
try:
tmp = TableGuru.TRANS[table]
except KeyError:
TableGuru.TRANS[table] = dict()
<file_sep>/mtods.py
#!/usr/bin/python
'''\
MtODS -- _M_igrate _t_he _O_racle _D_atabase _S_tuff
.. to our Chado schema.
'''
# global
import ConfigParser # Reading the table translation file.
import optparse
import os
import sys
# local
import table_guru
import migration
import chado
BASE_DIR = os.getcwd()
CONF_FILENAME = 'trans.conf'
table_guru.CONF_PATH = os.path.join(BASE_DIR, CONF_FILENAME)
def main():
'''Read the __doc__ string of this module.'''
parser = optparse_init()
o, args = parser.parse_args()
if args:
print 'Unknown argument: "{}"'.format(args)
exit(1)
mutally_exclusive_msg = 'options {0} and {1} are mutally exclusive'
exclusive_opts = zip(
[[o.verbose,'-v'],],
[[o.quiet, '-q'],]
)
for a,b in exclusive_opts:
if a[0] and b[0]:
parser.error(mutally_exclusive_msg.format(a[1],b[1]))
if o.config_path:
table_guru.CONF_PATH = o.config_path
if o.pg_user:
chado.USER = o.pg_user
if o.pg_db:
chado.DB = o.pg_db
chado.HOST = o.pg_host
chado.PORT = o.pg_port
migra = migration.Migration(verbose=o.verbose, quiet=o.quiet,
chado_db=o.ch_db, chado_cv=o.ch_cv,
chado_dataset=o.ch_pj)
if o.single_table:
migra.single(o.single_table)
else:
migra.full()
return 0
def optparse_init():
'''Return an initialized optparse.OptionParser object, ready to parse the
command line.
'''
p = optparse.OptionParser(description=__doc__)
p.add_option('-v', '--verbose', action='store_true', dest='verbose',
help='verbose', metavar='', default=False)
p.add_option('-q', '--quiet', action='store_true', dest='quiet',
help='only print critical failure information', metavar='',
default=False)
p.add_option('-c', '--config', action='store', type='string',
dest='config_path', help=\
'path to the table translation config (default: {})'\
.format('<basedir>/'+CONF_FILENAME), metavar='<path>', default='')
pgo = optparse.OptionGroup(p, 'Postgres Connection Options', '')
pgo.add_option('-y', '--pg_host', action='store', type='string',
dest='pg_host', help='postgres hostname, defaults to localhost',
metavar='<host>', default=None)
pgo.add_option('-p', '--pg_port', action='store', type='string',
dest='pg_port', help='postgres port, defaults to 5432', metavar='N',
default=None)
pgo.add_option('-t', '--pg_user', action='store', type='string',
dest='pg_user', help='postgres user, defaults to the current user',
metavar='<user>')
pgo.add_option('-d', '--pg_db', action='store', type='string',
dest='pg_db', help='postgres db, defaults to drupal7', metavar='<db>')
pch = optparse.OptionGroup(p, 'Chado/Drupal7 Config Options',
'We require these entries to already be in the database.')
pch.add_option('--ch-db', action='store', type='string', dest='ch_db',
help='db entry used for phenotyping data (default: mcl_pheno)',
metavar='<db>', default='mcl_pheno')
pch.add_option('--ch-cv', action='store', type='string', dest='ch_cv',
help='cv entry used for phenotyping data (default: mcl_pheno)',
metavar='<cv>', default='mcl_pheno')
pch.add_option('--ch-pj', action='store', type='string', dest='ch_pj',
help='dataset entry used for phenotyping data (default: mcl_pheno)',
metavar='<pj>', default='mcl_pheno')
single = optparse.OptionGroup(p, 'Single Table Options',
'By default we get data from all tables, for which a translation is'\
' possible. Specifying this option only given table is used.')
single.add_option('-s', '--singletab', action='store', type='string',
dest='single_table', help='specify a OracleDB table to migrate',
metavar='<table>', default='')
p.add_option_group(pgo)
p.add_option_group(pch)
p.add_option_group(single)
return p
if __name__ == '__main__':
main()
<file_sep>/cassava_ontology.py
'''
Cassava Phenotyping Ontology
We need to know this for translating the columns to their chado equivalent.
'''
from collections import namedtuple
from utility import OracleSQLQueries as OSQLQ
import utility
# TODO remove this, and use utility.make_namedtuple_with_query
def get_tabledata_as_tuple(cursor, table):
'''Create a list of namedtuple's for <table> with <column_names> as
members.
Arguments:
cursor a PEP 249 compliant cursor pointing to the oracledb
table name of the table
'''
sql = OSQLQ.get_column_metadata_from.format(table=table)
cursor.execute(sql)
column_names = [line[1] for line in cursor.fetchall()]
VOntology = namedtuple('VOntology', column_names)
sql = OSQLQ.get_all_from.format(table=table)
cursor.execute(sql)
vonto = [VOntology(*line) for line in cursor.fetchall()]
return vonto
class CassavaOntology():
'''Ontology for the Cassava plant, in spanish and english.
We also provide utilities for translation.
Methods:
get_ontologies() Returns (onto, onto_sp)
Members:
onto_sp Spanish raw ontology
onto English ontology (+cvterm meta info)
mapping Mapping of the spanish ontology names to a list of all
corresponding cvterms as VOntology() objects.
'''
SPANISH_ONTOLOGY_TABLE = 'V_ONTOLOGY_SPANISH'
ONTOLOGY_TABLE = 'V_ONTOLOGY'
def __init__(self, cursor):
'''We need that cursor to the db holding chado.'''
self.c = cursor
self.onto_sp = get_tabledata_as_tuple(self.c,
self.SPANISH_ONTOLOGY_TABLE)
self.onto = get_tabledata_as_tuple(self.c, self.ONTOLOGY_TABLE)
# Get all corresponding cvterm info for the spanish names
tmp_map = [[i for i in self.onto \
if i.VARIABLE_ID == j.VARIABLE_ID_BMS] for j in self.onto_sp]
self.mapping = {}
to_remove = []
for key,value in zip(self.onto_sp, tmp_map):
if len(value) == 0:
# we did not find a mapping, so this cvterm is unusable
to_remove.append(key)
else:
self.mapping[key.SPANISH.upper()] = value
for term in to_remove:
self.onto_sp.remove(term)
def get_ontologies(self):
'''Returns the two named tuples, with the Ontology data.'''
return self.onto, self.onto_sp
# delete entries we cannot map to cvterm's
remove_these = []
for term in ontology_spanish:
if not term.VARIABLE_ID_BMS:
remove_these.append(term)
for term in remove_these:
ontology_spanish.remove(term)
return ontology, ontology_spanish
def prettyprint_ontology_mapping(self, method='METHOD_NAME'):
'''Pretty-prints the ontology mapping.'''
fmt = "{0:25} -> {1}"
l = [fmt.format(k,getattr(v[0], method)) for k,v in\
self.mapping.iteritems()]
for i in l:
print i
def get_translation(self):
'''Return a dict() out of the ontologies, mapping Oracle columns to
chado entitys.'''
d = dict()
for k in self.onto_sp:
normalized_name = utility.normalize(k.SPANISH.upper())
d.update({normalized_name : 'phenotype.value'})
return d
# So we need to join the ontology_spanish.VARIABLE_ID_BMS on
# ontology.VARIABLE_ID and after that we should be able to self join ontology
# on: ontology.TRAIT_ID .SCALE_ID and METHOD_ID
# 'select * from V_ONTOLOGY_SPANISH vos inner join V_ONTOLOGY vo on'\
# +'vos.VARIABLE_ID_BMS = vo.SCALE_ID order by vo.TRAIT_NAME'
# But we did this in python, see CassavaOntology(cursor).mapping
<file_sep>/utility.py
'''Utility includes:
- base classes
- SQL Querie namespaces
- commonly used functions
- ?
'''
# So psycopg2 is level 2 threadsave, but our std-lib is not. Here you see the
# easiest way I could think of to fix this:
from gevent import monkey
monkey.patch_all() # Needs to be executed before threading, because the
# mainthread gets indexed on that import, and gevent
# replaces the indexing function, thus will create another
# index value, which will lead to a crash, once we search
# for the index of the main thread.
import threading
from collections import namedtuple
from re import sub
class Duplicate():
def __init__(self, index):
self.index = index
def invert_dict(d):
'''Switch keys with values in a dict.'''
new = {}
for k,v in d.iteritems():
new.update({v:k})
return new
def get_uniq_id(entry, trans, only_attrs=False):
attr = [trans[k] for k in trans.keys() if k.startswith('unique_id')]
attr = [a.lstrip('_') for a in attr] # see trans.conf for an explanation
attr = sorted(attr)
if only_attrs: return attr
return '_'.join(str(getattr(entry, a)) for a in attr)
def make_namedtuple_with_query(cursor, query, name, data):
'''Return <data> as a named tuple, called <name>.
Create a named tuple called <name> using <query> and <cursor> to retreive
the headers. Then format data with the created tuple and return it.
Assumptions:
- The result of query yields a list/tuple of results, which contain the
desired name at position [1], e.g.:
[(SomeThing, 'col_name1'), (SomeThing, 'col_name2'), ...]
- Data must be iterable
'''
cursor.execute(query)
headers = [normalize(i[1]) for i in cursor.fetchall()]
return make_namedtuple_with_headers(headers, name, data)
def make_namedtuple_with_headers(headers, name, data):
# we might get non-uniq headers here
# TODO find out what happened
NTuple = namedtuple(name, uniq(headers))
result = [NTuple(*r) for r in data]
return result
def normalize(s):
'''Some string substitutions, to make it a valid Attribute.
(Not complete)
'''
ss = sub(r'\s+', '_', s)
return ss
class OracleSQLQueries():
'''Namespace for format()-able Oracle SQL Queries'''
get_table_names = '''\
SELECT TNAME FROM tab\
'''
get_column_metadata_from = '''\
SELECT table_name, column_name, data_type, data_length, COLUMN_ID
FROM USER_TAB_COLUMNS
WHERE table_name = '{table}'
ORDER BY COLUMN_ID\
'''
get_all_from = '''\
SELECT * FROM {table}\
'''
get_all_from_uniq = '''\
SELECT * FROM {table} t
WHERE NOT EXISTS (
SELECT null FROM {table} t1
WHERE
'''
first_N_only = '''
ORDER BY {ord}
FETCH FIRST {N} ROWS ONLY\
'''
offset_O_fetch_next_N = '''
ORDER BY {ord}
OFFSET {O} ROWS
FETCH NEXT {N} ROWS ONLY\
'''
class PostgreSQLQueries():
'''Namespace for format()-able PostgreSQL queries.'''
select_all = '''\
SELECT * FROM {table}\
'''
select_all_from_where_eq = '''\
SELECT * FROM {table} WHERE {col} = '{name}'\
'''
select_count = '''\
SELECT count(*) FROM {table}\
'''
insert_into_table = '''\
INSERT INTO {table} {columns} VALUES {values}\
'''
delete_where = '''\
DELETE FROM {table} WHERE {cond}\
'''
column_names = '''\
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_name='{table}'
ORDER BY ordinal_position\
'''
select_linked_phenotype = '''\
SELECT {select} FROM nd_experiment AS e
JOIN nd_experiment_stock es
ON e.nd_experiment_id = es.nd_experiment_id
JOIN nd_experiment_phenotype ep
ON e.nd_experiment_id = ep.nd_experiment_id
JOIN phenotype p
ON p.phenotype_id = ep.phenotype_id
JOIN cvterm c
ON c.cvterm_id = p.attr_id
JOIN stock s
ON s.stock_id = es.stock_id\
'''
class VerboseQuiet(object):
'''To be inherited from.'''
def __init__(self):
self.printlock = threading.Lock()
self.VERBOSE = False
self.QUIET = False
def __acq(self):
if hasattr(self, 'printlock'):
self.printlock.acquire()
def __rel(self):
if hasattr(self, 'printlock'):
self.printlock.release()
def vprint(self, s):
'''Only print stuff, if we are in verbose mode.'''
if self.VERBOSE:
self.__acq()
print s
self.__rel()
def qprint(self, s):
'''Only print stuff, if we are NOT in quiet mode.'''
if not self.QUIET:
self.__acq()
print s
self.__rel()
class Task(VerboseQuiet):
'''Used for multithreading implementation.'''
def __init__(self, name, job, *args, **kwargs):
super(self.__class__, self).__init__()
self.VERBOSE = False
self.name = name
self.job = job
self.args = args
self.kwargs = kwargs
def execute(self, thread=False):
'''Calls self.job with given args and kwargs.'''
if thread:
msg = '[exec-thrd] {}'
else:
msg = '[exec] {}'
self.vprint(msg.format(self.__str__()[:70]+'...)'))
self.job(*self.args, **self.kwargs)
def __str__(self):
s = 'Task(name={name}, job={job}, default_args={dargs},'\
+ ' args={args}, kwargs={kwargs}'
s = s.format(name=self.name, job=self.job.func_name,
dargs=self.job.func_defaults, args=self.args,
kwargs=self.kwargs)
return s
def __repr__(self):
return self.__str__()
@staticmethod
def init_empty():
'''Returns a Task that does nothing when executed.'''
return Task('Empty', lambda args,kwargs: None, [], {})
@staticmethod
def non_parallel_upload(tasks):
'''Non parallel upload for testing purposes.'''
if not type(tasks) == Task:
for t in tasks:
Task.non_parallel_upload(t)
else:
tasks.execute()
@staticmethod
def parallel_upload(tasks):
'''Start upload instances in as manny threads as possible.
Syntax: A tuple() declares ordered execution, a list() parallel
execution.
Examples for tasks = ..
[a, b, c]
a, b and c will be uploaded in parallelly
[(a, b), c]
b will be uploaded after a
and (a,b) will be uploaded parallelly to c
([a, b], c)
a and b will be uploaded parallelly
and [a,b] will be uploaded before c
Realistically we can only parallelize stocks and sites and contacts.
=> ([stocks, sites, ?], phenotypes)
'''
if type(tasks) == tuple:
for t in tasks:
Task.parallel_upload(t)
elif type(tasks) == list:
ts = []
for task in tasks:
t = threading.Thread(target=Task.parallel_upload, args=[task])
ts.append(t)
map(lambda x: x.start(), ts)
map(lambda x: x.join(), ts)
else:
tasks.execute(thread=True)
@staticmethod
def print_tasks(ts, pre='', ind=False):
'''One level of indentation equals parallel execution.'''
if type(ts) == list:
for t in ts: pre = Task.print_tasks(t, pre=pre, ind=False)
elif type(ts) == tuple:
for t in ts: pre = Task.print_tasks(t, pre=pre, ind=True)
else:
print pre+'>', str(ts)[:80-(len(pre)*8)]+'...'
if ind: return pre + '\t'
else: return pre
def uniq(l, key=None):
'uniq(iterable, key=None) --> new list with unique entries'
if not key:
r = []
for i in l:
if not i in r:
r.append(i)
return r
else:
keyed_list = []
unkeyed_list = []
for i in l:
keyed_i = key(i)
if not keyed_i in keyed_list:
keyed_list.append(keyed_i)
unkeyed_list.append(i)
return unkeyed_list
<file_sep>/chado.py
'''
Chado Helper Module
'''
import psycopg2 as psql
import getpass
import types # used to copy has_.. functions
import os # environ -> db pw
import re
from utility import PostgreSQLQueries as PSQLQ
from utility import make_namedtuple_with_query
from utility import Task
from utility import uniq
import utility
from StringIO import StringIO
from itertools import izip_longest as zip_pad
import random
from task_storage import TaskStorage
from collections import Counter
DB='drupal7'
USER='drupal7'
HOST='127.0.0.1'
PORT=5432
CULTIVAR_WIKI='''\
Germplasm Type: assemblage of plants select for desirable characteristics\
'''
class ChadoPostgres(object):
'''You can ask questions about Chado once we have a connection to that
database.
Note: Initialization includes connection establishment to the database.
Note: We create some methods dynamically.
All 'has_'-functions return True if <table> contains sth. called <name>.
Namely:
.has_{table}(name)
, with {table} element [self.COMMON_TABLES, 'organism',
'nd_geolocation']
All 'get_'-functions Return all rows from {table} as namedtuple, with
<where> used as where statement. If <where> is empty all rows are returned.
.get_{table}(where='')
, with {table} element [self.COMMON_TABLES, 'organism',
'nd_geolocation', 'nd_experiment',
'dbxref', 'stockprop']
'''
COMMON_TABLES = ['db', 'cv', 'cvterm', 'genotype', 'phenotype', 'project',
'stock', 'study']
def __init__(self, db=DB, usr=USER, host=HOST, port=PORT):
'''Without host and port, we default to localhost:5432.'''
self.__connect(db, usr, host, port)
def __connect(self, db, usr, host, port):
'''Establish the connection.'''
self.con = None
pw = None
if os.environ.has_key('POSTGRES_PW'):
pw = os.environ['POSTGRES_PW']
try:
self.con = psql.connect(database=db, user=usr, host=host,
port=port, password=pw)
except psql.OperationalError as e:
prompt = '{n}/3 psql connection to {db} as {usr} @'\
+' {host}:{port}\nPassword: '
for i in range(1, 4):
if self.con:
break
try:
pw = getpass.getpass(prompt=prompt.format(n=i, db=db,
usr=usr, host=host, port=port))
self.con = psql.connect(database=db, user=usr, password=pw,
host=host, port=port)
except psql.OperationalError as e:
pass
if not self.con:
raise e
self.c = self.con.cursor()
def __exe(self, query):
'''execute + fetchall, remembers last query and result'''
self.c.execute(query)
self.lastq = query
self.last_res = self.c.fetchall()
return self.last_res
def __tab_contains(self, name, table='', column='name'):
'''Return True if Chado's '{table}' table contains an entry with
<column> = <name>.'''
if not table:
raise RuntimeError('need \'table\' argument')
sql = PSQLQ.select_all_from_where_eq
sql = sql.format(table=table, name=name, col=column)
if self.__exe(sql):
return True
else:
return False
def __get_rows(self, table='', where='', rawdata=False):
'''Return all rows from {table} as namedtuple
<where> is used as where statement. If where is empty all rows are
returned.
If <rawdata> is True, we return the fetched rows as list().
'''
sql = PSQLQ.select_all
if where:
sql = sql + ' WHERE {where}'
sql = sql.format(table=table, where=where)
else:
sql = sql.format(table=table)
raw_result = self.__exe(sql)
if rawdata:
return raw_result
sql = PSQLQ.column_names.format(table=table)
result = make_namedtuple_with_query(self.c, sql, table, raw_result)
return result
@staticmethod
def insert_into(table, values, columns=None, cursor=None, store=None):
'''INSERT INTO <table> (columns) VALUES (values)
kwargs:
columns specify columns in values, default to all columns of
table
cursor needed
store if given must be of the form [a,b] will store the
RETURNING column <a> of the insert statement into
TaskStorage.b
'''
if len(values) == 0:
print '[Warning] No values to upload for {}'.format(table)
if store:
setattr(TaskStorage, store[1], [])
return
if not type(values[0]) in [list, tuple]:
msg = 'expected values = [[...], [...], ...]\n\tbut received: {}'
msg = msg.format(str(values)[:50])
raise RuntimeError(msg)
if not cursor:
raise RuntimeError('need cursor object')
w = values
if not store:
# default to using fileIO
f = StringIO('\n'.join('\t'.join(str(i) for i in v) for v in w))
cursor.copy_from(f, table, columns=columns)
cursor.connection.commit()
else:
# making VALUE-format: ('a', 'b'), ('c', ..), ..
c, p, q = ',', "({})", "'{}'"
f = c.join(p.format(c.join(q.format(i) for i in v)) for v in w)
sql = '''
INSERT INTO {table} {columns} VALUES {values} RETURNING {what}
'''
columns = p.format(','.join(columns))
sql = sql.format(table=table, columns=columns, values=f, what=store[0])
cursor.execute(sql)
res = cursor.fetchall()
setattr(TaskStorage, store[1], res)
@staticmethod
def fetch_y_insert_into(fetch_stmt, values_constructor, *insert_args,
**insert_kwargs):
'''Execute a query, replace insert_args[1], which are the values,
passed to the insert_into function with the result of the
values_constructor function function, given the the original
insert_args[1] and the result of the fetch_stmt statement as argument.
args[1] = values_constructor(insert_args[1], fetch_result)
<insert_kwargs> must contain a key called 'cursor' with a valid
db-cursor as value.
Note: We could do this as a single sql statement, but we have a lot of
data to handle, and we don't want to construct incredebly long
INSERT-statements. Like this we only construct moderately long
SELECT-statements.
'''
if not insert_kwargs.has_key('cursor'):
raise RuntimeError('need cursor object')
c = insert_kwargs['cursor']
c.execute(fetch_stmt)
fetch_res = c.fetchall()
args = list(insert_args)
# replaces values with the constructed join'ed ones
args[1] = values_constructor(insert_args[1], fetch_res)
ChadoPostgres.insert_into(*args, **insert_kwargs)
@staticmethod
def storage_y_insert_into(values_constructor, *insert_args,
**insert_kwargs):
'''Construct insert_into content with the <values_constructor> and the
global TaskStorage object.
'''
if not insert_kwargs.has_key('cursor'):
raise RuntimeError('need cursor object')
args = list(insert_args)
args[1] = values_constructor(args[1], TaskStorage)
ChadoPostgres.insert_into(*args, **insert_kwargs)
# Following function definitions where made manually, as the identifying
# column name differs from 'name'
def has_genus(self, name):
'''See __tab_contains'''
return self.__tab_contains(name, table='organism', column='genus')
def has_species(self, name):
'''See __tab_contains'''
return self.__tab_contains(name, table='organism', column='species')
def has_nd_geolocation(self, name):
'''See __tab_contains'''
return self.__tab_contains(name, table='nd_geolocation', column='description')
def count_from(self, table):
'''Return row count from the given table.'''
r = self.__exe(PSQLQ.select_count.format(table=table))[0][0]
self.last_res = r
return r
def create_organism(self, genus, species, abbreviation='', common_name='',
comment=''):
'''Create an organism with the given specifications.'''
sql = PSQLQ.insert_into_table
columns = '(abbreviation, genus, species, common_name, comment)'
table = 'organism'
values = '''('{abr}', '{gen}', '{spec}', '{com_n}', '{com}')'''
values = values.format(abr=abbreviation, gen=genus, spec=species,
com_n=common_name, com=comment)
sql = sql.format(table=table, columns=columns, values=values)
self.c.execute(sql)
def __delete_where(self, table, condition):
'''DELETE FROM <table> WHERE <condition>'''
sql = PSQLQ.delete_where
sql = sql.format(table=table, cond=condition)
self.c.execute(sql)
if not self.con.autocommit:
self.con.commit()
def delete_organism(self, genus, species):
'''Deletes all organisms, with given genus and species.'''
cond = '''genus = '{0}' and species = '{1}' '''
cond = cond.format(genus, species)
self.__delete_where('organism', cond)
def delete_cvterm(self, name, cv=None, and_dbxref=False):
'''Deletes all cvterms, with given name and cv.'''
cond = "name = '{0}'".format(name)
if cv:
cvs = self.get_cv(where="name = '{}'".format(cv))
cv_id = cvs[0].cv_id
cond = cond + " AND cv_id = {1}".format(name, cv_id)
if and_dbxref:
cvts = self.get_cvterm(where=cond)
self.__delete_where('cvterm', cond)
if and_dbxref:
cond = "accession = '{}'".format(name)
self.__delete_where('dbxref', cond)
def delete_stock(self, stock, column='name'):
cond = column+" = '{}'".format(stock)
self.__delete_where('stock', cond)
def delete_geolocation(self, site='', keys={}):
'''<keys> are concatenated and "AND"-ed as =equal= conditions to the
delete condition, site ist checked against 'description'.
'''
if site:
cond = "description = '{}'".format(site)
else:
cond = '1=1'
if keys:
# we strip this prefix, because it comes like this from the Config
ndg = 'nd_geolocation.'
for k,v in keys.iteritems():
if k.startswith(ndg): k = k.split(ndg)[1]
cond = cond + " and {col} = '{val}'".format(col=k, val=v)
self.__delete_where('nd_geolocation', cond)
def delete_stockprop(self, val=None, type=None, keyval=None, keyvals=None,
del_attr=False):
'''Deletes all stockprops, with given value/type, or both.
If the stockprop to delete does not exist, we return silently.
If <val> or <type> is given <keyval[s]> are ignored.
if <del_attr> is True, we also delete the type of the stockprop
(the cvterm).
keyval = {a:b}
keyvals = [{a:b}, {c:d}, ..]
'''
if not any([val,type,keyval]): return
if val and type:
keyvals = [{type : val}]
elif val or type:
if val:
cond = "value = '{}'".format(val)
else:
t = self.get_cvterm(where="name = '{}'".format(type))
if not t: return
cond = "type_id = {}".format(t[0].cvterm_id)
return self.__delete_where('stockprop', cond)
if keyval:
keyvals = [keyval]
conds = []
if del_attr:
to_del = set()
for kv in keyvals:
for k,v in kv.iteritems():
t = self.get_cvterm(where="name = '{}'".format(k))
if not t: return
cond = "(type_id = {}".format(t[0].cvterm_id)
cond = cond + " AND value = '{}')".format(v)
conds.append(cond)
if del_attr:
to_del.update({k})
if del_attr:
for i in to_del:
self.delete_cvterm(i)
cond = ' OR '.join(conds)
self.__delete_where('stockprop', cond)
def delete_phenotype(self, uniquename=None, keyval=None, keyvals=None,
del_attr=False, del_nd_exp=False):
'''Deletes all phenotypes, with given descriptors/values.
if <uniquename> is given we delete exactly that phenotype
if <del_attr> is True, we also delete the type of the phenotype (the
cvterm).
keyval = {a:b}
keyvals = [{a:b}, {c:d}, ..]
'''
if keyval:
if keyvals:
keyvals.append(keyval)
else:
keyvals = [keyval]
conds = []
for kv in keyvals:
k,v = next(kv.iteritems())
t = self.get_cvterm(where="name = '{}'".format(k))
if not t: return
cond = "(attr_id = {}".format(t[0].cvterm_id)
cond = cond + " AND value = '{}')".format(v)
conds.append(cond)
cond = ' OR '.join(conds)
elif uniquename:
cond = "uniquename = '{}'".format(uniquename)
pheno = self.get_phenotype(where=cond)
nphenoes = len(pheno)
msg = 'ambiguous deletion: {}'
if nphenoes > 1: raise RuntimeError(msg.format(nphenoes))
if nphenoes == 0: return
pheno = pheno[0]
if del_attr:
attr_cond = "cvterm_id = {}".format(pheno.attr_id)
attr = self.get_cvterm(where=attr_cond)
if del_nd_exp: self.delete_nd_experiment(phenotype=pheno)
self.__delete_where('phenotype', cond)
def delete_nd_experiment(self, phenotype=None, stock=None):
if phenotype:
sql = '''
SELECT e.nd_experiment_id,ep.phenotype_id
FROM nd_experiment AS e, nd_experiment_phenotype AS ep
WHERE e.nd_experiment_id = ep.nd_experiment_id
AND ep.phenotype_id = {}
'''.format(phenotype.phenotype_id)
r = self.__exe(sql)
if len(r) == 0: return
if len(r) > 1:
msg = 'Ambiguous Phenotype deletion. id:{}, name:{}'
raise Warning(msg.format(r, phenotype.phenotype_id))
exp_id = r[0][0]
cond = "nd_experiment_id = {}".format(exp_id)
elif stock:
raise NotImplementedError('use phenotype')
self.__delete_where('nd_experiment', cond)
class ChadoDataLinker(object):
'''Links large list()s of data, ready for upload into Chado.
The create_* functions return Task-objects, that when execute()d, will link
and upload the given data into the chado schema.
'''
# Note: order matters, as we zip() dbxrefs at the end v
CVTERM_COLS = ['cv_id', 'definition', 'name', 'dbxref_id']
DBXREF_COLS = ['db_id', 'accession']
STOCK_COLS = ['organism_id', 'name', 'uniquename', 'type_id']
STOCKPROP_COLS = ['stock_id', 'type_id', 'value']
GEOLOC_COLS = ['description', 'latitude', 'longitude', 'altitude']
PHENO_COLS = ['uniquename', 'attr_id', 'value'] # not const
EXP_COLS = ['nd_geolocation_id', 'type_id']
EXP_STOCK_COLS = ['nd_experiment_id', 'stock_id', 'type_id']
EXP_PHENO_COLS = ['nd_experiment_id', 'phenotype_id']
def __init__(self, chado, dbname, cvname):
self.db = dbname
self.cv = cvname
self.chado = chado
self.con = chado.con
self.c = self.con.cursor()
def create_cvterm(self, cvterm, accession=[], definition=[], tname=None):
'''Create (possibly multiple) Tasks to upload cvterms.'''
if not accession:
accession = cvterm
if len(cvterm) != len(accession) or \
definition and len(cvterm) != len(definition):
raise RuntimeError('argument length unequal!')
cv_id = self.chado.get_cv(where="name = '{}'".format(self.cv))[0].cv_id
db_id = self.chado.get_db(where="name = '{}'".format(self.db))[0].db_id
all_dbxrefs = self.chado.get_dbxref(where="db_id = '{}'".format(db_id))
curr_dbxrefs = [d.accession for d in all_dbxrefs]
needed_dbxrefs = [a for a in accession if not a in curr_dbxrefs]
content = [[db_id, a] for a in needed_dbxrefs]
if content:
name = 'dbxref upload'
if tname: name = name + '({})'.format(tname)
f = self.chado.insert_into
args = ('dbxref', content, self.DBXREF_COLS)
kwargs = {'cursor' : self.con.cursor()} # new cursor() for every Task
t1_dbxref = Task(name, f, *args, **kwargs)
else:
t1_dbxref = Task.init_empty()
# Note: Scary code. We don't know dbxref_id's but still want to use
# the copy_from upload, or at least an execute query that uploads all
# our data at once, and not upload 1 dbxref, 1 cvterm at a time.
# cvterm names will be added later to <content> in order to ensure
# correct ordering, because we don't know the dbxref_id yet
if definition:
content = [[cv_id, de] for c,de in zip(cvterm, definition)]
else:
content = [[cv_id, ''] for c in cvterm]
fstmt = '''\
SELECT accession,dbxref_id
FROM dbxref JOIN (VALUES {}) AS v ON v.column1 = dbxref.accession
'''
fstmt = fstmt.format(','.join("('{}')".format(v) for v in cvterm))
def join_func(x, y):
return [[i[0],i[1],j[0],j[1]] for i,j in zip(x,y)]
name = 'cvterm upload'
if tname: name = name + '({})'.format(tname)
f = self.chado.fetch_y_insert_into
insert_args = ['cvterm', content, self.CVTERM_COLS]
insert_kwargs = {'cursor' : self.con.cursor()}
args = [fstmt, join_func]
args += insert_args
kwargs = {}
kwargs.update(insert_kwargs)
t2_cvt = Task(name, f, *args, **kwargs)
return (t1_dbxref, t2_cvt) # tuple = enforce sequencial execution
# TODO add definition
# including: TRAIT_NAME, TRAIT_DESCRIPTION
# maybe also : METHOD_NAME, METHOD_CLASS, SCALE_ID, TRAIT_CLASS, ++
def __get_or_create_cvterm(self, term, acs=None):
'''Returns the cvterm named <term>, if it does not exist, we create it
first.
'''
if not acs: acs = term
try:
cvterm = self.chado.get_cvterm(where="name = '{}'".format(term))[0]
except IndexError:
ts = self.create_cvterm([term], accession=[acs], tname='__get_or_create')
for t in ts: t.execute()
cvterm = self.chado.get_cvterm(where="name = '{}'".format(term))[0]
return cvterm
def create_stock(self, stock_names, organism, stock_uniqs=None,
tname=None, germplasm_t='cultivar'):
'''Create (possibly multiple) Tasks to upload stocks.
If stock_uniqs is not given, it will be set equal to stock_names.
'''
cvt = self.__get_or_create_cvterm(germplasm_t)
type_id = cvt.cvterm_id
o_id = organism.organism_id
if not stock_uniqs:
stock_uniqs = stock_names
it = zip(stock_names, stock_uniqs)
# need to make the name unique..
it = uniq(it, key=lambda x: x[0])
# need to make the uniquename unique..
it = uniq(it, key=lambda x: x[1])
content = [[o_id, sn, su, type_id] for sn,su in it]
name = 'stock upload'
if tname: name = name + '({})'.format(tname)
f = self.chado.insert_into
args = ('stock', content, self.STOCK_COLS)
kwargs = {'cursor' : self.con.cursor(),
'store' : ['stock_id', 'stock_ids']}
t = Task(name, f, *args, **kwargs)
return [t,]
def __check_coords(self, _, lat, lon, alt):
''''''
r = [_]
for i in [lat, lon, alt]:
try:
i = re.sub(r'^\s*0*', '', i)
i = re.sub(r'([0-9]*)[NE]', '+\\1', i)
i = re.sub(r'([0-9]*)[SW]', '-\\1', i)
except TypeError, ValueError:
# Either we found a plain int() or the first substitution was
# already successfull, and the second fails, which is both
# fine.
pass
finally:
if i in ['-','+','',None]: i = '0'
r.append(i)
return r
def create_geolocation(self, sites, tname=None):
'''Create (possibly multiple) Tasks to upload geolocations.'''
name = 'geolocation upload'
if tname: name = name + '({})'.format(tname)
# counting for fun, last run got 2 fails for 300k+ rows
fail_counter = 0
content = []
for i in sites:
try:
content.append(
self.__check_coords(i['nd_geolocation.description'],
i['nd_geolocation.latitude'],
i['nd_geolocation.longitude'],
i['nd_geolocation.altitude']))
except KeyError:
fail_counter += 1
args = ('nd_geolocation', content, self.GEOLOC_COLS)
kwargs = {'cursor' : self.con.cursor()}
f = self.chado.insert_into
t = Task(name, f, *args, **kwargs)
return [t,]
def __strip_0time(self, ps):
'''strip time from datetime stockprops'''
for p in ps:
if hasattr(p[1], 'date'):
if callable(p[1].date):
p[1] = p[1].date()
return ps
def create_stockprop(self, props, ptype='', tname=None):
'''Create (possibly multiple) Tasks to upload stocks.
Pass props = [['name0', 'val0'], ['name1', 'val1'], ...]
<ptype> is a string, that meanst one call per property
'''
if not ptype: raise RuntimeError('no stockprop type')
type_id = self.__get_or_create_cvterm(ptype).cvterm_id
stmt = '''
SELECT s.stock_id,s.name FROM (VALUES {}) AS v
JOIN stock s ON s.name = v.column1
'''
values = ','.join("('{}')".format(p[0]) for p in props)
stmt = stmt.format(values)
props = self.__strip_0time(props)
def join_func(content, stmt_res):
type_id = content[0]
props = content[1]
stocks = sorted(stmt_res, key=lambda x: x[1])
props = sorted(props, key=lambda x: x[0])
if not len(stocks) == len(props):
msg = 'unequal stocks/stockprops, unlikely\nstocks:{}\nprops:{}'
raise RuntimeError(msg.format(stocks, props))
join = zip(stocks, props)
content = [[sck[0],type_id,prp[1]] for sck,prp in join]
# ^ stock_id ^ value
content = uniq(content, key=lambda x: x[0])#necessary
return content
name = 'stockprop upload'
if tname: name = name + '({})'.format(tname)
f = self.chado.fetch_y_insert_into
content = [type_id, props]
insert_args = ['stockprop', content, self.STOCKPROP_COLS]
insert_kwargs = {'cursor' : self.con.cursor()}
args = [stmt, join_func]
args += insert_args
kwargs = {}
kwargs.update(insert_kwargs)
t = Task(name, f, *args, **kwargs)
return [t,]
@staticmethod
def make_pheno_unique(id, name):
s = '{0}__{1}'
return s.format(id, name)
def __t1_create_phenoes(self, ids, descs, tname=None):
content = []
attr_ids = {}
for id,d in zip(ids, descs):
for descriptor, value in d.iteritems():
if not attr_ids.has_key(descriptor):
# We create cvterm syncronously, as their numbers are low.
new = self.__get_or_create_cvterm(descriptor).cvterm_id
attr_ids.update({descriptor : new})
attr_id = attr_ids[descriptor]
uniq = self.make_pheno_unique(id, descriptor)
self.pheno_uniquenames.append(id)
if value is None: value = ''
content.append([uniq, attr_id, value])
name = 'phenotype upload'
if tname: name = name + '({})'.format(tname)
f = self.chado.insert_into
args = ('phenotype', content, self.PHENO_COLS)
kwargs = {'cursor' : self.con.cursor(),
'store' : ['phenotype_id', 'phenotype_ids']}
return Task(name, f, *args, **kwargs)
def __get_geo_names(self, others):
gs = []
for i in others:
if i.has_key('site_name'):
n = i['site_name']
else:
n = 'Not Available'
gs.append(n)
return gs
def __t2_create_experiments(self, ids, descs, others, stocks, tname=None):
ld, lo, li = len(descs), len(others), len(ids)
if ld != lo or ld != li:
msg = 'descriptors({}) ?= others({}) ?= ids({})'
raise RuntimeError(msg.format(ld, lo, li))
gs = self.__get_geo_names(others)
geos = ["('{0}')".format(s) for s in gs]
stmt = '''
SELECT g.nd_geolocation_id FROM (VALUES {}) AS v
JOIN nd_geolocation g ON v.column1 = g.description
'''
stmt = stmt.format(','.join(geos))
def join_func(type_id, stmt_res):
return [[x[0], type_id] for x in stmt_res]
# [geolocation_id, type_id]
type_id = self.__get_or_create_cvterm('phenotyping').cvterm_id
name = 'nd_experiment upload'
if tname: name = name + '({})'.format(tname)
f = self.chado.fetch_y_insert_into
insert_args = ['nd_experiment', type_id, self.EXP_COLS]
insert_kwargs = {'cursor' : self.con.cursor(),
'store' : ['nd_experiment_id', 'nd_experiment_ids']}
args = [stmt, join_func]
args += insert_args
kwargs = {}
kwargs.update(insert_kwargs)
t = Task(name, f, *args, **kwargs)
return [t,]
def __t3_link(self, others, stocks, tname=None):
linkers = []
# -- stocks --
cvt = self.__get_or_create_cvterm('sample')
type_id = cvt.cvterm_id
def join_stock_func(type_id,ts):
le, ls = len(ts.nd_experiment_ids), len(ts.stock_ids)
if le != ls:
# we fill in the holes in the known stock_ids with the new ones
ls = len(ts.stock_ids)
c = Counter(ts.known_stock_ids)
lnone_n_dups = c[None] + c[utility.Duplicate]
if c[None] > 0 and c[None] != ls:
msg = 'holes({})+dups({}) in known stocks(={}) != new'\
+ ' stocks({})'
msg = msg.format(c[None], c[utility.Duplicate],
lnone_n_dups, ls)
raise RuntimeError(msg)
stock_ids = []
new = iter(ts.stock_ids) # -> [(321,), (123,), ...]
for known in ts.known_stock_ids: # -> [321, 123, None, Dup, ...]
if known.__class__ == utility.Duplicate:
duplicate = known
stock_ids.append(ts.stock_ids[duplicate.index])
else:
stock_ids.append([known] if known else next(new))
ts.stock_ids = stock_ids
it = zip(ts.nd_experiment_ids, ts.stock_ids)
return [[eid[0], sid[0], type_id] for eid,sid in it]
name = 'link stocks'
if tname: name = name + '({})'.format(tname)
f = self.chado.storage_y_insert_into
insert_args = ['nd_experiment_stock', type_id, self.EXP_STOCK_COLS]
insert_kwargs = {'cursor' : self.con.cursor()}
args = [join_stock_func]
args += insert_args
kwargs = {}
kwargs.update(insert_kwargs)
linkers.append(Task(name, f, *args, **kwargs))
# -- phenotypes --
def join_pheno_func(ids, ts):
# Earlier this meant that we might have failed parsing Ontology
# and/or configuration, which is no longer a problem.
#if len(ids) == len(set(ids)):
# raise Warning('Only one phenotype per data line? Unlikely!')
eid_iter = iter(ts.nd_experiment_ids)
pid_iter = iter(ts.phenotype_ids)
test_iter = iter(ids)
last_id = next(test_iter)
eid = next(eid_iter)
pid = next(pid_iter)
r = []
while True:
try:
# only if we have a new row id we go to the next experiment
r.append([eid[0], pid[0]])
new_id = next(test_iter)
if new_id != last_id:
eid = next(eid_iter)
pid = next(pid_iter)
last_id = new_id
except StopIteration:
break
return r
name = 'link phenotypes'
if tname: name = name + '({})'.format(tname)
f = self.chado.storage_y_insert_into
insert_args = ['nd_experiment_phenotype', self.pheno_uniquenames, self.EXP_PHENO_COLS]
insert_kwargs = {'cursor' : self.con.cursor()}
args = [join_pheno_func]
args += insert_args
kwargs = {}
kwargs.update(insert_kwargs)
linkers.append(Task(name, f, *args, **kwargs))
return linkers
def create_phenotype(self, ids, stocks, descs, others=[], genus=None,
tname=None):
'''
Create (possibly multiple) Tasks to upload phenotypic data.
stocks - list of stock names
descs - list of dict's of phenotypic data
others - list of dict's with additional information
e.g.: geolocation(nd_geolocation), date's(stockprop), ..
'''
# === Plan of Action ===
# T1 - upload phenotypes from <descs>
self.pheno_uniquenames = [] # used to later query the ids
t_phenos = self.__t1_create_phenoes(ids, descs, tname)
# T2 - get geolocation ids # has already been uploaded..
# T2 - create_nd_experiment
t_experiment = self.__t2_create_experiments(ids, descs, others, stocks)
# T3 - get stock ids, and nd_experiment ids
# T3 - link 'em
# T3 - get phenotype ids, and nd_experiment ids
# T3 - link 'em
t_link = self.__t3_link(others, stocks)
del self.pheno_uniquenames
return ([t_phenos, t_experiment], t_link)
# META-BEGIN
# Metaprogramming helper-function.
def copy_func(f, newname):
return types.FunctionType(
f.func_code, f.func_globals, newname or f.func_name, f.func_defaults,
f.func_closure
)
# Create convenient methods:
# .has_db() .has_cv() .has_cvterm() ...
for table in ChadoPostgres.COMMON_TABLES:
prefix = 'has_'
newf_name = prefix+table
if not hasattr(ChadoPostgres, newf_name):
newf = copy_func(ChadoPostgres._ChadoPostgres__tab_contains, newf_name)
newf.func_defaults = (table,)
newf.func_doc = ChadoPostgres._ChadoPostgres__tab_contains\
.__doc__.format(table=table)
setattr(ChadoPostgres, prefix+table, newf)
# Create convenient methods:
# .get_db() .get_cv() .get_..
for table in ChadoPostgres.COMMON_TABLES + ['organism', 'nd_geolocation',
'dbxref', 'stockprop', 'nd_experiment']:
prefix = 'get_'
newfget_name = prefix+table
if not hasattr(ChadoPostgres, newfget_name):
newf = copy_func(ChadoPostgres._ChadoPostgres__get_rows, newfget_name)
newf.func_defaults = (table,'',False)
newf.func_doc = ChadoPostgres._ChadoPostgres__get_rows\
.__doc__.format(table=table)
setattr(ChadoPostgres, prefix+table, newf)
# META-END
| f07954937aba585efab5e7893077e7e34d254fd8 | [
"Python"
] | 11 | Python | visiting-scientist-3217/ciat_mtods | 590fa3284fd0147f410c992892c679a4906ea4fb | 43f23eae1077f2bed20b945e01178ce4a75fab3f |
refs/heads/master | <file_sep><?php
session_start();
// connessione con il database
include '../scripts/db-connection.php';
$pagina = $_GET['page'];
//protezione contro mysql injection
$data = $conn -> real_escape_string($_POST['data']);
$descrizione = $conn -> real_escape_string($_POST['descrizione']);
$id_utente = $_SESSION['id_utente'];
$query_insert_attivita = "INSERT INTO attivita(data, descrizione, id_utente) VALUES ('$data', '$descrizione', '$id_utente')";
$result = $conn -> query($query_insert_attivita);
// indirizza all'utente sulla pagina dove hanno eseguito la richiesta
if (!$result) {
die('Errore nella query: ' . mysqli_errno($conn));
mysqli_close($conn);
}
else {
mysqli_close($conn);
if ($pagina == "dashboard") {
header('location: ../dashboard/');
}
else {
header('location: ../main/');
}
}
?>
<file_sep><?php
// script per stabilire la connessione con il database.
include '../scripts/db-connection.php';
// Protezione contro mysql injection
$nome = $conn->real_escape_string($_POST['nome']);
$email = $conn->real_escape_string($_POST['email']);
// Criptare password per essere salvata nel database
$pswd = hash('sha256', $_POST['pswd']);
// Query d'inserimento dei dati del nuovo utente
$query = "INSERT INTO utenti (nome, email, pswd) VALUES ('$nome', '$email', '$pswd' )";
$result = $conn -> query($query);
/*
* Controlla se ci sono degli errore nella registrazione:
* Se c'è qualche errore, si torna nella pagina della registrazione e verrà comunicato uno dei seguenti errori:
*
* 'duplicated' -> l'email inserito dall'utente è già stato registrato.
* è specificato nel database che il campo 'email' è UNIQUE.
*
* 'insert' -> errore durante l'eseguimento della query.
*
* Altrimenti, la registrazione è avvenuta con successo e l'utente sarà reindirizzato al login.
*/
if (!$result)
{
$error = mysqli_error($conn);
mysqli_close($conn);
if (strstr($error, 'Valore duplicato') || strstr($error, 'Duplicate entry'))
{
header('location: index.php?error=duplicated');
}
else
{
header('location: index.php?error=insert');
}
}
else
{
header('location: ../login/index.php?msg=success');
}
?>
<file_sep><?php
// Controllare se l'utente ha già fatto il login per reindirizzarlo alla pagina corrispondente
session_start();
include '../scripts/session-control.php';
// navbar setup
$pagina_attuale = 'login';
/*
* feedback per l'utente in caso di:
* 1) fare logout.
* 2) una registrazione avvenuta con successo.
* 3) un errore durante l'accesso.
*/
$message = "";
if (isset($_GET['msg'])) {
$string = $_GET['msg'];
switch ($string) {
case 'logout':
$string = "Hai chiuso la sessione correttamente.";
$color = "success";
break;
case 'success':
$string = "Registrazione avvenuta con successo!";
$color = "success";
break;
case 'auth-error':
$string = "Credenziali incorrette.";
$color = "danger";
break;
case 'query':
$string = "Errore durante l'accesso. Fare un altro tentativo.";
$color = "danger";
break;
default:
break;
}
$message = "<p class='bg-$color rounded text-center text-light p-1'>$string</p>";
}
?>
<!DOCTYPE html>
<html lang="it">
<head>
<!-- stylesheet e metadata -->
<?php include '../scripts/head-meta-data.php';?>
<title>doQuick | Accedi</title>
</head>
<body>
<!-- container principale -->
<div class="container-lg d-flex flex-column vh-100">
<!-- navbar -->
<div class="row">
<?php include '../scripts/navbar.php'; ?>
</div>
<div class="d-flex flex-column justify-content-center flex-grow-1">
<!-- header -->
<div class="row">
<div class="col-12">
<header>
<h1 class="display-1 text-white text-center mb-4">doQuick</h1>
</header>
<hr class="w-75" style="color: white;">
</div>
</div>
<!-- form di login -->
<div class="row justify-content-center">
<div class="col-12 col-md-6 m-2">
<h2 class="lead text-white">Log in</h2>
<form class="bg-light p-3 rounded shadow-sm" action="login.php" method="post">
<?php echo $message; ?>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Indirizzo e-mail" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="pswd" name="pswd" placeholder="<PASSWORD>" required>
</div>
<button type="submit" class="btn btn-primary w-100">Accedi</button>
</form>
</div>
</div>
</div>
<!-- footer -->
<div class="row">
<footer class="footer-copyright lead text-center text-white py-1 bg-info w-100">
Copyright © 2019 <NAME>
</footer>
</div>
</div>
<!-- dipendenze di boostrap -->
<?php include '../scripts/bootstrap-dependencies.php'; ?>
</body>
</html>
<file_sep><?php
session_start();
// navbar setup
$pagina_attuale = 'home';
?>
<!DOCTYPE html>
<html lang="it">
<head>
<?php include 'scripts/head-meta-data.php';?>
<title>doQuick | To Do List</title>
</head>
<body>
<!-- container con navbar e header-->
<div class="container-lg d-flex flex-column bg-transparent vh-100">
<!-- navbar -->
<div class="row">
<?php include 'scripts/navbar.php'; ?>
</div>
<!-- header -->
<div class="d-flex flex-column justify-content-center flex-grow-1 ">
<div class="row">
<div class="col-12">
<header>
<h1 class="display-1 text-white text-center mt-4 mb-4">doQuick</h1>
</header>
<hr class="w-75">
<p class="lead text-light text-center p-2">Organizza le tue attività quotidiane e aumenta la tua produttività.</p>
</div>
</div>
<div class="row d-flex justify-content-center mb-4">
<div class="col-12 col-md-6 d-flex justify-content-around">
<!-- cambia i link presenti sulla pagina in funzione della sessione -->
<?php
if (isset($_SESSION['id_utente']))
{
if (isset($_SESSION['is_admin']))
{
?>
<div class="btn-group">
<a class="btn btn-primary text-light" href="dashboard/">Dashboard</a>
<a class="btn btn-primary text-light" href="main/">Main</a>
</div>
<?php
}
else
{
?>
<a class="btn btn-primary text-light" href="dashboard/">Dashboard</a>
<?php
}
}
else
{
?>
<div class="btn-group">
<a class="btn btn-primary text-light" href="login/">Accedi</a>
<a class="btn btn-primary text-light" href="signup/">Registrati</a>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
<!-- container con informazioni sulla pagina -->
<div class="container-fluid d-flex flex-column bg-dark p-0 min-vh-100 shadow-lg">
<div class="d-flex flex-grow-1 align-items-center justify-content-around mh-100">
<!-- card 1 -->
<div class="row w-100 mx-0 my-4 p-4">
<div class="col-12 col-md-4 mb-4 mb-md-0 ">
<div class="card">
<img class="card-img-top" src="img/img1.jpg" alt="immagine di esempio 1">
<div class="card-body">
<h5 class="card-title">Titolo</h5>
<p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. </p>
</div>
<div class="card-footer">
<small class="text-muted">By Adriano</small>
</div>
</div>
</div>
<!-- card 2 -->
<div class="col-12 col-md-4 mb-4 mb-md-0">
<div class="card">
<img class="card-img-top" src="img/img2.jpg" alt="immagine di esempio 2">
<div class="card-body">
<h5 class="card-title">Titolo</h5>
<p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur.</p>
</div>
<div class="card-footer">
<small class="text-muted">By Adriano</small>
</div>
</div>
</div>
<!-- card 3 -->
<div class="col-12 col-md-4">
<div class="card">
<img class="card-img-top" src="img/img3.jpg" alt="immagine di esempio 3">
<div class="card-body">
<h5 class="card-title">Titolo</h5>
<p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur.</p>
</div>
<div class="card-footer">
<small class="text-muted">By Adriano</small>
</div>
</div>
</div>
</div>
</div>
<!-- footer -->
<div class="row w-100 m-0">
<footer class="footer-copyright lead text-center text-white py-1 bg-info w-100">
Copyright © 2019 <NAME>
</footer>
</div>
</div>
<!-- dipendenze di boostrap -->
<?php include 'scripts/bootstrap-dependencies.php'; ?>
</body>
</html><file_sep><?php
// Controllare se l'utente ha già fatto il login per reindirizzarlo alla pagina corrispondente.
session_start();
include '../scripts/session-control.php';
// Navbar setup
$pagina_attuale = 'signup';
// $message sarà stampato se c'è stato un errore durante registrazione.
$message = '';
if (isset($_GET['error'])) {
$error = $_GET['error'];
if ($error == 'duplicated') {
$error = "L'indirizzo e-mail è già stato registrato.";
}
else {
$error = "Errore durante la registrazione. Fare un altro tentativo.";
}
$message = "<p class='bg-danger rounded text-center text-light p-1'>$error</p>";
}
?>
<!DOCTYPE html>
<html lang="it">
<head>
<!-- stylesheet e metadata -->
<?php include '../scripts/head-meta-data.php';?>
<title>doQuick | Registrazione</title>
</head>
<body>
<!-- container principale -->
<div class="container-lg d-flex flex-column justify-content-center vh-100">
<div class="row">
<!-- navbar -->
<?php include '../scripts/navbar.php'; ?>
</div>
<div class="d-flex flex-column justify-content-center flex-grow-1">
<!-- header -->
<div class="row">
<div class="col-12">
<header>
<h1 class="display-1 text-white text-center mb-4">doQuick</h1>
</header>
<hr class="w-75" style="color: white;">
</div>
</div>
<!-- form di registrazione -->
<div class="row justify-content-center">
<div class="col-12 col-md-6">
<h2 class="lead text-white"> Registrazione</h2>
<form class="bg-light p-3 rounded shadow-sm" action="registrazione.php" method="post">
<?php echo $message; ?>
<!-- campo nome e cognome -->
<div class="form-group">
<input type="text" class="form-control w-100" id="nome" name="nome" placeholder="Nome e cognome" required>
</div>
<!-- campo email -->
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Indirizzo e-mail" required>
</div>
<!-- campo password -->
<div class="form-group">
<input type="password" class="form-control" id="pswd" name="pswd" placeholder="<PASSWORD>" required>
</div>
<!-- privacy -->
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="privacy" required>
<label class="form-check-label" for="privacy">Accetto il trattamento dei miei dati personali secondo la normativa vigente.</label>
</div>
<button type="submit" class="btn btn-primary w-100">Invia</button>
</form>
</div>
</div>
</div>
<!-- footer -->
<div class="row">
<footer class="footer-copyright lead text-center text-white py-1 bg-info w-100">
Copyright © 2019 <NAME>
</footer>
</div>
</div>
<!-- dipendenze di Boostrap -->
<?php include '../scripts/bootstrap-dependencies.php'; ?>
</body>
</html>
<file_sep><?php
// connessione con il database
include '../scripts/db-connection.php';
$pagina = $_GET['page'];
//protezione contro mysql injection
$id = $conn -> real_escape_string($_GET['id']);
// query per cancellare l'attivita con id == $id
$query = "DELETE FROM attivita WHERE id = '$id'";
// indirizza all'utente sulla pagina dove hanno eseguito la richiesta
$result = $conn -> query($query);
if (!$result) {
die('Errore nella query: ' . mysqli_errno($conn));
mysqli_close($conn);
}
else {
mysqli_close($conn);
if ($pagina == "dashboard") {
header('location: ../dashboard/index.php');
}
else {
header('location: ../main/index.php');
}
}
?><file_sep><?php
if (isset($_SESSION["id_utente"]))
{
if ($_SESSION["is_admin"] == true)
{
header('location: /main/');
}
else
{
header('location: /dashboard/');
}
}
?><file_sep><?php
session_start();
include '../scripts/db-connection.php';
// Reindirizzare utenti se non sono registrati e/o non sono admin.
if (!isset($_SESSION['is_admin'])){
if (isset($_SESSION['id_utente'])) {
header('location: ../dashboard/');
}
else {
header('location: ../');
}
}
// Query per selezionare tutte le attivita di tutti gli utenti.
$query = "SELECT * FROM attivita
ORDER BY data ASC";
$result = $conn -> query($query);
if (!$result) {
die("Errore nella query: " . mysqli_errno($conn));
}
// navbar setup
$pagina_attuale = 'main';
?>
<!DOCTYPE html>
<html>
<head>
<!-- stylesheet e metadata -->
<?php include '../scripts/head-meta-data.php'; ?>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<title>doQuick | Dashboard</title>
</head>
<body>
<div class="container-lg d-flex flex-column vh-100 px-0 shadow">
<!-- navbar -->
<?php include '../scripts/navbar.php'; ?>
<!-- tabella delle attività -->
<div class="table-responsive flex-grow-1 bg-light p-0 p-sm-3 text-center text-dark">
<table class="table table-hover">
<thead class="thead-dark">
<tr class="lead text-white">
<th scope="col">Data</th>
<th scope="col">Descrizione</th>
<th scope="col">Utente</th>
<th scope="col">Opzioni</th>
</tr>
</thead>
<tbody>
<?php
/*
* Controlla se ci sono delle attività caricate dagli utenti
*
* Se ci sono, le stampa secondo la data dell'attività in ordine crescente (dalla più vecchia alla più recente).
*
* Altrimenti, mostra che non ci sono ancora delle attività e permette di creare una nuova.
*/
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data = date("d/m/Y", strtotime($row['data']));
$descrizione = $row['descrizione'];
$id_attivita = $row['id'];
$id_utente = $row['id_utente'];
// Utente che ha caricato l'attivita con id == $id_attivita;
// Verrà stampato l'email dell'utente per differenziare tra utenti con lo stesso nome e cognome.
$query_utente = "SELECT email FROM utenti WHERE id = '$id_utente'";
$result_utente = $conn -> query($query_utente);
$array_utente = $result_utente -> fetch_array();
$utente = $array_utente[0];
echo "<tr>
<th>$data</th>
<td>$descrizione</td>
<td>$utente</td>
<td><a class=\"btn btn-danger\" href=\"../attivita/delete.php?id=$id_attivita&page=$pagina_attuale\">Cancella</a></td>
</tr>";
}
}
else {
?>
<tr>
<th colspan="4">
<p> Non hai ancora inserito una attività. </p>
<br>
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#crea">
Premi qui per crearne una
</button>
</th>
</tr>
<?php
}
mysqli_close($conn);
?>
</tbody>
</table>
</div>
<!-- footer -->
<footer>
<div class="footer-copyright text-center text-white py-3 bg-info w-100">Copyright © 2019 <NAME></div>
</footer>
<!-- modal con form per caricare una nuova attività -->
<div class="modal fade" id="crea" tabindex="-1" role="dialog" aria-labelledby="nuova-attivita" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="nuova-attivita">Crea una nuova attività:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- form -->
<form id="form-attivita" action="../attivita/create.php?page=main" method="post">
<label for="data">Inserisci una data:</label>
<div class="form-group">
<input type="date" class="form-control" id="data" name="data" required>
</div>
<div class="form-group">
<textarea class="form-control" name="descrizione" form="form-attivita" placeholder="Descrizione dell'attività" required></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Chiudi</button>
<button type="submit" class="btn btn-primary" form="form-attivita">Salva</button>
</div>
</div>
</div>
</div>
</div>
<!-- dipendenze di boostrap -->
<?php include '../scripts/bootstrap-dependencies.php'; ?>
</body>
</html><file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.2
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 19-12-2019 a las 23:06:56
-- Versión del servidor: 10.4.10-MariaDB
-- Versión de PHP: 7.3.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `to-do-list`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `attivita`
--
CREATE TABLE `attivita` (
`id` int(11) NOT NULL,
`id_utente` int(11) NOT NULL,
`data` date NOT NULL,
`descrizione` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Volcado de datos para la tabla `attivita`
--
INSERT INTO `attivita` (`id`, `id_utente`, `data`, `descrizione`) VALUES
(1, 1, '2019-12-19', 'Finire il progetto'),
(2, 1, '2019-12-19', 'Fare debugging'),
(3, 1, '2019-12-19', 'Studiare per 30 minuti');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `utenti`
--
CREATE TABLE `utenti` (
`id` int(11) NOT NULL,
`nome` varchar(64) NOT NULL,
`email` varchar(64) NOT NULL,
`pswd` varchar(255) NOT NULL,
`is_admin` int(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Volcado de datos para la tabla `utenti`
--
INSERT INTO `utenti` (`id`, `nome`, `email`, `pswd`, `is_admin`) VALUES
(1, '<NAME>', '<EMAIL>', '033bd1a96cff<PASSWORD>a093acdcc<PASSWORD>ee6c1<PASSWORD>e<PASSWORD>', 1),
(2, '<NAME>', '<EMAIL>', 'a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3', 0);
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `attivita`
--
ALTER TABLE `attivita`
ADD PRIMARY KEY (`id`),
ADD KEY `id_utente` (`id_utente`);
--
-- Indices de la tabla `utenti`
--
ALTER TABLE `utenti`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `email` (`email`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `attivita`
--
ALTER TABLE `attivita`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `utenti`
--
ALTER TABLE `utenti`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
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>
<nav class="navbar navbar-expand-lg navbar-dark shadow w-100">
<a class="navbar-brand" href="/">doQuick</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navBar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse" id='navBar'>
<ul class="navbar-nav nav-fill justify-content-center">
<?php
if ($pagina_attuale != 'dashboard' && isset($_SESSION['id_utente']))
{
?>
<li class="nav-item">
<a class="nav-link" href="/dashboard/">Dashboard</a>
</li>
<?php
}
if ($pagina_attuale != 'main' && isset($_SESSION['is_admin']))
{
?>
<li class="nav-item">
<a class="nav-link" href="/main/">Main</a>
</li>
<?php
}
if ($pagina_attuale != 'login' && !isset($_SESSION['id_utente']))
{
?>
<li class="nav-item">
<a class="nav-link" href="/login/">Accedi</a>
</li>
<?php
}
if ($pagina_attuale != 'signup' && !isset($_SESSION['id_utente']))
{
?>
<li class="nav-item">
<a class="nav-link" href="/signup/">Registrati</a>
</li>
<?php
}
if (isset($_SESSION['id_utente']))
{
if ($pagina_attuale == 'main' || $pagina_attuale == 'dashboard')
{
?>
<li class="nav-item">
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#crea">Crea attività</button>
</li>
<?php
}
?>
<li class="nav-item">
<a class="nav-link" href="/login/logout.php">Esci</a>
</li>
<?php
}
?>
</ul>
</div>
</nav><file_sep><?php
session_start();
// script per stabilire la connessione con il database.
include '../scripts/db-connection.php';
$email = $conn->real_escape_string($_POST['email']);
$pswd = hash("sha256", $_POST['pswd']);
// query per controllare se l'utente è presente nel database
$query = "SELECT * FROM utenti
WHERE email = '$email'
AND pswd = '$pswd'";
$result = $conn->query($query);
// controlla se ci sono errori nella richiesta
if (!$result) {
header('location: index.php?msg=query');
}
else
{
$array = $result->fetch_assoc();
}
mysqli_close($conn);
/*
* $array vuoto -> l'utente non è registrato e/o ha inserito credenziali sbagliate.
* $array non vuoto -> le credenziali di accesso inserite sono corrette e la sessione sarà iniziata.
*
* Controllo per vedere se l'utente è admin o meno.
* admin -> sarà indirizzato alla pagina main.
* utente -> sarà indirizzato alla dashboard.
*/
if ($array != '')
{
// salva l'id dell'utente
$_SESSION['id_utente'] = $array['id'];
// Salva solo il primo nome
$_SESSION['nome'] = strtok($array['nome'], ' ');
if ($array['is_admin'] == 1)
{
$_SESSION['is_admin'] = true;
header('Location: ../main/');
}
else
{
header('Location: ../dashboard/');
}
}
else
{
header('Location: ../login/index.php?msg=auth-error');
}
?>
| 8cb9afc58ef12862b2b58ea5ec426e72fc9253de | [
"SQL",
"PHP"
] | 11 | PHP | CamacaroAdriano/to-do-list | 00f4c6d386ddf297640264c2204fe2c1fd2e1da0 | 60be3b89455b7021c5c210fb2f2e92f1a4b592b0 |
refs/heads/master | <repo_name>teguheka/template_mvc<file_sep>/src/main/resources/jdbc.dev.properties
jdbc.driverClassName = org.postgresql.Driver
jdbc.dialect = org.hibernate.dialect.PostgreSQL9Dialect
jdbc.url = jdbc:postgresql://127.0.0.1:5433/test
jdbc.username = root
jdbc.password = <PASSWORD><file_sep>/src/main/java/com/spring/example/controller/WelcomeController.java
package com.spring.example.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping(value = "/api/v1/hello")
@Api(value = "hello")
public class WelcomeController {
@GetMapping("/{message}")
@ApiOperation(value = "Get message")
public ResponseEntity list(@PathVariable String message) {
Map map = new HashMap();
map.put("message", message);
map.put("status", "ok");
return new ResponseEntity(map, HttpStatus.OK);
}
}
<file_sep>/src/main/resources/app.dev.properties
app.url = http://localhost:8080/spring-mvc
app.local.storage.path = /tmp<file_sep>/README.md
# template_mvc
Spring, Hibernate, Swagger | d7607e9e9b478f3955ab3f197f7e5536ad4a8f26 | [
"Markdown",
"Java",
"INI"
] | 4 | INI | teguheka/template_mvc | c41e7f90a548d47b08c982972e2090e2bf2f3b72 | 98eec1260544391d8cd5770b0e24069946b81ffe |
refs/heads/master | <file_sep>import logging
import os
from base.webdriverfactory import WebDriverFactory
from utilities import custom_logger as cl
log = cl.customLogger(logging.DEBUG)
def before_feature(context,feature):
print("before feature")
def after_feature(context,feature):
print("after feature")
def before_scenario(context,scenario):
print("before scenario")
browser = os.environ.get("browser")
wb = WebDriverFactory(browser)
context.driver = wb.getWebDriverInstance()
log.info("Browser Opened")
def after_scenario(context,scenario):
print("after scenario")
context.driver.close()
log.info("Browser Closed")
def before_step(context,step):
pass
def after_step(context,step):
pass
def before_tag(context,tag):
pass
def after_tag(context,tag):
pass
def before_all(context):
pass
def after_all(context):
pass
<file_sep>
class LoginPageLocator:
email = {"xpath":"//input[@id='login_id']"}
nextButton = {"xpath":"//button[@id='nextbtn']//span[text()='Next']"}
password = {"xpath":"//input[@id='password']"}
signInButton = {"xpath":"//button[@id='nextbtn']//span[text()='Sign in']"}
ErrorText ={"xpath":"//div[@class='fielderror errorlabel']"}
emailIDTextBox = {"id":"login_id"}
signInText = {"xpath" : "//span[@id='headtitle' and text()='Sign in']"}
loginErrorMessage= {"xpath" : "//div[@id='getusername']//div[@class='fielderror errorlabel']"}
<file_sep>import logging
from behave import given, then
from base.webdriverfactory import WebDriverFactory
from pages.actions.homepage.homepage import HomePage
@given('User go to the site')
def userGoToURL(context):
# wb = WebDriverFactory("chrome")
# context.driver=wb.getWebDriverInstance()
pass
@then('Page title should be "{pageTitle}"')
def userHomePageTitle(context,pageTitle):
context.hp = HomePage(context.driver)
assert context.hp.verifyHomePageTitle() == "Zoho - Cloud Software Suite and SaaS Applications for Businesses"
@then('URL should be "{url}"')
def pageUrl(context,url):
context.hp = HomePage(context.driver)
assert context.hp.verifyHomePageURL() == "https://www.zoho.com/"
<file_sep>import time
from base.webdriverfactory import WebDriverFactory
from pages.actions.homepage.homepage import HomePage
from behave import given,when,then
from utilities.teststatus import TestStatus
@given('User is on HomePage')
def userGoToURL(context):
# wb = WebDriverFactory("chrome")
# context.driver = wb.getWebDriverInstance()
pass
@when('User clicks on the Sign In link')
def userSignInClick(context):
context.hp = HomePage(context.driver)
context.lp=context.hp.clickSignInLink()
@when('User enters "{email}" as email')
def userEnterEmail(context,email):
context.lp.enterEmail(email)
@when('User clicks Next Button')
def userClickNextButton(context):
context.lp.clickNextButton()
@when('User enters "{password}" as password')
def userEntersPassword(context,password):
context.lp.enterPassword(password)
time.sleep(4)
@when('User clicks Sign In Button')
def userClickSignIn(context):
context.chp=context.lp.clickSignInButton()
time.sleep(5)
@then('Client Home Page is displayed')
def userClientHomePage(context):
clientHomePageTitle=context.chp.verifyClientHomePageTitle()
result=bool(clientHomePageTitle == "Zoho Home")
context.ts = TestStatus(context.driver)
context.ts.mark("userClientHomePage", result, "ClientHomePage is displayed")
@then('error message "{errorMessage}" is displayed')
def userErrorMessage(context,errorMessage):
errorMsg = context.lp.getLoginErrorMessage()
result = bool(errorMsg == errorMessage)
context.ts = TestStatus(context.driver)
context.ts.mark("userErrorMessage", result, "Error Message is Displayed")
@when('User fill the login details')
def userLoginDetails(context):
context.execute_steps(u"""
When User clicks on the Sign In link
And User enters "<EMAIL>" as email
And User clicks Next Button
And User enters "<PASSWORD>#" as password
And User clicks Sign In Button
""")
<file_sep>import subprocess
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--testDir',required=False,help="Location of test files")
parser.add_argument('--behaveOptions',type=str,required=False,help="String of behave option.For Example tags like -t <tag name>")
args = parser.parse_args()
testDir = args.testDir
behaveOptions = '' if not args.behaveOptions else args.behaveOptions
command = f'behave -k --no-capture {behaveOptions} {testDir} '
print(f"Running Command: {command}")
rs = subprocess.run(command,shell=True)<file_sep>from steps.homepagesteps.homepagesteps import *
from steps.loginpagesteps.loginpagesteps import *<file_sep>import logging
from base.basepage import BasePage
from pages.actions.homepage.customerpage import CustomerPage
from pages.actions.loginpage.loginpage import LoginPage
from utilities import custom_logger as cl
from base.selenium_driver import SeleniumDriver
from pages.locators.homepagelocators.homepagelocators import HomePageLocators as locator
class HomePage(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
def menuLinksText(self):
listText = []
elements=self.getElements(locator.menulinks)
for element in elements:
listText.append(element.text)
return listText
def clickCustomersLink(self):
SeleniumDriver(self.driver).elementClick(locator.customerLink)
return CustomerPage(self.driver)
def clickSignInLink(self):
self.elementClick(locator.signInLink)
return LoginPage(self.driver)
def verifyHomePageTitle(self,):
return self.verifyPageTitle()
def verifyHomePageURL(self):
return self.verifyPageURL()
| 3fc5495d7af5b2254b0cf14fe343947d86904092 | [
"Python"
] | 7 | Python | ShankuBisai/WebAutomationFramework-BDD | 51ff546023425efdc3fa137371a1824da9706d52 | b18830bbebc9635c972820358c07b649d2f485a9 |
refs/heads/master | <file_sep><section class="dashboard-panel-izq">
<div class="dashboard-box">
<div class="dashboard-box-title">
<span>Productos con mas movimiento</span>
<span class="icono icon-cancel-circle"></span>
<span class="icono max-min icon-circle-up"></span>
</div>
<div class="dashboard-box-content">
<div class="chart-content">
<canvas id="prod_mov"></canvas>
</div>
</div>
</div>
</section>
<section class="dashboard-panel-der">
<div class="dashboard-box">
<div class="dashboard-box-title">
<span>Retiros y Facturas de Bodega</span>
<span class="icono icon-cancel-circle"></span>
<span class="icono max-min icon-circle-up"></span>
</div>
<div class="dashboard-box-content">
<div class="chart-content">
<canvas id="descargos"></canvas>
</div>
</div>
</div>
</section>
<script src=<?= base_url("assets/js/Chart.js")?>></script>
<script type="text/javascript">
$(document).ready(function(){
var lbls = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
$.ajax({
type: 'post',
url: baseurl + "index.php/Dashboard/obtenerDescargosCargos",
data: {},
success: function(result) {
var res = JSON.parse(result);
var ctx = $("#descargos");
var data = {
labels: lbls,
datasets: [
{
label: "Retiros",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(119,190,119,0.4)",
borderColor: "rgb(119,190,119)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgb(119,190,119)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgb(119,190,119)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [res['descargos']['enero'],res['descargos']['febrero'],res['descargos']['marzo'],res['descargos']['abril'],res['descargos']['mayo'],res['descargos']['junio'],res['descargos']['julio'],res['descargos']['agosto'],res['descargos']['septiembre'],res['descargos']['octubre'],res['descargos']['noviembre'],res['descargos']['diciembre']],
spanGaps: false,
},
{
label: "Facturas",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [res['cargos']['enero'],res['cargos']['febrero'],res['cargos']['marzo'],res['cargos']['abril'],res['cargos']['mayo'],res['cargos']['junio'],res['cargos']['julio'],res['cargos']['agosto'],res['cargos']['septiembre'],res['cargos']['octubre'],res['cargos']['noviembre'],res['cargos']['diciembre']],
spanGaps: false,
}
]
};
var line = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
yAxes: [{
stacked: false
}]
}
}
});
},
});
$.ajax({
type: 'post',
url: baseurl + "index.php/Dashboard/obtenerProductoMovimiento",
data: {},
success: function(result) {
var res = JSON.parse(result);
var ctx = $("#prod_mov");
var data = {
labels: [
res[0]['nombre_producto'],
res[1]['nombre_producto'],
res[2]['nombre_producto'],
res[3]['nombre_producto'],
res[4]['nombre_producto']
],
datasets: [
{
data: [
res[0]['total'],
res[1]['total'],
res[2]['total'],
res[3]['total'],
res[4]['total'],
],
backgroundColor: [
"#AEC6CF",
"#B39EB5",
"#FFB347",
"#779ECB",
"#836953"
],
hoverBackgroundColor: [
"#AEC6CF",
"#B39EB5",
"#FFB347",
"#779ECB",
"#836953"
]
}
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
animation:{
animateScale:true
}
});
},
});
});
</script>
<file_sep># QUE ES SIB
Sistema Informático de Bodega Institucional para el INSAFOCOOP
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends CI_Controller {
public $cant_meses = array(
'enero' => 0,
'febrero' => 0,
'marzo' => 0,
'abril' => 0,
'mayo' => 0,
'junio' => 0,
'julio' => 0,
'agosto' => 0,
'septiembre' => 0,
'octubre' => 0,
'noviembre' => 0,
'diciembre' => 0,
);
public $meses = array(
'enero',
'febrero',
'marzo',
'abril',
'mayo',
'junio',
'julio',
'agosto',
'septiembre',
'octubre',
'noviembre',
'diciembre',
);
public function __construct() {
parent::__construct();
$this->load->model(array('Bodega/Solicitud_Model','Bodega/Factura_Model','Bodega/Producto'));
}
public function index(){
$USER = $this->session->userdata('logged_in');
if($USER){
$data['title'] = "Home";
$data['menu'] = $this->menu_dinamico->menus($USER, $this->uri->segment(1));
switch ($USER['rol']) {
case 'JEFE BODEGA':
$data['dhb'] = $this->load->view('dashboard/dhb_jefe_bodega', '', true);
break;
case 'USUARIO SIB':
$data['dhb'] = $this->load->view('dashboard/dhb_usuario', '', true);
break;
case 'COLABORADOR BODEGA':
$data['dhb'] = $this->load->view('dashboard/dhb_colaborador_bodega', '', true);
break;
default:
$data['dhb'] = $this->load->view('dashboard/dhb_usuario', '', true);
break;
}
$this->load->view('dashboard_view', $data);
} else {
redirect('login/index/error_no_autenticado');
}
}
/*
* <NAME>
*/
public function obtenerDescargosCargos(){
$cant_meses_des = $this->cant_meses;
$datos = $this->Solicitud_Model->obtenerLiquidadas(date("Y"));
if ($datos) {
$mes = 0;
foreach ($datos as $dato) {
$ar_meses = explode("-", $dato->fecha_solicitud);
$mes = $ar_meses[1];
$cant = $cant_meses_des[$this->meses[$mes - 1]] + 1;
$cant_meses_des[$this->meses[$mes - 1]] = $cant;
}
}
$cant_meses_car = $this->cant_meses;
$datos = $this->Factura_Model->obtenerLiquidadas(date("Y"));
if ($datos) {
$mes = 0;
foreach ($datos as $dato) {
$ar_meses = explode("-", $dato->fecha_ingreso);
$mes = $ar_meses[1];
$cant = $cant_meses_car[$this->meses[$mes - 1]] + 1;
$cant_meses_car[$this->meses[$mes - 1]] = $cant;
}
}
$cant_meses = array(
'descargos' => $cant_meses_des,
'cargos' => $cant_meses_car
);
echo json_encode($cant_meses);
}
public function obtenerSolicitudesCompra(){
$cant_meses = $this->cant_meses;
$USER = $this->session->userdata('logged_in');
$datos = $this->Solicitud_Compra_Model->obtenerSolicitudesCompraUserDHB($USER['id_seccion'], date("Y"));
if ($datos) {
$mes = 0;
foreach ($datos as $dato) {
$ar_meses = explode("-", $dato->fecha_solicitud_compra);
$mes = $ar_meses[1];
$cant = $cant_meses[$this->meses[$mes - 1]] + 1;
$cant_meses[$this->meses[$mes - 1]] = $cant;
}
}
echo json_encode($cant_meses);
}
public function obtenerProductoMovimiento() {
echo json_encode($this->Producto->obtenerProductoMasMovimiento());
}
public function obtenerGastosSeccion() {
$USER = $this->session->userdata('logged_in');
$com = $this->Compromiso_Presupuestario_Model->obtenerGastoComprasSeccion($USER['id_seccion'], date("Y")."-01-01", date("Y")."-12-31");
$bod = $this->Solicitud_Model->obtenerGastosRetiros($USER['id_seccion'], date("Y")."-01-01", date("Y")."-12-31");
echo json_encode($com->total + $bod->total);
}
/*
* USUARIO SIB
*/
public function obtenerSolicitudesCompraBodegaUsuario() {
$cant_meses_compra = $this->cant_meses;
$USER = $this->session->userdata('logged_in');
$cant_meses_bodega = $this->cant_meses;
$datos = $this->Solicitud_Model->obtenerSolicitudesUserFecha($USER['id'], date("Y"));
if ($datos) {
$mes = 0;
foreach ($datos as $dato) {
$ar_meses = explode("-", $dato->fecha_solicitud);
$mes = $ar_meses[1];
$cant = $cant_meses_bodega[$this->meses[$mes - 1]] + 1;
$cant_meses_bodega[$this->meses[$mes - 1]] = $cant;
}
}
$data = array($cant_meses_compra , $cant_meses_bodega);
echo json_encode($data);
}
public function obtenerSolicitudesCompraBodegaJefe() {
$cant_meses_compra = $this->cant_meses;
$USER = $this->session->userdata('logged_in');
$datos = $this->Solicitud_Compra_Model->obtenerSolicitudesCompraUserDHB($USER['id_seccion'], date("Y"));
if ($datos) {
$mes = 0;
foreach ($datos as $dato) {
$ar_meses = explode("-", $dato->fecha_solicitud_compra);
$mes = $ar_meses[1];
$cant = $cant_meses_compra[$this->meses[$mes - 1]] + 1;
$cant_meses_compra[$this->meses[$mes - 1]] = $cant;
}
}
$cant_meses_bodega = $this->cant_meses;
$datos = $this->Solicitud_Model->obtenerSolicitudesSeccionFecha($USER['id_seccion'], date("Y"));
if ($datos) {
$mes = 0;
foreach ($datos as $dato) {
$ar_meses = explode("-", $dato->fecha_solicitud);
$mes = $ar_meses[1];
$cant = $cant_meses_bodega[$this->meses[$mes - 1]] + 1;
$cant_meses_bodega[$this->meses[$mes - 1]] = $cant;
}
}
$data = array($cant_meses_compra , $cant_meses_bodega);
echo json_encode($data);
}
public function obtenerActivosFijosUser() {
$USER = $this->session->userdata('logged_in');
echo json_encode($this->Datos_Comunes_Model->totalBienesUsuario($USER['id_empleado'])->total);
}
public function obtenerSolicitudesDesApr() {
$USER = $this->session->userdata('logged_in');
$data = array(
'bod_ap' => $this->Solicitud_Model->obtenerSolicitudesAprobadasSeccion($USER['id_seccion'], date("Y"))->cantidad,
'bod_dap' => $this->Solicitud_Model->obtenerSolicitudesNoAprobadasSeccion($USER['id_seccion'], date("Y"))->cantidad,
'cmp_ap' => $this->Solicitud_Compra_Model->obtenerSolicitudesAprobadasSeccionFecha($USER['id_seccion'], date("Y"))->cantidad,
'cmp_dap' => $this->Solicitud_Compra_Model->obtenerSolicitudesNoAprobadasSeccionFecha($USER['id_seccion'], date("Y"))->cantidad
);
echo json_encode($data);
}
public function obtenerSolicitudesCompraEnProceso() {
echo json_encode($this->Solicitud_Compra_Model->obtenerSolicitudesAprJefe(date("Y"))->cantidad);
}
public function obtenerGastoTotalBodega() {
$data = array(
'mes' => $this->Solicitud_Model->obtenerGastoTotalBodegaMes(date("m"), date("Y"), date("t"))->total,
'mes_ant' => 0
);
if (date("m") == 01) {
$data['mes_ant'] = $this->Solicitud_Model->obtenerGastoTotalBodegaMes(12, date("Y")-1, date("t"))->total;
} else {
$data['mes_ant'] = $this->Solicitud_Model->obtenerGastoTotalBodegaMes(date("m")-1, date("Y"), date("t"))->total;
}
echo json_encode($data);
}
}
?>
<file_sep><?php
class Seccion_model extends CI_Model{
function __construct() {
parent::__construct();
}
public function obtenerPorIdSeccion($id){
$this->db->where('id_seccion', $id);
$query = $this->db->get('org_seccion')->row();
$seccion = '';
if (!is_null($query)) {
$seccion = $query->nombre_seccion;
}
return $seccion;
}
public function nombreEmpleado($id_empleado) {
$this->db->select('primer_nombre, segundo_nombre, primer_apellido, segundo_apellido')
->from('sir_empleado')
->where('id_empleado', $id_empleado);
$query = $this->db->get();
if ($query->num_rows()>0) {
$empleado = $query->row();
return $empleado->primer_nombre . " " . $empleado->segundo_nombre . " " . $empleado->primer_apellido . " " . $empleado->segundo_apellido;
}
}
}
?>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><?= $title?></title>
<link rel="shortcut icon" href="<?= base_url("assets/image/logo.jpg")?>" />
<link href=<?= base_url("vendor/twbs/bootstrap/dist/css/bootstrap.min.css")?> rel="stylesheet" media="screen">
<link href=<?= base_url("assets/css/main.css")?> rel="stylesheet" media="screen">
<link href=<?= base_url("assets/css/menu.css")?> rel="stylesheet" media="screen">
<link href=<?= base_url("assets/css/sweetalert.css")?> rel="stylesheet" media="screen">
<link rel="shortcut icon" href="<?= base_url("assets/image/logo.jpg")?>" />
<script type="text/javascript">
var baseurl = "<?= base_url(); ?>";
</script>
</head>
<body onload="window.print()">
<div align="right"><img src=<?= base_url("assets/image/icono.jpg")?> alt="" width="100px"/></div>
<?php
setlocale (LC_TIME, 'es_ES');
date_default_timezone_set('America/El_Salvador');
$hora=date_create($var['hora']);
echo "<br><br><br><br><center><b>Instituto Salvadoreño de Fomento Cooperativo - SIB</b></center>";
echo "<br><br><center><H2>ACTA DE RECEPCION DE MERCADERIA</H2></center>";
#echo "<br>Correlativo: ".$var['id_factura'];
echo "<br>Correlativo de Fuente de Fondos: ".$var['nombre_fuente']."-".$var['correlativo'];
echo "<br><br>En la Bodega General, del Instituto Salvadoreño de Fomento Cooperativo a las ".date_format($hora,"h:i A").
" de la fecha ".$var['fecha_ingreso'].
", reunidos los señores ".$var['nombre_entrega']." de la empresa ".$var['nombre_proveedor'].
" y el señor(a) <NAME>.";
echo "<br><br>Representando al Instituto Salvadoreño de Fomento Cooperativo, para la recepción de mercaderia que a continuación se detalla,
segun factura No. ".$var['numero_factura']." de fecha ".$var['fecha_factura'].".";
echo "<br><br>";
echo "<center>$table</center>";
echo('<br>'.$var['comentario_productos']);
echo "<br><br>No habiendo más que hacer constar y leída que fue, para constancia firmamos.";
echo "<br><br><br><br><br><br>";
echo "<left>____________________________</left>"."       
                          
                ____________________________";
echo "<br>Por Empresa Suministrante"."       
                          
                          
 Por Bodega General";
?>
</body>
</html>
<file_sep><?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Notificacion.php
*/
class Notificacion {
public $emisor;
public $receptor;
public $mensaje_notificacion;
public $url_notificacion;
public $clase_notificacion;
function __construct() {
$this->ci =& get_instance();
$this->ci->load->model(array('User_model', 'Bodega/Solicitud_Model'));
}
public function insertarNotificacion($data){
$this->ci->emisor = $data['emisor'];
$this->ci->receptor = $data['receptor'];
$this->ci->mensaje_notificacion = $data['mensaje_notificacion'];
$this->ci->url_notificacion = $data['url_notificacion'];
$this->ci->clase_notificacion = $data['clase_notificacion'];
$this->ci->db->insert('sic_notificacion', $this->ci);
return $this->ci->db->insert_id();
}
public function eliminarNotificacion($id) {
$this->ci->db->delete('sic_notificacion', array('id_notificacion' => $id));
}
public function obtenerNotificaciones($id_usuario) {
$this->ci->db->from('sic_notificacion')
->where('receptor', $id_usuario)
->order_by("id_notificacion", "asc");
$query = $this->ci->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return FALSE;
}
}
public function totalNotificacion($id_usuario) {
$this->ci->db->from('sic_notificacion')
->where('receptor', $id_usuario);
return $this->ci->db->count_all_results();
}
public function EnviarNotificacion($data) {
if (is_array($data)) {
$nombre_emisor = $data['nombre_emisor'];
$correo_emisor = $data['correo_emisor'];
$id_emisor = $data['id_emisor'];
$correo_receptor = $data['correo_receptor'];
$id_receptor = $data['id_receptor'];
$asunto = $data['asunto'];
$mensaje = $data['mensaje'];
$url = $data['url'];
if ('' != $id_emisor && '' != $id_receptor && '' != $mensaje && '' != $url) {
$not = array(
'emisor' => $id_emisor,
'receptor' => $id_receptor,
'mensaje_notificacion' => $mensaje,
'url_notificacion' => $url,
'clase_notificacion' => 'success',
);
$this->insertarNotificacion($not);
}
if ('' != $nombre_emisor && '' != $correo_receptor && '' != $asunto && '' != $mensaje) {
$this->ci->load->library('email');
$config = array(
'protocol' => 'sendmail',
'mailtype' => 'html'
);
$this->ci->email->initialize($config);
$this->ci->email->from($nombre_emisor);
$this->ci->email->to($correo_receptor);
$this->ci->email->subject('SICBAF: ' . $asunto);
$this->ci->email->message('<h2>' . $mensaje . '</h2>');
$this->ci->email->send();
}
}
}
// como emisor recibe a $USER de la sesion
public function NotificacionSolicitudBodega($id_solicitud, $emisor, $nivel) {
$emisor = $this->ci->User_model->obtenerUsuario($emisor['id']);
$data = array();
$roles = $this->ci->User_model->obtenerRolesSistema();
switch ($nivel) {
case 1:
// enviar a jefe unidad
$receptor = $this->ci->User_model->obtenerCorreoUsuario($roles[4]['id_rol'], $emisor->id_seccion);
if ($receptor) {
$data[0]['nombre_emisor'] = $emisor->nombre_completo;
$data[0]['correo_emisor'] = $emisor->correo;
$data[0]['id_emisor'] = $emisor->id_usuario;
$data[0]['correo_receptor'] = $receptor->correo;
$data[0]['id_receptor'] = $receptor->id_usuario;
$data[0]['mensaje'] = "Hay una nueva solicitud que require atención con id " . $id_solicitud;
$data[0]['asunto'] = 'Solicitud Bodega';
$data[0]['url'] = base_url("index.php/Bodega/Solicitud_control");
}
break;
case 2:
// enviar a DA
$receptor = $this->ci->User_model->obtenerCorreoUsuario($roles[1]['id_rol'], 36);
if ($receptor) {
$data[0]['nombre_emisor'] = $emisor->nombre_completo;
$data[0]['correo_emisor'] = $emisor->correo;
$data[0]['id_emisor'] = $emisor->id_usuario;
$data[0]['correo_receptor'] = $receptor->correo;
$data[0]['id_receptor'] = $receptor->id_usuario;
$data[0]['mensaje'] = "Hay una nueva solicitud que require atención con id " . $id_solicitud;
$data[0]['asunto'] = 'Solicitud Bodega';
$data[0]['url'] = base_url("index.php/Bodega/Solicitud_control");
}
// solicitante
$solicitud = $this->ci->Solicitud_Model->obtenerTodaSolicitud($id_solicitud);
$receptor = $this->ci->User_model->obtenerUsuario($solicitud[0]->id_usuario);
if ($receptor) {
$data[1]['nombre_emisor'] = $emisor->nombre_completo;
$data[1]['correo_emisor'] = $emisor->correo;
$data[1]['id_emisor'] = $emisor->id_usuario;
$data[1]['correo_receptor'] = $receptor->correo;
$data[1]['id_receptor'] = $receptor->id_usuario;
$data[1]['mensaje'] = "La solicitud id " . $id_solicitud . " ha sido aprobada por su Jefe.";
$data[1]['asunto'] = 'Solicitud Bodega';
$data[1]['url'] = base_url("index.php/Bodega/Solicitud_control");
}
break;
case 3:
# enviar a Bodega
$receptor = $this->ci->User_model->obtenerCorreoUsuario($roles[3]['id_rol'], 72);
if ($receptor) {
$data[0]['nombre_emisor'] = $emisor->nombre_completo;
$data[0]['correo_emisor'] = $emisor->correo;
$data[0]['id_emisor'] = $emisor->id_usuario;
$data[0]['correo_receptor'] = $receptor->correo;
$data[0]['id_receptor'] = $receptor->id_usuario;
$data[0]['asunto'] = "Hay una nueva solicitud que require atención con id " . $id_solicitud;
$data[0]['mensaje'] = 'Solicitud Bodega';
$data[0]['url'] = base_url("index.php/Bodega/Solicitud_control");
}
// solicitante
$solicitud = $this->ci->Solicitud_Model->obtenerTodaSolicitud($id_solicitud);
$receptor = $this->ci->User_model->obtenerUsuario($solicitud[0]->id_usuario);
if ($receptor) {
$data[1]['nombre_emisor'] = $emisor->nombre_completo;
$data[1]['correo_emisor'] = $emisor->correo;
$data[1]['id_emisor'] = $emisor->id_usuario;
$data[1]['correo_receptor'] = $receptor->correo;
$data[1]['id_receptor'] = $receptor->id_usuario;
$data[1]['mensaje'] = "La solicitud id " . $id_solicitud . " ha sido aprobada por Directora Administrativa.";
$data[1]['asunto'] = 'Solicitud Bodega';
$data[1]['url'] = base_url("index.php/Bodega/Solicitud_control");
}
break;
case 4:
# enviar a solicitante
$solicitud = $this->ci->Solicitud_Model->obtenerTodaSolicitud($id_solicitud);
$receptor = $this->ci->User_model->obtenerUsuario($solicitud[0]->id_usuario);
if ($receptor) {
$data[0]['nombre_emisor'] = $emisor->nombre_completo;
$data[0]['correo_emisor'] = $emisor->correo;
$data[0]['id_emisor'] = $emisor->id_usuario;
$data[0]['correo_receptor'] = $receptor->correo;
$data[0]['id_receptor'] = $receptor->id_usuario;
$data[0]['mensaje'] = "La solicitud id " . $id_solicitud . " ha sido liquidada.";
$data[0]['asunto'] = 'Solicitud Bodega';
$data[0]['url'] = base_url("index.php/Bodega/Solicitud_control");
}
break;
case 9:
# enviar a solicitante
$solicitud = $this->ci->Solicitud_Model->obtenerTodaSolicitud($id_solicitud);
$receptor = $this->ci->User_model->obtenerUsuario($solicitud[0]->id_usuario);
if ($receptor) {
$data[0]['nombre_emisor'] = $emisor->nombre_completo;
$data[0]['correo_emisor'] = $emisor->correo;
$data[0]['id_emisor'] = $emisor->id_usuario;
$data[0]['correo_receptor'] = $receptor->correo;
$data[0]['id_receptor'] = $receptor->id_usuario;
$data[0]['mensaje'] = "La solicitud id " . $id_solicitud . " no ha sido aprobada.";
$data[0]['asunto'] = 'Solicitud Bodega';
$data[0]['url'] = base_url("index.php/Bodega/Solicitud_control");
}
break;
}
foreach ($data as $dato) {
$this->EnviarNotificacion($dato);
}
}
}
?>
<file_sep><?php $this->ci =& get_instance(); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<title><?= $title?></title>
<link rel="shortcut icon" href="<?= base_url("assets/image/logo.jpg")?>" />
<link href=<?= base_url("vendor/twbs/bootstrap/dist/css/bootstrap.min.css")?> rel="stylesheet" media="screen">
<link href=<?= base_url("assets/css/main.css")?> rel="stylesheet" media="screen">
<link href=<?= base_url("assets/css/menu.css")?> rel="stylesheet" media="screen">
<link href=<?= base_url("assets/css/sweetalert.css")?> rel="stylesheet" media="screen">
<link href=<?= base_url("assets/css/iconos.css")?> rel="stylesheet" media="screen">
<script type="text/javascript">
var baseurl = "<?= base_url(); ?>";
</script>
</head>
<body>
<div>
<?php
if (isset($menu)) {
echo $menu;
}
?>
</div>
<div class="content">
<?= $body?>
</div></div>
</div></div>
<?php $this->ci->load->view("help/reportar_problema"); ?>
<div class="footer">
<div class="content_footer">
<div class="content-info-sis">
<p class="name-sis">
SIB INSAFOCOOP
</p>
<p>
Copyright (c) 2017 Copyright Holder All Rights Reserved.
</p>
</div>
<div class="conten-info-min">
<img id="ues" src="<?= base_url("assets/image/minerva.gif")?>" alt="" width="50px"/>
<img id="escudo" src="<?= base_url("assets/image/escudo.png")?>" alt="" />
<img id="escudo" src="<?= base_url("assets/image/icono.jpg")?>" alt="" />
<div class="nombre-inst"> INSTITUTO SALVADOREÑO DE FOMENTO COOPERATIVO.</div>
</div>
</div>
</div>
<!-- script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script -->
<script src='<?= base_url('assets/js/jquery-1.11.3.min.js') ?>'></script>
<script src="<?= base_url('assets/js/jquery.validate.min.js')?>"></script>
<script src="<?= base_url('assets/js/html2canvas.min.js')?>"></script>
<script src="<?= base_url("assets/js/validate/additional-methods.js")?>"></script>
<script src="<?= base_url('assets/js/jquery-migrate-1.2.1.min.js')?>"></script>
<script src="<?= base_url("vendor/twbs/bootstrap/dist/js/bootstrap.min.js")?>"></script>
<script src="<?= base_url("assets/js/jQueryRotate.js")?>"></script>
<script src="<?= base_url("assets/js/main.js")?>"></script>
<?php
if (isset($js)) {
echo "<script src=".base_url($js)." type=\"text/javascript\"></script>";
}
?>
<script src="<?= base_url("assets/js/notice.js")?>"></script>
<script src="<?= base_url("assets/js/help.js")?>"></script>
<script src="<?= base_url("assets/js/sweetalert.min.js")?>"></script>
</body>
</html>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Help extends CI_Controller {
public function __construct() {
parent::__construct();
if($this->session->userdata('logged_in') == FALSE){
redirect('login/index/error_no_autenticado');
}
}
public function sendMail() {
$USER = $this->session->userdata('logged_in');
$from = $this->User_model->obtenerUsuario($USER['id']);
$this->load->library("email");
$configGmail = array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => '<EMAIL>',
'smtp_pass' => '<PASSWORD>',
'mailtype' => 'html',
'charset' => 'utf-8',
'newline' => "\r\n"
);
$this->email->initialize($configGmail);
//$from->correo
$this->email->from("<EMAIL>");
$this->email->to("<EMAIL>");
$this->email->cc("<EMAIL>", "<EMAIL>", "<EMAIL>");
$this->email->subject($this->input->post('asunto'));
$this->email->message($this->input->post('msj'));
$this->email->attach(base_url('uploads/'.$this->input->post('image')));
$this->email->send();
unlink("uploads/".$this->input->post('image'));
echo $this->email->print_debugger();
}
public function seveScreen() {
$img = $this->input->post('img');
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$im = imagecreatefromstring($data); //convertir text a imagen
// generando nombre imagen
date_default_timezone_set('America/El_Salvador');
$name = "screenshots-" . date("Y-m-d-H-i");
if ($im !== false) {
imagejpeg($im, 'uploads/'.$name.'.jpg'); //guardar a server
imagedestroy($im); //liberar memoria
echo $name;
}else {
echo '';
}
}
public function eliminarImagen() {
unlink("uploads/".$this->input->post('image'));
}
}
<file_sep>var not = 0;
var max = 2;
var activo = 0;
$(document).ready(function() {
$('html').click(function () {
$('.container-area-notice').slideUp();
$('.tgs').slideUp();
activo = 0;
});
$('.container-area-notice').click(function (e) {
e.stopPropagation();
});
$('#notice').click(function (e) {
if (1 == activo) {
$('.container-area-notice').slideUp();
$('.tgs').slideUp();
activo = 0;
} else if (0 == activo) {
$('.container-area-notice').slideDown();
$('.tgs').slideDown();
Notificaciones();
activo = 1;
}
e.stopPropagation();
});
TotalNotificaciones();
setInterval(function() {
TotalNotificaciones();
}, 60000);
});
var getLocation = function() {
var arrayLocation = String(window.location).split('/');
return arrayLocation[5];
}
var Notificaciones = function() {
var elemet = $(this);
var content = $('.content-area-notice');
$.ajax({
type: 'post',
dataType: 'json',
url: baseurl + "index.php/CNotificacion/ConsultarNotificaciones",
//data: {},
success: function(result) {
var mensaje = "";
var i;
if (result) {
for (i = 0; i < result.length; i++) {
mensaje += "<div class='alert alert-notification alert-dismissable'>";
mensaje += "<button type='button' class='close' data-id='"+result[i].id_notificacion+"' data-dismiss='alert'>×</button>";
mensaje += "<a href="+result[i].url_notificacion+"><div class='cont-icon " + GenerarIcon(result[i].url_notificacion) + "'></div>" ;
mensaje += "<div class='cont-notice'>"+result[i].mensaje_notificacion+"</div>" ;
mensaje += "</a></div>";
}
} else {
mensaje = "<div class='content-no-notice'>Has leído todas las notificaciones</div>";
}
content.html(mensaje);
$('.close').click(function() {
var id = $(this).data('id');
$(this).parent().hide(400);
$.ajax({
type: 'post',
data: { id: id },
url: baseurl + "index.php/CNotificacion/EliminarDato",
success: function(result) {
$('#notice .badge').text(result);
}
});
});
},
});
}
var GenerarIcon = function (url) {
var urls = url.split('/');
var icon = "";
switch (urls[5]) {
case "Compras":
icon = "icon-compra";
break;
case "Bodega":
icon = "icon-database";
break;
case "ActivoFijo":
icon = "icon-office";
break;
default:
icon = "icon-bell";
}
return icon;
}
var Notificacion = function() {
var elemet = $(this);
var content = $('.content-notice');
$.ajax({
type: 'post',
dataType: 'json',
url: baseurl + "index.php/CNotificacion/ConsultarNotificaciones",
success: function(result) {
var mensaje = "";
for (var i = 0; i < result.length; i++) {
mensaje += "<div class='alert alert-"+ result[i].clase_notificacion +" alert-dismissable' style='display: 'none''><a href="+result[i].url_notificacion+">";
mensaje += "<button type='button' class='close' data-id='"+result[i].id_notificacion+"' data-dismiss='alert'>×</button>";
mensaje += result[i].mensaje_notificacion;
mensaje += "</a></div>";
if (max == i) {
break;
max = 2;
}
}
content.html(mensaje);
$(".content-notice .alert").slideDown();
setInterval(function() {
$(".content-notice .alert").slideUp();
}, 5000);
},
});
}
var TotalNotificaciones = function () {
var elemet = $(this);
var content = $('.content-area-notice');
$.ajax({
type: 'post',
dataType: 'json',
url: baseurl + "index.php/CNotificacion/TotalNotificaciones",
success: function(result) {
$('#notice .badge').text(result);
if (result > not) {
max = 0;
Notificacion();
}
not = result;
},
});
}
| 40f0dd47ddfd5c5e019e7669d1e4110639ea5c14 | [
"Markdown",
"JavaScript",
"PHP"
] | 9 | PHP | moisesHerrera01/SIB | 7223192696cb6be12e108d25d5680b15fbdf5bf0 | d44b34a3b5f0dfd8789d0bc3581f8642ac10601f |
refs/heads/master | <repo_name>yolan90/CardGame<file_sep>/CardGame/ViewController.swift
//
// ViewController.swift
// CardGame
//
// Created by <NAME> on 01/02/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var winnerLabel: UILabel!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var firstPlayerCardLabel1: UILabel!
@IBOutlet weak var firstPlayerCardLabel2: UILabel!
@IBOutlet weak var secondPlayerCardLabel1: UILabel!
@IBOutlet weak var secondPlayerCardLabel2: UILabel!
enum CardNumber : Int, CaseIterable {
case ace = 1, two = 2, three = 3, four = 4, five = 5, six = 6, seven = 7, eight = 8, nine = 9, ten = 10, jack = 11, queen = 12, king = 13
}
enum CardSuit : String, CaseIterable {
case spade = "♠️", heart = "♥️", club = "♣️", diamond = "♦️"
}
@IBAction func playGame(_ sender: Any) {
var cardSuitArr : [String] = []
for item in CardSuit.allCases {
cardSuitArr.append(item.rawValue)
}
cardSuitArr.shuffle()
let player1Card : Card = Card(cardNum: CardNumber(rawValue: Int.random(in: 1...13))!, cardSuit: cardSuitArr.shuffled()[0])
var player2Card : Card? = Card(cardNum: CardNumber(rawValue: Int.random(in: 1...13))!, cardSuit: cardSuitArr.shuffled()[0])
repeat {
player2Card = Card(cardNum: CardNumber(rawValue: Int.random(in: 1...13))!, cardSuit: cardSuitArr.shuffled()[0])
} while (player2Card?.cardNum == player1Card.cardNum && player2Card?.cardSuit == player1Card.cardSuit)
print("\(player1Card.cardNum.rawValue) \(player1Card.cardSuit)")
print("\(player2Card!.cardNum.rawValue) \(player2Card!.cardSuit)")
firstPlayerCardLabel1.text = "\(translateCardSymbol(card: player1Card)) \(player1Card.cardSuit)"
firstPlayerCardLabel2.text = "\(translateCardSymbol(card: player1Card)) \(player1Card.cardSuit)"
secondPlayerCardLabel1.text = "\(translateCardSymbol(card: player2Card!)) \(player2Card!.cardSuit)"
secondPlayerCardLabel2.text = "\(translateCardSymbol(card: player2Card!)) \(player2Card!.cardSuit)"
compare(card1: player1Card, card2: player2Card!)
winnerLabel.isHidden = false
}
func compare(card1: Card, card2: Card) {
if card1.cardNum.rawValue > card2.cardNum.rawValue {
winnerLabel.text = "player 1 wins!"
} else if card1.cardNum.rawValue < card2.cardNum.rawValue {
winnerLabel.text = "player 2 wins!"
} else {
winnerLabel.text = "Draw"
}
}
override func viewDidLoad() {
super.viewDidLoad()
winnerLabel.isHidden = true
// Do any additional setup after loading the view, typically from a nib.
}
struct Card {
var cardNum : CardNumber
var cardSuit : String
}
func translateCardSymbol(card: Card) -> String {
var cardNum = ""
switch(card.cardNum) {
case CardNumber.jack : cardNum = "J"
case CardNumber.queen : cardNum = "Q"
case CardNumber.king : cardNum = "K"
case CardNumber.ace: cardNum = "A"
default : cardNum = String(card.cardNum.rawValue)
}
return cardNum
}
}
| edadf4d02a86f3a3a5fc89402eb3f8b3b0322747 | [
"Swift"
] | 1 | Swift | yolan90/CardGame | 5fb4d0d425548b435e40e8deee281c4554d1a472 | b05a512cc6531e42836b363ee7ce9a7616cfd0f4 |
refs/heads/main | <file_sep>//
// UnionFindTests.swift
// UnionFindTests
//
// Created by <NAME> on 2020/11/10
// Copyright © 2020 <NAME>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import XCTest
@testable import UnionFind
final class UnionFindTests: XCTestCase {
var sut: UnionFind!
override func setUp() {
super.setUp()
sut = UnionFind()
}
override func tearDown() {
sut = nil
super.tearDown()
}
// MARK: - Intializers tests
func testInit_whenKIsZero() {
XCTAssertNotNil(sut)
XCTAssertNotNil(sut.ids)
XCTAssertNotNil(sut.sizes)
XCTAssertTrue(sut.isEmpty)
XCTAssertTrue(sut.ids.isEmpty)
XCTAssertTrue(sut.sizes.isEmpty)
}
func testInit_whenKIsGreaterThanZero() {
for k in 1...100 {
sut = UnionFind(k)
XCTAssertNotNil(sut)
XCTAssertNotNil(sut.ids)
XCTAssertNotNil(sut.sizes)
XCTAssertFalse(sut.isEmpty)
XCTAssertFalse(sut.ids.isEmpty)
XCTAssertFalse(sut.sizes.isEmpty)
XCTAssertEqual(sut.count, k)
XCTAssertEqual(sut.ids.count, k)
XCTAssertEqual(sut.sizes.count, k)
XCTAssertEqual(sut.ids, Array(0..<k))
XCTAssertEqual(sut.sizes, Array(repeating: 1, count: k))
}
}
// MARK: - Computed properties tests
func testCount() {
XCTAssertTrue(sut.isEmpty)
XCTAssertEqual(sut.count, 0)
XCTAssertEqual(sut.count, sut.ids.count)
whenNotEmptyElementsDisconnected()
XCTAssertFalse(sut.isEmpty)
XCTAssertGreaterThan(sut.count, 0)
XCTAssertEqual(sut.count, sut.ids.count)
}
func testIsEmpty() {
XCTAssertEqual(sut.count, 0)
XCTAssertTrue(sut.isEmpty)
XCTAssertEqual(sut.isEmpty, sut.ids.isEmpty)
whenNotEmptyElementsDisconnected()
XCTAssertGreaterThan(sut.count, 0)
XCTAssertFalse(sut.isEmpty)
XCTAssertEqual(sut.isEmpty, sut.ids.isEmpty)
}
// MARK: - Common functionalities tests
func testIncreaseNodesCount() {
for _ in 0..<10 {
let prevCount = sut.count
sut.increaseNodesCount()
XCTAssertEqual(sut.count, prevCount + 1)
XCTAssertEqual(sut.ids.count, sut.count)
XCTAssertEqual(sut.sizes.count, sut.count)
XCTAssertEqual(sut.ids[prevCount], prevCount)
XCTAssertEqual(sut.sizes[prevCount], 1)
}
let prevCount = sut.count
sut.increaseNodesCount(by: 10)
XCTAssertEqual(sut.count, prevCount + 10)
XCTAssertEqual(sut.ids.count, prevCount + 10)
XCTAssertEqual(sut.sizes.count, prevCount + 10)
XCTAssertEqual(Array(sut.ids[prevCount..<(prevCount + 10)]), Array(prevCount..<(prevCount + 10)))
XCTAssertEqual(Array(sut.sizes[prevCount..<(prevCount + 10)]), Array(repeating: 1, count: 10))
}
func testUnion() {
whenNotEmptyElementsDisconnected()
// when ids are equal, then nothing changes:
var prevIDS = sut.ids
var prevSizes = sut.sizes
sut.union(0, 0)
XCTAssertEqual(sut.ids, prevIDS)
XCTAssertEqual(sut.sizes, prevSizes)
// when ids are different, roots are different,
// then sets same root and weight of root increases by one:
XCTAssertNotEqual(sut.ids[0], sut.ids[1])
XCTAssertEqual(sut.sizes[0], sut.sizes[1])
sut.union(0, 1)
XCTAssertEqual(sut.ids[0], sut.ids[1])
XCTAssertGreaterThan(sut.sizes[sut.ids[0]], 1)
XCTAssertEqual(2, sut.sizes[sut.ids[0]])
// when ids are different, roots are same,
// then nothing changes:
prevIDS = sut.ids
prevSizes = sut.sizes
XCTAssertEqual(sut.ids[0], sut.ids[1])
sut.union(0, 1)
XCTAssertEqual(sut.ids, prevIDS)
XCTAssertEqual(sut.sizes, prevSizes)
// when ids and roots are different, leftmost root weight is
// smaller than rightmost one, then sets common root to
// rightmost one and increases rightmost root weight by
// leftmost root weight:
var lhs = 2
var rhs = 1
var lhsRoot = sut.ids[lhs]
var rhsRoot = sut.ids[rhs]
XCTAssertNotEqual(lhsRoot, rhsRoot)
var lhsRootPrevSize = sut.sizes[lhsRoot]
var rhsRootPrevSize = sut.sizes[rhsRoot]
XCTAssertGreaterThan(rhsRootPrevSize, lhsRootPrevSize)
sut.union(lhs, rhs)
XCTAssertEqual(sut.ids[lhs], sut.ids[rhs])
XCTAssertEqual(sut.ids[lhs], rhsRoot)
XCTAssertGreaterThan(sut.sizes[rhsRoot], rhsRootPrevSize)
XCTAssertEqual(sut.sizes[rhsRoot], rhsRootPrevSize + lhsRootPrevSize)
XCTAssertEqual(sut.sizes[rhsRoot], 3)
// when ids and roots are different, leftmost root weight is
// greater than rigthmost one, then sets common root to
// leftmost one, and increases leftmost root weight by
// rightmost root weight:
sut.union(3, 4)
lhs = 2
rhs = 3
lhsRoot = sut.ids[lhs]
rhsRoot = sut.ids[rhs]
XCTAssertNotEqual(lhsRoot, rhsRoot)
lhsRootPrevSize = sut.sizes[lhsRoot]
rhsRootPrevSize = sut.sizes[rhsRoot]
XCTAssertGreaterThan(lhsRootPrevSize, rhsRootPrevSize)
sut.union(lhs, rhs)
XCTAssertEqual(sut.ids[lhs], sut.ids[rhs])
XCTAssertEqual(sut.ids[lhs], lhsRoot)
XCTAssertGreaterThan(sut.sizes[lhsRoot], lhsRootPrevSize)
XCTAssertEqual(sut.sizes[lhsRoot], rhsRootPrevSize + lhsRootPrevSize)
XCTAssertEqual(sut.sizes[lhsRoot], 5)
}
func testAreConnected() {
whenNotEmptyElementsDisconnected()
// when lhs is equal to rhs, then returns true:
XCTAssertTrue(sut.areConnected(0, 0))
// when lhs and rhs are different and have different roots,
// then return false:
let lhs = 0
let rhs = 1
var lhsRoot = sut.find(lhs)
var rhsRoot = sut.find(rhs)
XCTAssertNotEqual(lhsRoot, rhsRoot)
XCTAssertFalse(sut.areConnected(lhs, rhs))
sut.union(lhs, rhs)
// when lhs and rhs are different and have same root,
// then returns true:
lhsRoot = sut.find(lhs)
rhsRoot = sut.find(rhs)
XCTAssertEqual(lhsRoot, rhsRoot)
XCTAssertTrue(sut.areConnected(lhs, rhs))
}
func testMonteCarloSimulation() {
for i in 0..<10 {
var montecarlo = MonteCarloSimulation(1000)
while montecarlo.p <= MonteCarloSimulation.pThreshold {
montecarlo.openRandomSite()
}
XCTAssertTrue(montecarlo.isPercolating, "Not percolating despite p is greater than p*\np = \(montecarlo.p)\np* = \(MonteCarloSimulation.pThreshold)\nIteration: \(i)\nOpened sites: \(montecarlo.openSitesCount)")
}
}
// MARK: - Private helpers
// MARK: - When
private func whenNotEmptyElementsDisconnected() {
sut = UnionFind(10)
}
}
<file_sep># UnionFind
A data structure for modelling dynamic connectivity.
Dynamic connectivity can be defined by two operations on a set of *n* distinctive elments:
- **Union Command**: connect two objects
- **Find/Connected Query**: is there a path connecting two elements?
Assuming *"is connected to"* is an equivalence relation between elements which is:
- **Reflexive**: *p* is connected to *p*.
- **Symmetric**: if *p* is connected to *q*, then *q* is also connected to *p*.
- **Transitive**: if *p* is connected to *q* and *q* is connected to *r*, then *p* is also connected to *r*.
Where *p*, *q*, *r* are distinct nodes from the set.
<file_sep>//
// UnionFind.swift
// UnionFind
//
// Created by <NAME> on 2020/11/10
// Copyright © 2020 <NAME>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
/// A data structure for modeling dynamic connectivity on a set of distinct elments.
///
/// Dynamic connectivity can be defined by two operations on a set of *n* distinctive
/// nodes:
/// - **Union Command**: connect two nodes.
/// - **Find/Connected Query**: is there a path connecting two nodes?
/// Assuming *"is connected to"* is an equivalence relation between nodes, that is:
/// - **Reflexive**: *p* is connected to *p*.
/// - **Symmetric**: if *p* is connected to *q*, then *q* is also connected to *p*.
/// - **Transitive**: if *p* is connected to *q* and *q* is connected to *r*,
/// then *p* is also connected to *r*.
/// Where *p*, *q*, *r* are distinct nodes from the set.
public struct UnionFind {
private(set) var ids: [Int] = []
private(set) var sizes: [Int] = []
/// Returns a new instance, initialized with the specified amount of nodes,
/// without any connection between them.
///
/// - Parameter _: An Int value representing the number of nodes for the new
/// instance. **Must not be negative**. Defaults to `0`.
/// - Returns: A new instance with the specified number of nodes,
/// without any connection between them.
public init(_ k: Int = 0) {
precondition(k >= 0, "k must not be negative")
guard k != 0 else { return }
self.ids = Array(0..<k)
self.sizes = Array(repeating: 1, count: k)
}
}
// MARK: - Public interface
// MARK: - Computed properties
extension UnionFind {
/// An integer value representing the total number of nodes in this instance.
public var count: Int { ids.count }
/// A Boolean value, `true` when this instance doesn't contain any node.
public var isEmpty: Bool { ids.isEmpty }
}
// MARK: - Union-Find functionalities
extension UnionFind {
/// Increases the number of nodes by the specified amount.
///
/// - Parameter by: An Int value representing the number of additional nodes
/// to add to this instance. **Must be positive**.
/// - Note: Added nodes will be disconnected from any other one, either already in the
/// instance before the operation, or new one.
/// - Complexity: O(log *m*) where *m* is the count of added nodes.
public mutating func increaseNodesCount(by k: Int = 1) {
precondition(k > 0, "k must be greater than zero")
let idsToAppend = ids.count..<(ids.count + k)
ids.append(contentsOf: idsToAppend)
sizes.append(contentsOf: Array(repeating: 1, count: k))
}
/// Find the root node for the specified node.
///
/// - Parameter _: An Int value representing the id of the node to find the root of.
/// **Must not be negative and less than the count of nodes of this instance**.
/// - Returns: An Int value representing the id of the root node for the specified
/// node id.
/// - Complexity: O(log *n*) where *n* is the count of instance's nodes.
/// - Note: Nodes are uniquevely identified by an Int value in range `0..<count`
public func find(_ id: Int) -> Int {
_checkID(id)
return _fastRootOf(id)
}
/// Connectes the specified nodes.
///
/// - Parameter _: An Int value representing the id of one of the nodes to
/// connect to the other one. **Must not be negative and less than the count of nodes of this instance**.
/// - Parameter _: An Int value representing the id of one of the nodes to
/// connect to the other one. **Must not be negative and less than the count of nodes of this instance**.
/// - Complexity: O(log *n*) where *n* is the count of nodes of the instance.
/// - Note: Nodes are uniquevely identified by an Int value in range `0..<count`
public mutating func union(_ lhs: Int, _ rhs: Int) {
_checkID(lhs)
_checkID(rhs)
_fastUnion(lhs, rhs)
}
/// Returns `true` if the two specified nodes are connected, otherwise `false`.
///
/// - Parameter _: An Int value representing the id of one of the nodes to
/// check if is connected to the other one. **Must not be negative and less than the count of nodes of this instance**.
/// - Parameter _: An Int value representing the id of one of the nodes to
/// check if is connected to the other one. **Must not be negative and less than the count of nodes of this instance**.
/// - Returns: `true` if the two nodes at the specified ids are connected,
/// otherwise `false`.
/// - Complexity: O(log *n*) where *n* is the count of nodes of the instance.
/// - Note: Nodes are uniquevely identified by an Int value in range `0..<count`
public func areConnected(_ lhs: Int, _ rhs: Int) -> Bool {
_checkID(lhs)
_checkID(rhs)
return _fastRootOf(lhs) == _fastRootOf(rhs)
}
}
// MARK: - Internal and Private interface
extension UnionFind {
@usableFromInline
internal mutating func _fastUnion(_ lhs: Int, _ rhs: Int) {
guard lhs != rhs else { return }
let lhsRoot = _fastCompactingRootOf(lhs)
let rhsRoot = _fastCompactingRootOf(rhs)
guard lhsRoot != rhsRoot else { return }
sizes.withUnsafeMutableBufferPointer { sizesBuff in
ids.withUnsafeMutableBufferPointer { idsBuff in
if sizesBuff[lhsRoot] < sizesBuff[rhsRoot] {
idsBuff[lhsRoot] = rhsRoot
sizesBuff[rhsRoot] += sizesBuff[lhsRoot]
} else {
idsBuff[rhsRoot] = lhsRoot
sizesBuff[lhsRoot] += sizesBuff[rhsRoot]
}
}
}
}
@usableFromInline
internal func _fastRootOf(_ id: Int) -> Int {
var i = id
ids.withUnsafeBufferPointer { buff in
while buff[i] != i {
i = buff[i]
}
}
return i
}
@inline(__always)
private mutating func _fastCompactingRootOf(_ id: Int) -> Int {
var i = id
ids.withUnsafeMutableBufferPointer { buff in
while buff[i] != i {
buff[i] = buff[buff[i]]
i = buff[i]
}
}
return i
}
@inline(__always)
private func _checkID(_ id: Int) {
precondition(ids.indices ~= id, "Id out of range")
}
}
<file_sep>//
// MonteCarloSimulation.swift
// UnionFind
//
// Created by <NAME> on 2020/11/13.
// Copyright © 2020 <NAME>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
/// A data structure for simulating percolation in an interconnected matrix of nodes –a.k.a. sites–.
public struct MonteCarloSimulation {
/// An Int value representing the number of sites per side in this instance's matrix.
public let sideCount: Int
/// An Int value representing the total number of sitess in this instance's matrix.
public let sitesCount: Int
/// An Int value representing the total number of sites open in this intance's matrix.
public var openSitesCount = 0
private(set) var elements: [Bool]
private(set) var unionFind: UnionFind
let virtualTop = 0
let virtualBottom: Int
/// Returns a new instance initialized to have the number of specified sites per side in its
/// matrix. Every site will be closed.
///
/// - Parameter _: An Int value representing the number of sites per side for the
/// matrix. **Must be greater than or equal to 5**. Defaults to `5`.
/// - Returns: A new instance with a matrix of sites of *k* by *k* size,
/// where *k* is equal to the specified `sideCount` parameter.
public init(_ sideCount: Int = 5) {
precondition(sideCount >= 5, "Must use a value greater than or equal to 5")
self.sideCount = sideCount
self.sitesCount = sideCount * sideCount
self.elements = Array(repeating: false, count: sideCount * sideCount)
self.unionFind = UnionFind((sideCount * sideCount + 2))
self.virtualBottom = self.unionFind.count - 1
for i in 1...sideCount {
unionFind.union(0, i)
}
for i in stride(from: virtualBottom - 1, through: virtualBottom - 1 - sideCount, by: -1) {
unionFind.union(virtualBottom, i)
}
}
}
extension MonteCarloSimulation {
/// A Double value representing the threshold of value of open sites by total number of sites
/// since where the system should be percolating.
public static let pThreshold: Double = /*0.592746*/ 0.596
/// A Boolean value, `true` when the system is percolating, otherwise `false`.
public var isPercolating: Bool {
unionFind._fastRootOf(virtualTop) == unionFind._fastRootOf(virtualBottom)
}
/// A Double value representing the number of sites opened divided by
/// the total count of sites.
public var p: Double {
Double(openSitesCount) / Double(sitesCount)
}
}
extension MonteCarloSimulation {
/// Opens closed a site, randomly picked.
public mutating func openRandomSite() {
guard sitesCount != openSitesCount else { return }
let site = _randomClosedSite()
_openSite(site)
}
private mutating func _openSite(_ site: Int) {
guard !elements[site] else { return }
elements[site] = true
openSitesCount += 1
for adj in _adjacenciesOpened(for: site) {
unionFind._fastUnion(site, adj)
}
}
private func _randomClosedSite() -> Int {
var site: Int!
repeat {
site = Int.random(in: 1..<sitesCount)
} while elements[site] == true
return site
}
private func _adjacenciesOpened(for site: Int) -> [Int] {
[site - sideCount, site + 1, site + sideCount, site - 1]
.filter { adj in
guard elements.startIndex..<elements.endIndex ~= adj else { return false }
return elements[adj]
}
}
}
| 9e2dad0cad2e4a309fd9ee0439350267432ef3a5 | [
"Swift",
"Markdown"
] | 4 | Swift | vale-cocoa/UnionFind | d424187bf2d4f966553df089a386ca20990dcaa9 | 04e223bf613e2aa573794e7b371481713e1060bb |
refs/heads/main | <repo_name>ofir3009/Directory-and-Images<file_sep>/CreatingDirectories.py
import os
import matplotlib.pyplot as plt
#import opencv
from PIL import Image
import numpy as np
import shutil
def CreateDirectory(path, name):
'''
Function gets the parameters:
path = the path of the directory we want to create.
name = the name of the directory we want to create.
Function creates a directory with the name and the path.
Returns the directory's address
'''
if (path==""): #User input in ENTER
path= r"C:\Users\PCP\Desktop" #path will be on desktop as default
path=os.path.join(path, name) #path is needed to have the name in it to create it
print("Directory will be created in the path: " + path)
try:
os.mkdir(path) #Calling the function that will create the directory
except OSError: #When there is already a directory with the same name.
print("Creation of the directory %s failed" % path) #print that there was an error in creating the directory
else:
print ("Succesfully created directory %s " % path) #print that the creation was successful
return path
def SaveFiles(Source_path,Which_One,Train_path,Test_path):
'''
Function gets the parameters:
Source_path = the path of a directory with jpg images in it
Which_One = input string that determines if the images go to test or train
If user inputted train: transfer 70% of the images
If user inputted test: transfer all of the images
'''
if(Which_One=="test"): #If the path leads to test directory
for file in os.listdir(Source_path): #A loop to move every file
shutil.move(os.path.join(Source_path, file), os.path.join(Test_path,file)) #moving file from source to directory
if(Which_One=="train"): #If the path leads to train directory
i=0.0 #setting a counter for number of files
for file in os.listdir(Source_path): #loop to count how many files are in the source directory
i=i+1 #increase count by 1
i =int(0.7*i) #Multiplying the counter by 0.7 so it we can take 70% of the files in the source
for file in os.listdir(Source_path): #a loop to move 70% of the files in the source directory
if i>0: #while loop to help stop the moving of the files at 70%
shutil.move(os.path.join(Source_path,file),os.path.join(Train_path,file)) #moving file from source to directory
i=i-1 #decrease count by 1 - essential for our while loop
def image_plot(path):
'''
function gets the parameters:
images = the test path or the train path
Function prints all of the images in plot
'''
li=os.listdir(path)
#image_array = [np.array(Image.open(filename)) for filename in li]
image_array = [np.array(Image.open(os.path.join(path,filename))) for filename in li]
f,axs=plt.subplots(len(image_array))
for i in range(len(image_array)):
axs[i].imshow(image_array[i])
plt.tight_layout()
plt.show()
#Input for main directory
TheDirectoryPath = input("Enter Directory Path, press enter to create the directory on desktop ") #Main directory path input
TheDirectoryName = input("Enter Directory Name ") #Main directory name input
TheDirectoryPath = CreateDirectory(TheDirectoryPath, TheDirectoryName) #Creating the Directory with the name 'Dina_Directory'
#Creating Train and Test directories
#Train
Train_Path=TheDirectoryPath # The Train directory path will be updated in its creation
Train_Path = CreateDirectory(Train_Path, "train")
#Test
Test_Path=TheDirectoryPath # The Test directory path will be upddated in its creation
Test_Path = CreateDirectory(Test_Path, "test")
#Saving files in test or train
Which_One = input("type 'test' for test directory, type 'train' for train directory ")
SaveFiles(input("Enter Source Directory Path: "), Which_One, Train_Path, Test_Path)
#Showing the images in plot
if(Which_One=="test"):
image_plot(Test_Path)
if(Which_One=="train"):
image_plot(Test_Path) | 770aff586fda6b42f948897909100f6719058679 | [
"Python"
] | 1 | Python | ofir3009/Directory-and-Images | 05a85447bec187d1790701105e11e61b549f70a5 | 62de5443a4a4562cde53fd6e774401833a17fd00 |
refs/heads/master | <file_sep>#!/bin/sh
#Author: <EMAIL>
#init kubernetes node server
h1() { printf "$(tput bold)%s...\n$(tput sgr0)" "$@"
}
h2() { printf "$(tput setaf 3)%s\n$(tput sgr0)" "$@"
}
success() { printf "$(tput setaf 2; tput bold)✔ %s \n$(tput sgr0)" "$@"
}
error() { printf "$(tput setaf 1; tput bold) %s \n$(tput sgr0)" "$@"
exit 0
}
ret() {
if [ $? -eq 0 ]; then
success $"Sucess"
else
printf '\n'$(tput setaf 1; tput setab 0; tput bold)' Error '$(tput sgr0)'\n'
exit 0
fi
}
printf '\n'$(tput setaf 1; tput setab 0; tput bold)'此脚本应用于系统安装之后的node节点部署'$(tput sgr0)'\n\n'
sleep 2
h1 $" System checking and setting proxy"
ip route del default
sleep 1
ip route add default via 192.168.1.224
ret
h2 $" check google network registry k8s.gcr.io"
curl -s --connect-timeout 3 -m 10 k8s.gcr.io > /dev/null
ret
h2 $" It is Centos7.x ?"
[[ "`cat /etc/redhat-release|sed -r 's/.* ([0-9]+)\..*/\1/'`" == "7" ]] && success $"OK!" || error $"Error please check system version"
h2 $" Firewalld and iptables stop "
echo "checking firewalld"
systemctl status firewalld > /dev/null
[[ $? -eq 0 ]] && error $"please stop firewalld" || success $"OK!"
echo -n "Do you want to continue [Y/N]?"
read answer
[[ "$answer" == "y" || "$answer" == "Y" ]] && h1 $"Starting install..." || error $"Exit"
h2 $" iptables setting ,Please insert then following /etc/sysconfig/iptables ,and systemctl restart iptables"
echo "-A INPUT -s 10.10.0.0/16 -j ACCEPT
-A FORWARD -s 10.0.0.0/8 -j ACCEPT"
h2 $" Change kubernetes repo"
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
EOF
h2 $" Init IPVS modules......"
setenforce 0
swapoff -a
cat <<EOF > /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sysctl --system > /dev/null
cat > /etc/sysconfig/modules/ipvs.modules <<EOF
#!/bin/bash
ipvs_modules="ip_vs ip_vs_lc ip_vs_wlc ip_vs_rr ip_vs_wrr ip_vs_lblc ip_vs_lblcr ip_vs_dh ip_vs_sh ip_vs_nq ip_vs_sed ip_vs_ftp nf_conntrack_ipv4"
for kernel_module in \${ipvs_modules}; do
/sbin/modinfo -F filename \${kernel_module} > /dev/null 2>&1
if [ $? -eq 0 ]; then
/sbin/modprobe \${kernel_module}
fi
done
EOF
chmod 755 /etc/sysconfig/modules/ipvs.modules && /bin/bash /etc/sysconfig/modules/ipvs.modules
ret
h2 $" Checking DNS configured"
dnssum=`cat /etc/resolv.conf |egrep -v "^#" |grep nameserver|wc -l`
if [[ $dnssum -gt 3 ]];then
dns=`cat /etc/resolv.conf |egrep -v "^#" |grep nameserver|awk 'NR <=3 {print $0}'`
echo "$dns" > /etc/resolv.conf
fi
ret
h2 $" Setting start server configured"
cat <<EOF >> /etc/rc.local
swapoff -a
EOF
chmod +x /etc/rc.local
chmod +x /etc/rc.d/rc.local
h2 $" install docker and change docker strong dir"
mkdir -p /data/docker
yum install -y -q docker > /dev/null
cat <<EOF > /usr/lib/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=http://docs.docker.com
After=network.target rhel-push-plugin.socket registries.service
Wants=docker-storage-setup.service
Requires=docker-cleanup.timer
[Service]
Type=notify
NotifyAccess=all
EnvironmentFile=-/run/containers/registries.conf
EnvironmentFile=-/etc/sysconfig/docker
EnvironmentFile=-/etc/sysconfig/docker-storage
EnvironmentFile=-/etc/sysconfig/docker-network
Environment=GOTRACEBACK=crash
Environment=DOCKER_HTTP_HOST_COMPAT=1
Environment=PATH=/usr/libexec/docker:/usr/bin:/usr/sbin
ExecStart=/usr/bin/dockerd-current \
--add-runtime docker-runc=/usr/libexec/docker/docker-runc-current \
--default-runtime=docker-runc \
--exec-opt native.cgroupdriver=cgroupfs \
--userland-proxy-path=/usr/libexec/docker/docker-proxy-current \
--init-path=/usr/libexec/docker/docker-init-current \
--seccomp-profile=/etc/docker/seccomp.json \
--graph=/data/docker \
\$OPTIONS \
\$DOCKER_STORAGE_OPTIONS \
\$DOCKER_NETWORK_OPTIONS \
\$ADD_REGISTRY \
\$BLOCK_REGISTRY \
\$INSECURE_REGISTRY \
\$REGISTRIES
ExecReload=/bin/kill -s HUP \$MAINPID
LimitNOFILE=1048576
LimitNPROC=1048576
LimitCORE=infinity
TimeoutStartSec=0
Restart=on-abnormal
KillMode=process
[Install]
WantedBy=multi-user.target
EOF
ret
h2 $" change docker log-driver=json-file"
sed -i 's/journald/json-file/g' /etc/sysconfig/docker
ret
h2 $" install kubelet、kubeadm、kubectl "
yum install -y -q kubelet-1.11.1 kubeadm-1.11.1 kubectl-1.11.1 kubernetes-cni-0.6.0> /dev/null 2>&1
ret
h2 $" install epel "
yum install -y epel-release > /dev/null
ret
h2 $" install nfs glusterfs client "
yum install -y glusterfs glusterfs-fuse nfs-utils --disablerepo=epel> /dev/null
ret
h2 $" start docker and kubelet"
sed -i 's/EXTRA_ARGS$/EXTRA_ARGS --runtime-cgroups=\/systemd\/system.slice --kubelet-cgroups=\/systemd\/system.slice/g' \
/etc/systemd/system/kubelet.service.d/10-kubeadm.conf
ret
systemctl daemon-reload
systemctl enable docker -q && systemctl start docker > /dev/null
ret
systemctl enable kubelet -q
/bin/bash /etc/sysconfig/modules/ipvs.modules
ret<file_sep>#!/bin/bash
# Copyright (c) 2008-2012 Aerospike, Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# 适用于:
# 1、linux kernel 2.6.32+
# 2、CentOS 6+
# 定义 CPU 掩码,通过掩码来绑定中断号到指定 CPU
# echo MASK > /proc/irq/${IRQ_NUM}/smp_affinity
IRQ_AFFINITY_FOR_CORE[0]=1
IRQ_AFFINITY_FOR_CORE[1]=2
IRQ_AFFINITY_FOR_CORE[2]=4
IRQ_AFFINITY_FOR_CORE[3]=8
IRQ_AFFINITY_FOR_CORE[4]=10
IRQ_AFFINITY_FOR_CORE[5]=20
IRQ_AFFINITY_FOR_CORE[6]=40
IRQ_AFFINITY_FOR_CORE[7]=80
IRQ_AFFINITY_FOR_CORE[8]=100
IRQ_AFFINITY_FOR_CORE[9]=200
IRQ_AFFINITY_FOR_CORE[10]=400
IRQ_AFFINITY_FOR_CORE[11]=800
IRQ_AFFINITY_FOR_CORE[12]=1000
IRQ_AFFINITY_FOR_CORE[13]=2000
IRQ_AFFINITY_FOR_CORE[14]=4000
IRQ_AFFINITY_FOR_CORE[15]=8000
IRQ_AFFINITY_FOR_CORE[16]=10000
IRQ_AFFINITY_FOR_CORE[17]=20000
IRQ_AFFINITY_FOR_CORE[18]=40000
IRQ_AFFINITY_FOR_CORE[19]=80000
IRQ_AFFINITY_FOR_CORE[20]=100000
IRQ_AFFINITY_FOR_CORE[21]=200000
IRQ_AFFINITY_FOR_CORE[22]=400000
IRQ_AFFINITY_FOR_CORE[23]=800000
function check_app_installed {
if [ -z "$1" ]; then
echo "Usage: $0 appname"
exit 1
fi
RES=$(which "$1" 2>&1);
MISS=$?
if [ $MISS -eq 1 ]; then return 0;
else return 1; fi
}
function check_required_apps {
check_app_installed numactl
OK=$?
if [ $OK -ne 1 ]; then
echo "Required application not found: (numactl)"
exit 1;
fi
}
function check_is_user_root {
RES=$(whoami)
if [ "$RES" != "root" ]; then
echo "ERROR: $0 must be run as user: root"
exit 1;
fi
}
function find_eths {
RES=$(/sbin/ip link show | grep "state UP")
# NETH : 正在使用的网卡总数
NETH=$(echo "${RES}" | wc -l)
I=0; for eth in $(echo "$RES" | cut -f 2 -d : ); do
ETH[$I]="$eth"; I=$[${I}+1];
done
}
# NOTE: if the last word in /proc/interrupt does not have a "-"
# then it is not an active nic-queue, rather a placeholder for the nic
function validate_eth_q {
echo $1 |rev | cut -f 1 -d \ | rev | grep \- |wc -l
}
# NUM_TOT_ETH_QUEUES : 所有网卡的队列总数
# NUM_QUEUES_PER_ETH[$I] : 每个网卡的队列总数
# IRQS_PER_ETH[$I] : 网络接口队列所对应的中断号
function count_eth_queues {
find_eths
NUM_TOT_ETH_QUEUES=0
I=0; while [ $I -lt $NETH ]; do
eth="${ETH[$I]}";
INTERRUPTS=$(grep "$eth" /proc/interrupts)
GOOD_INTERRUPTS=$(echo "${INTERRUPTS}" |while read intr; do
GOOD=$(validate_eth_q "$intr")
if [ "$GOOD" == "1" ]; then echo "$intr"; fi
done)
NUM_QUEUES_PER_ETH[$I]=$(echo "${GOOD_INTERRUPTS}" | wc -l)
NUM_TOT_ETH_QUEUES=$[${NUM_QUEUES_PER_ETH[$I]}+${NUM_TOT_ETH_QUEUES}];
IRQS_PER_ETH[$I]=$(echo "${GOOD_INTERRUPTS}" | cut -f 1 -d :)
#echo eth: $eth NUMQ: ${NUM_QUEUES_PER_ETH[$I]} IRQS: ${IRQS_PER_ETH[$I]}
I=$[${I}+1];
done
}
function get_num_cpu_sockets {
NCS=$(numactl --hardware |grep cpus: | wc -l)
}
function get_cpu_socket_cores {
get_num_cpu_sockets
# NUM_TOT_CPU_CORES : CPU 逻辑核总数
NUM_TOT_CPU_CORES=0
I=0; while [ $I -lt $NCS ]; do
SOCKET_CORES[$I]=$(numactl --hardware |grep "node $I cpus:" | cut -f 2 -d :)
NUM_CORE_PER_SOCKET[$I]=$(echo ${SOCKET_CORES[$I]} | wc -w)
NUM_TOT_CPU_CORES=$[${NUM_CORE_PER_SOCKET[$I]}+${NUM_TOT_CPU_CORES}];
I=$[${I}+1];
done
}
<file_sep># kubernetes 一些部署脚本
You need the following conditions.
- Centos7.X +
- Kubetnets 1.11 +
- Connection Google
Problem feedback : 90776500<EMAIL>
lvs/lvs_realserver_init.sh
Usage: sh lvs_realserver_init.sh start vip subnum
- sh lvs_realserver_init.sh start 172.16.31.10 0
- sh lvs_realserver_init.sh start 192.168.3.11 1
<file_sep>#!/bin/bash
#auther: syw
#优化lvs 机器
ethname=$1
#yum install -y epel* ipvsadm keepalived
#lvs hash table size
cat > /etc/modprobe.d/ip_vs.conf <<EOF
options ip_vs conn_tab_bits=20
EOF
##keepalived iptables
#-A INPUT -s 192.168.3.11/24 -p vrrp -j ACCEPT
#ring buffer
ethtool -G $ethname rx 4096
ethtool -G $ethname tx 4096
#queue size
sysctl -w net.core.netdev_max_backlog=262144
#
ethtool -K $ethname lro off
ethtool -K $ethname gro off
<file_sep>#!/bin/sh
#Author: shiyiwen
#init kubernetes master server
h1() { printf "$(tput bold)%s...\n$(tput sgr0)" "$@"
}
h2() { printf "$(tput setaf 3)%s\n$(tput sgr0)" "$@"
}
success() { printf "$(tput setaf 2; tput bold)✔ %s \n$(tput sgr0)" "$@"
}
error() { printf "$(tput setaf 1; tput bold) %s \n$(tput sgr0)" "$@"
exit 0
}
ret() {
if [ $? -eq 0 ]; then
success $"Sucess"
else
printf '\n'$(tput setaf 1; tput setab 0; tput bold)' Error '$(tput sgr0)'\n'
exit 0
fi
}
printf '\n'$(tput setaf 1; tput setab 0; tput bold)'此脚本应用于系统安装之后的master节点部署'$(tput sgr0)'\n\n'
sleep 2
h1 $" System checking "
h2 $" check google network registry k8s.gcr.io"
curl -s --connect-timeout 3 -m 10 k8s.gcr.io > /dev/null
ret
h2 $" It is Centos7.x ?"
[[ "`cat /etc/redhat-release|sed -r 's/.* ([0-9]+)\..*/\1/'`" == "7" ]] && success $"OK!" || error $"Error please check system version"
h2 $" Firewalld and iptables stop "
echo "checking firewalld"
systemctl status firewalld > /dev/null
[[ $? -eq 0 ]] && error $"please stop firewalld" || success $"OK!"
echo "checking iptables"
systemctl status iptables > /dev/null
[[ $? -eq 0 ]] && error $"please stop iptables" || success $"OK!"
echo -n "Do you want to continue [Y/N]?"
read answer
[[ "$answer" == "y" || "$answer" == "Y" ]] && h1 $"Starting install..." || error $"Exit"
h1 " Change kubernetes repo"
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
EOF
setenforce 0
swapoff -a
cat <<EOF > /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
vm.swappiness=0
EOF
sysctl --system > /dev/null
h1 $" install docker and change docker strong dir"
mkdir -p /data/docker
yum install -y docker > /dev/null
cat <<EOF > /usr/lib/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=http://docs.docker.com
After=network.target rhel-push-plugin.socket registries.service
Wants=docker-storage-setup.service
Requires=docker-cleanup.timer
[Service]
Type=notify
NotifyAccess=all
EnvironmentFile=-/run/containers/registries.conf
EnvironmentFile=-/etc/sysconfig/docker
EnvironmentFile=-/etc/sysconfig/docker-storage
EnvironmentFile=-/etc/sysconfig/docker-network
Environment=GOTRACEBACK=crash
Environment=DOCKER_HTTP_HOST_COMPAT=1
Environment=PATH=/usr/libexec/docker:/usr/bin:/usr/sbin
ExecStart=/usr/bin/dockerd-current \
--add-runtime docker-runc=/usr/libexec/docker/docker-runc-current \
--default-runtime=docker-runc \
--exec-opt native.cgroupdriver=cgroupfs \
--userland-proxy-path=/usr/libexec/docker/docker-proxy-current \
--init-path=/usr/libexec/docker/docker-init-current \
--seccomp-profile=/etc/docker/seccomp.json \
--graph=/data/docker \
\$OPTIONS \
\$DOCKER_STORAGE_OPTIONS \
\$DOCKER_NETWORK_OPTIONS \
\$ADD_REGISTRY \
\$BLOCK_REGISTRY \
\$INSECURE_REGISTRY \
\$REGISTRIES
ExecReload=/bin/kill -s HUP \$MAINPID
LimitNOFILE=1048576
LimitNPROC=1048576
LimitCORE=infinity
TimeoutStartSec=0
Restart=on-abnormal
KillMode=process
[Install]
WantedBy=multi-user.target
EOF
h1 $" loading ipvs kernel model"
modprobe ip_vs_rr
modprobe ip_vs_wrr
modprobe ip_vs_sh
modprobe nf_conntrack_ipv4
modprobe ip_vs
ret
h1 $" Seting start server configured"
cat <<EOF >> /etc/rc.local
swapoff -a
modprobe ip_vs_rr
modprobe ip_vs_wrr
modprobe ip_vs_sh
modprobe nf_conntrack_ipv4
modprobe ip_vs
EOF
chmod +x /etc/rc.local
chmod +x /etc/rc.d/rc.local
h1 $" install kubelet、kubeadm、kubectl "
yum install -y kubelet kubeadm kubectl > /dev/null
ret
h1 $" start docker and kubelet"
systemctl daemon-reload
systemctl enable docker && systemctl start docker && systemctl enable kubelet && systemctl restart kubelet
ret
success $"Master node initing Sucess"
<file_sep>#!/bin/bash
#
# Copyright (c) 2008-2012 Aerospike, Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# 此脚本摘自 Aerospike,用于均衡 CPU0 的网络中断到多个 CPU 上。
# 适用于:
# 1、linux kernel 2.6.32+
# 2、CentOS 6+
CURRENT_DIR=$(dirname $0)
SCRIPT_HOME=$(cd $CURRENT_DIR; pwd)
#echo $SCRIPT_HOME
. $SCRIPT_HOME/helper.sh
check_is_user_root
check_required_apps
count_eth_queues
get_cpu_socket_cores
# 正在使用的 CPU 插槽数
NCS=1 # jerry-rig NCS for non cpu-socket aware community edition
# NETH:正在使用的网卡总数
# NUM_TOT_ETH_QUEUES:网络接口队列总数
if [ $NETH -gt 1 -a $NUM_TOT_ETH_QUEUES -gt 1 ]; then
echo "Number of Ethernet interfaces detected: ($NETH)"
echo "Apply NIQ queue IRQ smp_affinity to ALL ethernet interfaces: [y/n]"
read ans
if [ "$ans" != "Y" -a "$ans" != "y" ]; then
echo "Skipping NIQ queue IRQ smp_affinity optimizations"
exit 0;
fi
fi
# CL_IRQS_PER_ETH[$I]、IRQS_PER_ETH[$I]:网络接口队列所对应的中断号
# CL_NUM_QUEUES_PER_ETH[$I]、NUM_QUEUES_PER_ETH[$I] : 每个网卡的队列总数
I=0; while [ $I -lt $NETH ]; do
CL_ETH[$I]=${ETH[$I]}
CL_NUM_QUEUES_PER_ETH[$I]=${NUM_QUEUES_PER_ETH[$I]}
CL_IRQS_PER_ETH[$I]=${IRQS_PER_ETH[$I]}
I=$[${I}+1];
done
# NUM_TOT_CPU_CORES : CPU 逻辑核总数
# CL_NUM_QUEUES_PER_ETH[$I] : 每个网卡的队列总数
# IRQ[$J] : 网络接口队列所对应的中断号
I=0; while [ $I -lt $NETH ]; do
J=0; for irq in ${CL_IRQS_PER_ETH[$I]}; do
IRQ[$J]=$irq J=$[${J}+1];
done
J=0; while [ $J -lt $NUM_TOT_CPU_CORES -a $J -lt ${CL_NUM_QUEUES_PER_ETH[$I]} ]; do
echo "Configuring core: $J; ETH: ${CL_ETH[$I]}; IRQ: ${IRQ[$J]}; AFFINITY: ${IRQ_AFFINITY_FOR_CORE[${J}]}"
# 核心代码只有这一句
echo ${IRQ_AFFINITY_FOR_CORE[${J}]} > /proc/irq/${IRQ[$J]}/smp_affinity
J=$[${J}+1];
done
I=$[${I}+1];
done
exit 0;
| 2404c4ea724be70ac617d57b7f5fd88aa0a1fa5e | [
"Markdown",
"Shell"
] | 6 | Shell | shiyiwenv/k8s_script | bde434d86fbb33c8ff238b0e2221d463e34b08cf | a1c6e1cb14fc57ab6f37c84b3e52e4a7a1372934 |
refs/heads/master | <repo_name>gayatribhore524/gayatri_guibank<file_sep>/src/com/main/view/deleteaccount.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.main.view;
import com.main.service.DeleteAccountService;
/**
*
* @author dell
*/
public class deleteaccount extends javax.swing.JFrame {
/**
* Creates new form deleteaccount
*/
public deleteaccount() {
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();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtaccno = new javax.swing.JTextField();
btnsubmit = new javax.swing.JButton();
btnclear = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("delete account");
jLabel1.setFont(new java.awt.Font("Tahoma", 3, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 51, 0));
jLabel1.setText("DELETE ACCOUNT DETAILS");
jLabel2.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
jLabel2.setText("account number");
btnsubmit.setFont(new java.awt.Font("Tahoma", 2, 18)); // NOI18N
btnsubmit.setText("submit");
btnsubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnsubmitActionPerformed(evt);
}
});
btnclear.setFont(new java.awt.Font("Tahoma", 2, 18)); // NOI18N
btnclear.setText("clear");
btnclear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnclearActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 779, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(73, 73, 73)
.addComponent(txtaccno, javax.swing.GroupLayout.PREFERRED_SIZE, 376, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(322, 322, 322)
.addComponent(btnsubmit)
.addGap(146, 146, 146)
.addComponent(btnclear)))
.addContainerGap(24, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(jLabel2))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(txtaccno, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(110, 110, 110)
.addComponent(btnsubmit))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(118, 118, 118)
.addComponent(btnclear)))
.addGap(0, 205, Short.MAX_VALUE))
);
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)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnsubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsubmitActionPerformed
// TODO add your handling code here:
int accno=Integer.parseInt(txtaccno.getText().trim());
DeleteAccountService.deleteacc(accno);
System.out.println("Name :" +accno);
StringBuffer sb=new StringBuffer();
sb.append("\n :").append(accno);
jLabel2.setText(sb.toString());
}//GEN-LAST:event_btnsubmitActionPerformed
private void btnclearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnclearActionPerformed
// TODO add your handling code here:
txtaccno.setText("");
}//GEN-LAST:event_btnclearActionPerformed
/**
* @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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(deleteaccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new deleteaccount().setVisible(true);
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnclear;
private javax.swing.JButton btnsubmit;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField txtaccno;
// End of variables declaration//GEN-END:variables
}
| e1cd3c768a03d7f26d866999cedc91d5dafe12dd | [
"Java"
] | 1 | Java | gayatribhore524/gayatri_guibank | c5b7643b3a10400a5f9f736c59934271f8d9f9a3 | f064c682f95fc840bcd5e12e5a7ff504a4454b97 |
refs/heads/master | <file_sep>/**************************************************************************************
* N.Kozak // Lviv'2020 // ACM // event-driven validator example by JavaScript(NodeJS) *
* file: acmhw28_1.js (renamed to index.js) *
***************************************************************************************/
const ATTEMPTS_COUNT = 5
var attemptsDownCount = ATTEMPTS_COUNT;
const GROUPS_DIGITS_COUNT = 5;
const GROUP_DIGITS_SIZE = 5;
const PRODUCT_KEY_PART1 = [
<KEY>,
0xD, 0xD, 0xD, 0xD, 0xD,
0x8, 0x8, 0x8, 0x8, 0x8,
0xB, 0xB, 0xB, 0xB, 0xB,
0xF, 0xF, 0xF, 0xF, 0xF
];
const PRODUCT_KEY_PART2 = [
0xE, 0xE, 0xE, 0xE, 0xE,
0xF, 0xF, 0xF, 0xF, 0xF,
0xB, 0xB, 0xB, 0xB, 0xB,
0xF, 0xF, 0xF, 0xF, 0xF,
0xA, 0xA, 0xA, 0xA, 0xA
];
const DIGITS_COUNT = GROUPS_DIGITS_COUNT * GROUP_DIGITS_SIZE;
var outOfEdgeIndex = 0;
var currIndex = 0;
var data = new Array(DIGITS_COUNT).fill(0); // var data = [];
function integerDiv(a, b){
return (a - a % b) / b;
}
function checkProductKey(productKey){
for(var index = 0; index < DIGITS_COUNT; ++index){
if(productKey[index] ^ PRODUCT_KEY_PART1[index] ^ PRODUCT_KEY_PART2[index]){
return false;
}
}
return true
}
function toDigitPosition(currIndex){
let positionAddon = integerDiv(currIndex, GROUP_DIGITS_SIZE);
positionAddon && positionAddon >= GROUPS_DIGITS_COUNT ? --positionAddon : 0;
process.stdout.cursorTo(currIndex + positionAddon);
}
function printProductKey(productKey, outOfEdgeIndex){
for(var index = 0; index < DIGITS_COUNT && index < outOfEdgeIndex; ++index){
process.stdout.write(productKey[index].toString(16) );
}
}
function printFormattedProductKey(productKey, outOfEdgeIndex){
for(var index = 0; index < DIGITS_COUNT && index < outOfEdgeIndex; ++index){
process.stdout.write(productKey[index].toString(16) );
if(!((index + 1) % GROUP_DIGITS_SIZE) && (index + 1) < DIGITS_COUNT){
process.stdout.write( '-' );
}
}
}
function inputHandler(ch, key) {
if(!attemptsDownCount){
return;
}
if ( key && key.name == 'return' ) {
if (checkProductKey(data) ) {
process.stdout.write("\nThe product key is correct\n\n");
printProductKey(data, outOfEdgeIndex)
process.stdout.write(' (COMPLETE)');
process.stdout.write('\nFor exit press Ctrl + C\n');
attemptsDownCount = 0;
}
else{
process.stdout.write("\nThe product key is not correct\n");
process.stdout.write("\nYou have " + --attemptsDownCount + " attempts to try");
if(attemptsDownCount){
process.stdout.write("\nPlease, enter the product key:\n");
printFormattedProductKey(data, outOfEdgeIndex);
toDigitPosition(currIndex);
}
else{
process.stdout.write("\nThe product key is not entered\n");
process.stdout.write("For exit press Ctrl + C\n");
}
}
}
if (key && key.name == 'backspace') {
if(currIndex){
--currIndex;
toDigitPosition(currIndex);
data[currIndex] = 0;
process.stdout.write( '0' );
toDigitPosition(currIndex);
}
}
else if (key && key.name == 'delete') {
toDigitPosition(currIndex);
data[currIndex] = 0;
process.stdout.write( '0' );
toDigitPosition(currIndex);
}
else if (key && key.name == 'left') {
if(currIndex){
toDigitPosition(--currIndex); // got to 1.5
}
}
else if (key && key.name == 'right') {
if(currIndex < outOfEdgeIndex){
toDigitPosition(++currIndex);
}
}
ch == ' ' || ch == '\t' ? ch = '0' : 0;
var hexDigitRegularExpression = /^[0-9A-Fa-f]\b/; // /[0-9A-Fa-f]/g
if (ch && hexDigitRegularExpression.test(ch) && currIndex < DIGITS_COUNT) {
data[currIndex] = ch.toUpperCase();
process.stdout.write( data[currIndex] );
if(outOfEdgeIndex <= currIndex){
outOfEdgeIndex = currIndex + 1;
}
if(currIndex + 1 < DIGITS_COUNT) {
++currIndex;
if (currIndex != DIGITS_COUNT && !(currIndex % 5)) {
process.stdout.write( '-' );
}
}
if(currIndex + 1 == DIGITS_COUNT){
toDigitPosition(currIndex);
}
}
}
console.clear();
var keypress = require('keypress');
keypress(process.stdin);
process.stdin.setRawMode(true); // without press enter
process.stdin.setEncoding( 'utf8' );
// Resume stdin in the parent process.
// Node application close all by itself if be an error or process.exit().
process.stdin.resume();
process.stdin.on( 'keypress', (ch, key) => {
if ( key && key.ctrl && key.name == 'c' ) { // ctrl-c ( return from program )
process.exit();
}
});
process.stdin.on( 'keypress', inputHandler);
console.clear();
if(attemptsDownCount){
process.stdout.write('Please, enter the product key:\n');
}
process.stdout.close; // state out fix
| 89643079377ea7991d6ca09051609bdb0c6411b5 | [
"JavaScript"
] | 1 | JavaScript | RomanLypenko/srcacmhw28_1 | ebc5b9df1f3afce3d3890d861f584b8c3b8e97cb | bc8d25dcf92d382bbc6f77ae84b9638b0b6e16f5 |
refs/heads/master | <repo_name>acejnar/wiasane<file_sep>/winsane/winsane_socket.h
/***************************************************************************
* _ ___ _____
* Project | | / (_)___ _/ ___/____ _____ ___
* | | /| / / / __ `/\__ \/ __ `/ __ \/ _ \
* | |/ |/ / / /_/ /___/ / /_/ / / / / __/
* |__/|__/_/\__,_//____/\__,_/_/ /_/\___/
*
* Copyright (C) 2012 - 2013, <NAME>, <<EMAIL>>
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this software distribution.
*
* You may opt to use, copy, modify, and distribute this software for any
* purpose with or without fee, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either expressed or implied.
*
***************************************************************************/
#ifndef WINSANE_SOCKET_H
#define WINSANE_SOCKET_H
#if _MSC_VER > 1000
#pragma once
#endif
#include <winsock2.h>
#include "sane.h"
class WINSANE_Socket {
public:
/* Constructer & Deconstructer */
WINSANE_Socket(_In_ SOCKET sock);
~WINSANE_Socket();
/* Internal API */
SOCKET GetSocket();
VOID SetConverting(_In_ BOOL converting);
BOOL IsConverting();
DWORD Flush();
VOID Clear();
int WritePlain(_In_reads_bytes_(buflen) CONST PBYTE buf, _In_ DWORD buflen);
int ReadPlain(_Out_writes_bytes_(buflen) PBYTE buf, _In_ DWORD buflen);
int Write(_In_reads_bytes_(buflen) CONST PBYTE buf, _In_ DWORD buflen);
int Read(_Out_writes_bytes_(buflen) PBYTE buf, _In_ DWORD buflen);
int WriteByte(_In_ SANE_Byte b);
int WriteWord(_In_ SANE_Word w);
int WriteChar(_In_ SANE_Char c);
int WriteString(_In_ SANE_String_Const s);
int WriteHandle(_In_ SANE_Handle h);
int WriteStatus(_In_ SANE_Status s);
SANE_Byte ReadByte();
SANE_Word ReadWord();
SANE_Char ReadChar();
SANE_String ReadString();
SANE_Handle ReadHandle();
SANE_Status ReadStatus();
protected:
int WriteSocket(_In_reads_bytes_(buflen) CONST PBYTE buf, _In_ DWORD buflen);
int ReadSocket(_Out_writes_bytes_(buflen) PBYTE buf, _In_ DWORD buflen);
private:
PBYTE ReallocBuffer(_In_opt_ PBYTE buf, _In_opt_ DWORD oldlen, _In_ DWORD newlen);
VOID Close();
SOCKET sock;
PBYTE buf;
DWORD buflen;
DWORD bufoff;
BOOL conv;
};
typedef WINSANE_Socket* PWINSANE_Socket;
#endif
<file_sep>/winsane/winsane_socket.cpp
/***************************************************************************
* _ ___ _____
* Project | | / (_)___ _/ ___/____ _____ ___
* | | /| / / / __ `/\__ \/ __ `/ __ \/ _ \
* | |/ |/ / / /_/ /___/ / /_/ / / / / __/
* |__/|__/_/\__,_//____/\__,_/_/ /_/\___/
*
* Copyright (C) 2012 - 2013, <NAME>, <<EMAIL>>
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this software distribution.
*
* You may opt to use, copy, modify, and distribute this software for any
* purpose with or without fee, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either expressed or implied.
*
***************************************************************************/
#include "winsane_socket.h"
#include "winsane_internal.h"
#include <stdlib.h>
#include <malloc.h>
#include <algorithm>
WINSANE_Socket::WINSANE_Socket(_In_ SOCKET sock)
{
this->sock = sock;
this->conv = FALSE;
this->buf = NULL;
this->buflen = 0;
this->bufoff = 0;
}
WINSANE_Socket::~WINSANE_Socket()
{
this->Clear();
this->Close();
}
SOCKET WINSANE_Socket::GetSocket()
{
return this->sock;
}
VOID WINSANE_Socket::SetConverting(_In_ BOOL converting)
{
this->conv = converting;
}
BOOL WINSANE_Socket::IsConverting()
{
return this->conv;
}
DWORD WINSANE_Socket::Flush()
{
DWORD result, offset, size;
for (offset = 0; offset < this->buflen; ) {
result = this->WriteSocket(this->buf + offset, this->buflen - offset);
if (result > 0) {
offset += result;
} else {
break;
}
}
if (offset < this->buflen) {
size = this->buflen - offset;
memmove(this->buf, this->buf + offset, size);
this->buf = this->ReallocBuffer(this->buf, this->buflen, size);
this->buflen = size;
this->bufoff = 0;
} else {
this->Clear();
}
return offset;
}
VOID WINSANE_Socket::Clear()
{
if (this->buf) {
if (this->buflen) {
memset(this->buf, 0, this->buflen);
this->buflen = 0;
}
free(this->buf);
this->buf = NULL;
}
this->bufoff = 0;
}
PBYTE WINSANE_Socket::ReallocBuffer(_In_opt_ PBYTE buf, _In_opt_ DWORD oldlen, _In_ DWORD newlen)
{
PBYTE newbuf;
newbuf = NULL;
if (buf && oldlen) {
if (newlen) {
newbuf = (PBYTE) realloc(buf, newlen);
} else {
free(buf);
}
} else if (newlen) {
newbuf = (PBYTE) malloc(newlen);
}
if (newbuf && newlen > oldlen) {
memset(newbuf + oldlen, 0, newlen - oldlen);
}
return newbuf;
}
VOID WINSANE_Socket::Close()
{
if (this->sock != INVALID_SOCKET) {
closesocket(this->sock);
this->sock = INVALID_SOCKET;
}
}
int WINSANE_Socket::WriteSocket(_In_reads_bytes_(buflen) CONST PBYTE buf, _In_ DWORD buflen)
{
return send(this->sock, (const char*) buf, buflen, 0);
}
int WINSANE_Socket::ReadSocket(_Out_writes_bytes_(buflen) PBYTE buf, _In_ DWORD buflen)
{
return recv(this->sock, (char*) buf, buflen, MSG_WAITALL);
}
int WINSANE_Socket::WritePlain(_In_reads_bytes_(buflen) CONST PBYTE buf, _In_ DWORD buflen)
{
DWORD space, size;
if (this->buf && this->buflen)
space = this->buflen - this->bufoff;
else
space = 0;
if (space < buflen) {
size = this->bufoff + buflen;
this->buf = this->ReallocBuffer(this->buf, this->buflen, size);
this->buflen = size;
}
memcpy(this->buf + this->bufoff, buf, buflen);
this->bufoff += buflen;
return buflen;
}
int WINSANE_Socket::ReadPlain(_Out_writes_bytes_(buflen) PBYTE buf, _In_ DWORD buflen)
{
return this->ReadSocket(buf, buflen);
}
int WINSANE_Socket::Write(_In_reads_bytes_(buflen) CONST PBYTE buf, _In_ DWORD buflen)
{
PBYTE buftmp;
int result;
buftmp = (PBYTE) malloc(buflen);
if (!buftmp)
return 0;
memset(buftmp, 0, buflen);
memcpy(buftmp, buf, buflen);
if (this->conv)
std::reverse(buftmp, buftmp + buflen);
result = this->WritePlain(buftmp, buflen);
memset(buftmp, 0, buflen);
free(buftmp);
return result;
}
int WINSANE_Socket::Read(_Out_writes_bytes_(buflen) PBYTE buf, _In_ DWORD buflen)
{
PBYTE buftmp;
int result;
buftmp = (PBYTE) malloc(buflen);
if (!buftmp)
return 0;
memset(buftmp, 0, buflen);
result = this->ReadPlain(buftmp, buflen);
if (this->conv)
std::reverse(buftmp, buftmp + buflen);
memcpy(buf, buftmp, buflen);
memset(buftmp, 0, buflen);
free(buftmp);
return result;
}
int WINSANE_Socket::WriteByte(_In_ SANE_Byte b)
{
return this->Write((PBYTE) &b, sizeof(SANE_Byte));
}
int WINSANE_Socket::WriteWord(_In_ SANE_Word w)
{
return this->Write((PBYTE) &w, sizeof(SANE_Word));
}
int WINSANE_Socket::WriteChar(_In_ SANE_Char c)
{
return this->Write((PBYTE) &c, sizeof(SANE_Char));
}
int WINSANE_Socket::WriteString(_In_ SANE_String_Const s)
{
SANE_Word length;
int written;
length = (SANE_Word) strlen(s) + 1;
written = this->WriteWord(length);
written += this->WritePlain((PBYTE) s, length);
return written;
}
int WINSANE_Socket::WriteHandle(_In_ SANE_Handle h)
{
return this->WriteWord((SANE_Word) h);
}
int WINSANE_Socket::WriteStatus(_In_ SANE_Status s)
{
return this->WriteWord((SANE_Word) s);
}
SANE_Byte WINSANE_Socket::ReadByte()
{
SANE_Byte b;
if (this->Read((PBYTE) &b, sizeof(SANE_Byte)) != sizeof(SANE_Byte))
b = 0;
return b;
}
SANE_Word WINSANE_Socket::ReadWord()
{
SANE_Word w;
if (this->Read((PBYTE) &w, sizeof(SANE_Word)) != sizeof(SANE_Word))
w = 0;
return w;
}
SANE_Char WINSANE_Socket::ReadChar()
{
SANE_Char c;
if (this->Read((PBYTE) &c, sizeof(SANE_Char)) != sizeof(SANE_Char))
c = 0;
return c;
}
SANE_String WINSANE_Socket::ReadString()
{
SANE_Word length;
SANE_String s;
length = this->ReadWord();
if (length > 0) {
s = new SANE_Char[length+1];
if (this->ReadPlain((PBYTE) s, length) == length) {
s[length] = '\0';
} else {
delete[] s;
s = NULL;
}
} else {
s = NULL;
}
return s;
}
SANE_Handle WINSANE_Socket::ReadHandle()
{
return (SANE_Handle) this->ReadWord();
}
SANE_Status WINSANE_Socket::ReadStatus()
{
return (SANE_Status) this->ReadWord();
}
| 9ddd537d660c750935082c0a43429bdf80f7debb | [
"C++"
] | 2 | C++ | acejnar/wiasane | 585d4a30ae7f45cc467e9c2928d419f696af0302 | 91877868dec82df376973191522cecd3ec83fdc3 |
refs/heads/master | <file_sep>using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using NUnit.Framework;
namespace NullabilityMetadataParser.Tests
{
public class NullabilityMetadataParserTests
{
[TestCaseSource(typeof(NullabilityData), nameof(NullabilityData.TestCases))]
public Nullability TestNullability(MemberInfo memberInfo)
=> new NullabilityMetadataParser().ParseNullability(memberInfo);
/*
public void Foo()
{
var x = new MixedType();
string s = x.NullableWithNotNull;
string s2 = x.NonNullableWithMaybeNull;
}*/
}
static class NullabilityData
{
public static IEnumerable TestCases
{
get
{
yield return new TestCaseData(typeof(MixedType).GetProperty(nameof(MixedType.NonNullable)))
.Returns(Nullability.NonNullable).SetName("NonNullableInMixedType");
yield return new TestCaseData(typeof(MixedType).GetProperty(nameof(MixedType.Nullable)))
.Returns(Nullability.Nullable).SetName("NullableInMixedType");
yield return new TestCaseData(typeof(MostlyNullableType).GetProperty(nameof(MostlyNullableType.NonNullable)))
.Returns(Nullability.NonNullable).SetName("NonNullableInMostlyNullableType");
yield return new TestCaseData(typeof(ObliviousType).GetProperty(nameof(ObliviousType.Oblivious)))
.Returns(Nullability.Oblivious).SetName("Oblivious");
// [MaybeNull]
yield return new TestCaseData(typeof(MixedType).GetProperty(nameof(MixedType.NonNullableWithMaybeNull)))
.Returns(Nullability.Nullable).SetName("NonNullableWithMaybeNull");
yield return new TestCaseData(typeof(GenericType<string>).GetProperty(nameof(GenericType<string>.MaybeNullable)))
.Returns(Nullability.Nullable).SetName("MaybeNullableProperty");
// [NotNull]
yield return new TestCaseData(typeof(MixedType).GetProperty(nameof(MixedType.NullableWithNotNull)))
.Returns(Nullability.NonNullable).SetName("GenericNullableWithNotNull");
yield return new TestCaseData(typeof(GenericType<string?>).GetProperty(nameof(GenericType<string?>.NotNullable)))
.Returns(Nullability.NonNullable).SetName("GenericNotNullProperty");
}
}
}
public class MixedType
{
public string NonNullable { get; set; } = "";
public string? Nullable { get; set; }
[MaybeNull] [DisplayName("WHAT")] public string NonNullableWithMaybeNull { get; set; } = "";
[NotNull] public string? NullableWithNotNull { get; set; }
}
public class MostlyNullableType
{
public string NonNullable { get; set; } = "";
public string? Nullable1 { get; set; }
public string? Nullable2 { get; set; }
public string? Nullable3 { get; set; }
public string? Nullable4 { get; set; }
public string? Nullable5 { get; set; }
public string? Nullable6 { get; set; }
public string? Nullable7 { get; set; }
public string? Nullable8 { get; set; }
public string? Nullable9 { get; set; }
}
public class GenericType<T>
{
[MaybeNull] public T MaybeNullable { get; set; } = default!;
[NotNull] public T NotNullable { get; set; } = default!;
}
#nullable disable
public class ObliviousType
{
public string Oblivious { get; set; }
}
#nullable enable
}
<file_sep>namespace NullabilityMetadataParser
{
public enum Nullability : byte
{
Oblivious = 0,
NonNullable = 1,
Nullable = 2
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
namespace NullabilityMetadataParser
{
public class NullabilityMetadataParser
{
// For the interpretation of nullability metadata, see
// https://github.com/dotnet/roslyn/blob/master/docs/features/nullable-metadata.md
Type? _nullableAttrType;
Type? _nullableContextAttrType;
FieldInfo? _nullableFlagsFieldInfo;
FieldInfo? _nullableContextFlagFieldInfo;
readonly Dictionary<Type, Nullability> _typeNullabilityContextCache = new Dictionary<Type, Nullability>();
readonly Dictionary<Module, Nullability> _moduleNullabilityContextCache = new Dictionary<Module, Nullability>();
const string NullableAttributeFullName = "System.Runtime.CompilerServices.NullableAttribute";
const string NullableContextAttributeFullName = "System.Runtime.CompilerServices.NullableContextAttribute";
public Nullability ParseNullability(MemberInfo memberInfo)
{
// First, check if we have [MaybeNull] or [NotNull]
foreach (var attr in Attribute.GetCustomAttributes(memberInfo, true))
{
switch (attr)
{
case MaybeNullAttribute _:
return Nullability.Nullable;
case NotNullAttribute _:
return Nullability.NonNullable;
}
}
// For C# 8.0 nullable types, the C# currently synthesizes a NullableAttribute that expresses nullability into assemblies
// it produces. If the model is spread across more than one assembly, there will be multiple versions of this attribute,
// so look for it by name, caching to avoid reflection on every check.
// Note that this may change - if https://github.com/dotnet/corefx/issues/36222 is done we can remove all of this.
// First look for NullableAttribute on the member itself
if (Attribute.GetCustomAttributes(memberInfo, true)
.FirstOrDefault(a => a.GetType().FullName == NullableAttributeFullName) is Attribute nullableAttr)
{
var attrType = nullableAttr.GetType();
if (attrType != _nullableAttrType)
{
_nullableFlagsFieldInfo = attrType.GetField("NullableFlags");
_nullableAttrType = attrType;
}
if (_nullableFlagsFieldInfo?.GetValue(nullableAttr) is byte[] flags)
return (Nullability)flags[0];
// TODO: If NullablePublicOnly is on, return oblivious immediately...?
}
// No attribute on the member, try to find a NullableContextAttribute on the declaring type
var type = memberInfo.DeclaringType;
if (type != null)
{
if (_typeNullabilityContextCache.TryGetValue(type, out var typeContext))
{
return typeContext;
}
if (TryGetNullabilityContextFlag(Attribute.GetCustomAttributes(type), out typeContext))
{
return _typeNullabilityContextCache[type] = typeContext;
}
}
// Not found at the type level, try at the module level
var module = memberInfo.Module;
if (!_moduleNullabilityContextCache.TryGetValue(module, out var moduleContext))
{
moduleContext = TryGetNullabilityContextFlag(Attribute.GetCustomAttributes(memberInfo.Module), out var x)
? x
: Nullability.Oblivious;
}
if (type != null)
{
_typeNullabilityContextCache[type] = moduleContext;
}
return moduleContext;
}
bool TryGetNullabilityContextFlag(Attribute[] attributes, out Nullability contextFlag)
{
if (attributes.FirstOrDefault(a => a.GetType().FullName == NullableContextAttributeFullName) is Attribute attr)
{
var attrType = attr.GetType();
if (attrType != _nullableContextAttrType)
{
_nullableContextFlagFieldInfo = attrType.GetField("Flag");
_nullableContextAttrType = attrType;
}
if (_nullableContextFlagFieldInfo?.GetValue(attr) is byte flag)
{
contextFlag = (Nullability)flag;
return true;
}
}
contextFlag = default;
return false;
}
/// <summary>
/// Resets all internal caches, preparing the parser for usage with new types or assemblies.
/// </summary>
public void Reset()
{
(_nullableAttrType, _nullableContextAttrType, _nullableFlagsFieldInfo, _nullableContextFlagFieldInfo) =
(null, null, null, null);
_typeNullabilityContextCache.Clear();
_moduleNullabilityContextCache.Clear();
}
}
}
| a7b2ecbcf098bfec5b2b3b1613660bdd4ba1e3ab | [
"C#"
] | 3 | C# | roji/NullabilityMetadataParser | 4b20b2f0d5288782fe1b483f91b7f33c8ed144ca | b5e96fed2aaa216f5218bbfd034f6416e62a2fed |
refs/heads/main | <repo_name>fabriziobonavita/python-rest-template<file_sep>/README.md
# Template for python rest services
This repository is serving as a template to base python rest webservices on
The scope of this service example covers:
* Fastapi uvicorn service
* SqlAlchemy setup
* Nox sessions for tests, linting, type checking, formatting and docs
* Dependency management with poetry
## Setup
Setup and run simply by
git clone <EMAIL>:fabriziobonavita/python-rest-template.git
poetry install
.venv/bin/uvicorn src.project_name.main:app --reload
Run all available nox sessions
nox
List all available nox sessions
nox --list
## TODOS
* Fix warnings
* Setup alembic properly
* Make example endpoint proper and semantically correct crud example
<file_sep>/src/project_name/example/schemas.py
from project_name.schemas import EntityBase
class Example(EntityBase):
test: str
class Config:
orm_mode = True
<file_sep>/src/project_name/example/models.py
from sqlalchemy import Column, String
from project_name.db import Base
class Example(Base):
__tablename__ = "examples"
test = Column(String)
<file_sep>/src/project_name/example/service.py
from sqlalchemy.orm import Session
from project_name.example.models import Example
def get_example(db: Session) -> Example:
return db.query(Example).first()
<file_sep>/pyproject.toml
[tool.poetry]
license = "MIT"
name = "project_name"
version = "0.1.0"
description = "A service that gets a webpage and extracts meta data"
readme = "README.md"
authors = ["<NAME> <<EMAIL>>"]
[tool.poetry.dependencies]
python = "^3.9"
fastapi = "^0.63.0"
uvicorn = "^0.13.3"
pydantic-sqlalchemy = "^0.0.8"
alembic = "^1.5.8"
[tool.poetry.dev-dependencies]
pytest = "^6.1.2"
coverage = {extras = ["toml"], version = "^5.3"}
pytest-cov = "^2.10.1"
pytest-mock = "^3.3.1"
black = "^20.8b1"
flake8 = "^3.8.4"
flake8-bandit = "^2.1.2"
flake8-black = "^0.2.1"
flake8-bugbear = "^20.1.4"
flake8-import-order = "^0.18.1"
safety = "^1.9.0"
mypy = "^0.790"
flake8-annotations = "^2.4.1"
typeguard = "^2.10.0"
flake8-docstrings = "^1.5.0"
darglint = "^1.5.6"
Sphinx = "^3.3.1"
xdoctest = "^0.15.0"
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
[tool.coverage.paths]
source = ["src", "*/site-packages"]
[tool.coverage.run]
branch = true
source = ["project_name"]
[tool.coverage.report]
show_missing = true
fail_under = 100
<file_sep>/src/project_name/__init__.py
"""This package is simply for education purpose."""
__version__ = "0.1.0"
<file_sep>/src/project_name/schemas.py
from datetime import datetime
from pydantic import BaseModel
class EntityBase(BaseModel):
id: int
created_at: datetime
modified_at: datetime
<file_sep>/src/project_name/main.py
import uvicorn
from fastapi import FastAPI
from project_name import db
from project_name.db import engine
from project_name.example.endpoints import router as url_router
from project_name.example.models import Example
app = FastAPI()
app.include_router(url_router)
Example
db.Base.metadata.create_all(bind=engine)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
<file_sep>/src/project_name/db.py
from datetime import datetime
from sqlalchemy import Column, DateTime, Integer, MetaData, Sequence, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
class EntityBase:
# id = Column(UUID, primary_key=True, unique=True, server_default=text("uuid_generate_v1()"))
id = Column(Integer, Sequence("id_seq"), primary_key=True)
created_at = Column(
"created_at", DateTime(timezone=True), default=datetime.now, nullable=False
)
modified_at = Column(
"modified_at", DateTime(timezone=True), default=datetime.now, nullable=False
)
Base = declarative_base(cls=EntityBase, metadata=MetaData())
<file_sep>/src/project_name/example/endpoints.py
from sqlalchemy.orm import Session
from fastapi import APIRouter, Depends
from project_name.db import get_db
from project_name.example import service
from project_name.example.schemas import Example
router = APIRouter()
@router.get("/examples/", response_model=Example)
async def example(db: Session = Depends(get_db)) -> Example:
return service.get_example(db)
<file_sep>/docs/index.rst
This is docs/index.rst,
documenting the {{project}} Python project. | e3b68b37ca57fca4d4d93b6e582fda6128ba02a4 | [
"Markdown",
"TOML",
"Python",
"reStructuredText"
] | 11 | Markdown | fabriziobonavita/python-rest-template | 5ebed6c3acb6980ba4aced2bd9c586ed6a39aef8 | eba01274f87143567bed981dcf980b96680fff9e |
refs/heads/master | <repo_name>l236/paxos<file_sep>/main.cpp
#include <queue>
#include <string>
#include <stdlib.h>/*用到了srand函数,所以要有这个头文件*/
#include <stdio.h>
#include <iostream>
#include <list>
#include <vector>
#include <sstream>
#include <time.h>
using namespace std;
class Promise {
private:
bool ack;
long ab;
string av;
public:
Promise(bool ack, long ab, string av) {
this->ack = ack;
this->ab = ab;
this->av = av;
}
bool isAck() {
return ack;
}
long getAb() {
return ab;
}
string getAv() {
return av;
}
};
class Acceptor {
private:
long pb;
long ab;
string av;
string name;
public:
Acceptor(string name) {
this->name = name;
this->pb = 0;
this->ab = 0;
this->av = "";
}
Promise* onPrepare(long b) {
//假设这个过程有50%的几率失败
if (rand() / double(RAND_MAX) - 0.5 > 0) {
std::cout << "accepter: " << this->name << " prepare no response" << std::endl;
return NULL;
}
if (b >= this->pb) {
pb = b;
Promise *response = new Promise(true, this->ab, this->av);
std::cout << "accepter: " << this->name << " prepare ok" << std::endl;
return response;
} else {
std::cout << "accepter: " << this->name << " prepare rejected" << std::endl;
return new Promise(false, 0, "");
}
}
bool onAccept(long b, string v) {
//假设这个过程有50%的几率失败
if (rand() / double(RAND_MAX) - 0.5 > 0) {
std::cout << "accepter: " << this->name << " accept no response" << std::endl;
return false;
}
if (b == this->pb) {
ab = b;
av = v;
std::cout << "accepter: " << this->name << " accept ok < " << b << " : " << v << " >" << std::endl;
return true;
} else {
std::cout << "accepter: " << this->name << " accept rejected" << std::endl;
return false;
}
}
long getPb() {
return pb;
}
long getAb() {
return ab;
}
string getAv() {
return av;
}
string getName() {
return name;
}
};
string PROPOSALS[3] = {"Proposal_1", "Proposal_2", "Proposal_3"};
#define ARRAY_LENGTH(array) (sizeof(array)/sizeof(array[0]))
static void proposerVote(vector<Acceptor *> &acceptors) {
int quorum = acceptors.size() / 2 + 1;
int maxb = 0;
int last_prepare_b = 0;
int b = last_prepare_b + 1;
int count_pre_ok = 0;
int count_accept_ok = 0;
int i = 0;
queue<int> queue;
string v;
while (true) {
v = PROPOSALS[rand() % ARRAY_LENGTH(PROPOSALS)];
//得到b的序号
if ((!queue.empty()) && rand() / double(RAND_MAX) - 0.5 > 0) {
//乱序的序号到达
b = queue.front();
queue.pop();
} else {
b = last_prepare_b + 1;
last_prepare_b ++;
if (rand() / double(RAND_MAX) - 0.7 > 0) {
//模拟乱序, 部分没有到达, 下一次随机到达
queue.push(b);
continue;
}
}
std::cout << std::endl;
std::cout << "**************************************************************" << std::endl;
std::cout << "Accepter pb ab av" << std::endl;
for (i = 0; i < acceptors.size(); i ++) {
std::cout << acceptors[i]->getName() << " "
<< acceptors[i]->getPb() << " "
<< acceptors[i]->getAb() << " "
<< acceptors[i]->getAv() << " "
<< std::endl;
}
std::cout << std::endl;
std::cout << "vote : start < vote_number : " << b << " >" << std::endl;
count_pre_ok = 0;
for (i = 0; i < acceptors.size(); i ++) {
Promise *promise = acceptors[i]->onPrepare(b);
if (promise && promise->isAck()) {
count_pre_ok ++;
if (promise->getAb() > maxb && promise->getAv() != "") {
maxb = promise->getAb();
//使用maxvalue的v
v = promise->getAv();
std::cout << "vote : v change < maxb : " << maxb << " v : " << v << " >" << std::endl;
}
}
}
if (count_pre_ok < quorum) {
std::cout<<"prepare : end <" << b << "> : vote < not accepted >" << std::endl;
continue;
}
count_accept_ok = 0;
for (i = 0; i < acceptors.size(); i ++) {
if (acceptors[i]->onAccept(b, v)) {
count_accept_ok ++;
}
}
if (count_accept_ok < quorum) {
std::cout<<"accept : end <" << b << ":" << v << "> : vote < not accepted >"<<std::endl;
continue;
}
break;
}
std::cout<<"proposal: <" << b << ":" << v << "> : vote < success >"<<std::endl;
}
int main() {
srand((unsigned)time(NULL));
vector<Acceptor *> acceptors;
acceptors.push_back(new Acceptor("A"));
acceptors.push_back(new Acceptor("B"));
acceptors.push_back(new Acceptor("C"));
acceptors.push_back(new Acceptor("D"));
acceptors.push_back(new Acceptor("E"));
proposerVote(acceptors);
return 0;
}
<file_sep>/README.md
# paxos
cpp
| a6802594d7d1670dd482c23cbfa2e9cdc098c1ef | [
"Markdown",
"C++"
] | 2 | C++ | l236/paxos | 5e7be13a6b8d1be7bc8cec35d5dcdeb5a17d8f9b | 690e7fdfafb1267b201c7482aa0a43d29fdb696a |
refs/heads/master | <file_sep>rootProject.name = 'MyTextInput'
include ':app'
<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput
} from 'react-native';
export default class MyTextInput extends Component {
render() {
return (
<Search/>
);
}
}
class Search extends Component{
render(){
return (
<View style={[styles.flex,styles.flexDirection]}>
<View style={[styles.flex,styles.searchInput,styles.topStatus]}>
<TextInput placeholder='于静' placeholderTextColor='gainsboro' underlineColorAndroid="white" ></TextInput>
</View >
<View style={[styles.searchBtn,styles.topStatus]}>
<Text style={styles.searchText}>搜索</Text>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
flex: {
flex: 1,
},
flexDirection:{
flexDirection:'row'
},
topStatus:{
marginTop:25,
},
searchInput:{
marginLeft:40,
height:40,
borderWidth:1,
borderRadius:5,
borderColor:'red'
},
searchBtn:{
borderWidth:1,
height:40,
backgroundColor:'aqua',
width:60,
marginRight:20,
justifyContent:'center',
alignItems:'center',
borderRadius:5,
marginLeft:-8
},
searchText:{
fontSize:15,
fontWeight:'bold',
}
});
AppRegistry.registerComponent('MyTextInput', () => MyTextInput);
| 1343c5ab95e68bfed5b670cf5f6df8764fae46ea | [
"JavaScript",
"Gradle"
] | 2 | Gradle | chenqianwen/MyTextInput | cce09d9ff79196c1156d0f6a1ed648d594553290 | 18f267ef5a1d53e280ac236b020137d9412b0d7d |
refs/heads/master | <file_sep>VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "debian-jessie-8.0-RC2"
config.vm.box_url = "http://static.gender-api.com/debian-8-jessie-rc2-x64-slim.box"
config.ssh.forward_agent = true
config.vm.define "dev" do |devconf|
devconf.vm.hostname = "box.dev"
devconf.vm.network "forwarded_port", guest: 3306 ,host: 3306
devconf.vm.network "forwarded_port", guest: 6379 ,host: 6379
devconf.vm.synced_folder "../", "/home/vagrant/src"
devconf.vm.synced_folder "./puppet", "/tmp/puppet"
devconf.vm.provision "shell", inline: "apt-get install -y git netselect-apt"
devconf.vm.provision "shell", inline: "cd /etc/apt; netselect-apt > /dev/null 2>&1"
devconf.vm.provision "shell", inline: "apt-get update; apt-get dist-upgrade -y"
devconf.vm.provision "shell", inline: "gem install librarian-puppet"
devconf.vm.provision "shell", inline: "cd /tmp/puppet && librarian-puppet install"
devconf.vm.provision :puppet do |p|
p.manifests_path = "./puppet"
p.manifest_file = "devbox.pp"
p.options = ["--hiera_config /tmp/puppet/manifests/hiera.yml", "--modulepath=/tmp/puppet/modules"]
end
end
end
| 1138f46f71e6abfbbc9ee2a796a44c3ad415ed16 | [
"Ruby"
] | 1 | Ruby | dominis/box.dev | 9882bd43919a8cb177f05a8fd67c6669f882625b | e05b4b94a890aaa3a1b9e4b7fc317561b21b5e0c |
refs/heads/master | <repo_name>ramonvictor/dumbx-js<file_sep>/README.md
# dumbx-js
[](https://badge.fury.io/js/dumbx)
A very dumb way of using some Redux principles.
# Usage
First of all, instantiate the store:
```js
const Dumbx = require('./dumbx');
const store = new Dumbx({
state: {
isPlaying: false,
music: ''
},
setters: {
pause(state) {
state.isPlaying = false;
},
play(state) {
state.isPlaying = true;
},
selectMusic(state, payload) {
state.music = payload.name;
}
}
});
```
Then, on the UI component, subscribe for store updates:
```js
// Component render example
const render = () => {
console.log(store.getState().isPlaying);
};
// Subscribe render returns unsubscribe function
const unsubscribe = store.subscribe(render);
```
Dispatch actions on user interactions (example):
```js
// Dispatching actions
const pauseBtn = document.querySelector('#pause');
const playBtn = document.querySelector('#play');
pauseBtn.addEventListener('click', () => {
store.dispatch('pause'); // store.getState().isPlaying => `false`
});
playBtn.addEventListener('click', () => {
store.dispatch('play'); // store.getState().isPlaying => `true`
});
document.addEventListener('DOMContentLoaded', () => {
store.dispatch('selectMusic', {
name: 'Awesome!'
}); // store.getState().music => 'Awesome!'
});
```
Optionally, unsubscribe whenever component is distroyed:
```js
const destroy = () => {
unsubscribe();
};
```
# Testing locally
Run the example file with:
```
$ node example.js
```
<file_sep>/dumbx.js
class Dumbx {
constructor(store = {}) {
this.subscribers = [];
this.state = store.state || {};
this.setters = store.setters || {};
}
getState() {
return this.state;
}
dispatch(action, payload) {
if (typeof action != 'string') {
throw new Error('Dumbx/dispatch: undefined/invalid action name!');
}
if (!this.setters.hasOwnProperty(action)) {
throw new Error('Dumbx/dispatch: undefined action!');
}
this.setters[action].call(null, this.state, payload);
this.subscribers.forEach((callback) => callback());
}
subscribe(callback) {
if (typeof callback != 'function') {
throw new Error('Dumbx/subscribe: invalid argument, expected function!');
}
this.subscribers.push(callback);
return () => {
let index = this.subscribers.indexOf(callback);
this.subscribers.splice(index, 1);
}
}
}
module.exports = Dumbx;
| 37eb30bcf6414bc340ec4ba00555d69e77d0089d | [
"Markdown",
"JavaScript"
] | 2 | Markdown | ramonvictor/dumbx-js | ce88ebe667996af1099ec45a3ec4cea393de675f | 49b63c1bcfc00b6ff22b6402590579407edd7981 |
refs/heads/master | <repo_name>wwhui/icare<file_sep>/src/main/java/com/sjtu/icare/modules/op/service/IWorkService.java
/**
* @Package com.sjtu.icare.modules.op.service
* @Description TODO
* @date Mar 23, 2015 7:47:52 PM
* @author <NAME>
* @version TODO
*/
package com.sjtu.icare.modules.op.service;
import java.util.List;
import com.sjtu.icare.modules.op.entity.AreaworkEntity;
import com.sjtu.icare.modules.op.entity.CareworkEntity;
public interface IWorkService {
/**
* @Title getCareworkEntities
* @Description TODO
* @param @param careworkEntity
* @param @return
* @return List<CareworkEntity>
* @throws
*/
List<CareworkEntity> getCareworkEntities(
CareworkEntity careworkEntity);
/**
* @Title insertCarework
* @Description TODO
* @param @param requestCareworkEntity
* @return void
* @throws
*/
void insertCarework(CareworkEntity careworkEntity);
/**
* @Title updateCarework
* @Description TODO
* @param @param requestCareworkEntity
* @return void
* @throws
*/
void updateCarework(CareworkEntity careworkEntity);
/**
* @Title deleteCarework
* @Description TODO
* @param @param requestCareworkEntity
* @return void
* @throws
*/
void deleteCarework(CareworkEntity careworkEntity);
/**
* @Title getAreaworkEntities
* @Description TODO
* @param @param requestAreaworkEntity
* @param @return
* @return List<AreaworkEntity>
* @throws
*/
List<AreaworkEntity> getAreaworkEntities(
AreaworkEntity areaworkEntity);
/**
* @Title insertAreawork
* @Description TODO
* @param @param areaworkEntity
* @return void
* @throws
*/
void insertAreawork(AreaworkEntity areaworkEntity);
/**
* @Title updateAreawork
* @Description TODO
* @param @param areaworkEntity
* @return void
* @throws
*/
void updateAreawork(AreaworkEntity areaworkEntity);
/**
* @Title deleteAreawork
* @Description TODO
* @param @param areaworkEntity
* @return void
* @throws
*/
void deleteAreawork(AreaworkEntity areaworkEntity);
}
<file_sep>/db/demo/demoDB.sql
DROP TABLE T_GERO;
DROP TABLE T_USER;
CREATE TABLE T_GERO
(
id int NOT NULL AUTO_INCREMENT COMMENT '编号',
name varchar(50) NOT NULL COMMENT '养老院名称',
cancel_date datetime,
PRIMARY KEY (id)
) COMMENT = '机构表';
CREATE TABLE T_USER
(
id int NOT NULL AUTO_INCREMENT COMMENT '编号',
username varchar(30) NOT NULL COMMENT '登录名',
password varchar(80) NOT NULL COMMENT '密码',
user_id int NOT NULL COMMENT '用户id',
user_type int NOT NULL COMMENT '用户类型',
register_date Date COMMENT '注册时间',
cancel_date Date COMMENT '注销时间',
PRIMARY KEY (id)
) COMMENT = '用户表';
<file_sep>/src/main/java/com/sjtu/icare/modules/op/service/IItemRecordService.java
/**
* @Package com.sjtu.icare.modules.op.service
* @Description TODO
* @date Mar 18, 2015 1:42:15 PM
* @author <NAME>
* @version TODO
*/
package com.sjtu.icare.modules.op.service;
import java.util.List;
import com.sjtu.icare.modules.op.entity.AreaworkRecordEntity;
import com.sjtu.icare.modules.op.entity.CareworkRecordEntity;
public interface IItemRecordService {
/**
* @Title getCareworkRecords
* @Description TODO
* @param @param careworkRecordEntity
* @param @param startDate
* @param @param endDate
* @param @return
* @return List<CareworkRecordEntity>
* @throws
*/
List<CareworkRecordEntity> getCareworkRecords(
CareworkRecordEntity careworkRecordEntity, String startDate,
String endDate);
/**
* @Title insertCareworkRecords
* @Description TODO
* @param @param postEntities
* @return void
* @throws
*/
void insertCareworkRecords(List<CareworkRecordEntity> careworkRecordEntities);
/**
* @Title getAreaworkRecords
* @Description TODO
* @param @param areaworkRecordEntity
* @param @param startDate
* @param @param endDate
* @param @return
* @return List<AreaworkRecordEntity>
* @throws
*/
List<AreaworkRecordEntity> getAreaworkRecords(
AreaworkRecordEntity areaworkRecordEntity, String startDate,
String endDate);
/**
* @Title insertAreaworkRecords
* @Description TODO
* @param @param areaworkRecordEntities
* @return void
* @throws
*/
void insertAreaworkRecords(List<AreaworkRecordEntity> areaworkRecordEntities);
}
<file_sep>/src/main/webapp/static/js/arrange.js
var arrange={
drawArrangeList:function(){
$(".inf").addClass('hide');
$("#arrangeshow").removeClass('hide');
/*$.ajax({
type: "get",
dataType: "json",
contentType: "application/json;charset=utf-8",
url:,
success: function (msg) {
},
error: function(e) {
alert(e);
}
});*/
},
}<file_sep>/src/main/java/com/sjtu/icare/modules/staff/webservice/GeroStaffScheduleRestController.java
/**
* @Package com.sjtu.icare.modules.staff.webservice
* @Description TODO
* @date Mar 13, 2015 9:34:36 PM
* @author <NAME>
* @version TODO
*/
package com.sjtu.icare.modules.staff.webservice;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.sjtu.icare.common.config.ErrorConstants;
import com.sjtu.icare.common.utils.BasicReturnedJson;
import com.sjtu.icare.common.utils.MapListUtils;
import com.sjtu.icare.common.utils.ParamUtils;
import com.sjtu.icare.common.utils.ParamValidator;
import com.sjtu.icare.common.web.rest.MediaTypes;
import com.sjtu.icare.common.web.rest.RestException;
import com.sjtu.icare.modules.staff.entity.StaffEntity;
import com.sjtu.icare.modules.staff.entity.StaffSchedulePlanEntity;
import com.sjtu.icare.modules.staff.service.impl.StaffDataService;
import com.sjtu.icare.modules.sys.entity.User;
@RestController
@RequestMapping({"${api.web}/gero/{gid}/schedule", "${api.service}/gero/{gid}/schedule"})
public class GeroStaffScheduleRestController {
private static Logger logger = Logger.getLogger(GeroStaffScheduleRestController.class);
@Autowired
StaffDataService staffDataService;
@RequestMapping(method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Object getStaffSchedulePlans(
@PathVariable("gid") int geroId,
@RequestParam(value="start_date", required=false) String startDate,
@RequestParam(value="end_date", required=false) String endDate,
@RequestParam(value="role", required=false) String role
) {
// 参数检查
if ((startDate != null && !ParamValidator.isDate(startDate)) || (endDate != null && !ParamValidator.isDate(endDate))) {
String otherMessage = "start_date 或 end_date 不符合日期格式:" +
"[start_date=" + startDate + "]" +
"[end_date=" + endDate + "]";
String message = ErrorConstants.format(ErrorConstants.GERO_STAFF_SCHEDULE_PLAN_GET_PARAM_INVALID, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.BAD_REQUEST, message);
}
try {
// 参数预处理
Map<String, String> tempMap = ParamUtils.getDateOfStartDateAndEndDate(startDate, endDate);
startDate = tempMap.get("startDate");
endDate = tempMap.get("endDate");
// 获取基础的 JSON返回
BasicReturnedJson basicReturnedJson = new BasicReturnedJson();
StaffSchedulePlanEntity queryStaffSchedulePlanEntity = new StaffSchedulePlanEntity();
queryStaffSchedulePlanEntity.setGeroId(geroId);
List<StaffSchedulePlanEntity> allStaffSchedulePlans = null;
if (role == null)
allStaffSchedulePlans = staffDataService.getAllStaffPlansByGeroId(queryStaffSchedulePlanEntity, startDate, endDate);
else
allStaffSchedulePlans = staffDataService.getAllStaffPlansByGeroId(queryStaffSchedulePlanEntity, startDate, endDate, role);
// 构造返回的 JSON
Map<Integer, Map<String, Object>> staffPlanMap = new HashMap<Integer, Map<String, Object>>();
for (StaffSchedulePlanEntity entity : allStaffSchedulePlans) {
Integer staffId = entity.getStaffId();
if (staffPlanMap.containsKey(staffId)) {
Map<String, Object> tempMap2 = (Map<String, Object>) staffPlanMap.get(staffId);
List<String> tempList = (List<String>) tempMap2.get("work_date");
tempList.add(entity.getWorkDate());
} else {
Map<String, Object> tempMap2 = new HashMap<String, Object>();
tempMap2.put("staff_id", staffId);
List<String> tempList = new ArrayList<String>();
tempList.add(entity.getWorkDate());
tempMap2.put("work_date", tempList);
StaffEntity queryStaffEntity = new StaffEntity();
queryStaffEntity.setId(staffId);
User user = staffDataService.getUserEntityOfStaff(queryStaffEntity);
if (user == null)
throw new Exception("内部错误,找不到 staff 对应的 user");
tempMap2.put("id", user.getId());
tempMap2.put("name", user.getName());
staffPlanMap.put(staffId, tempMap2);
}
}
for (Integer key : staffPlanMap.keySet())
basicReturnedJson.addEntity(staffPlanMap.get(key));
return basicReturnedJson.getMap();
} catch(Exception e) {
String otherMessage = "[" + e.getMessage() + "]";
String message = ErrorConstants.format(ErrorConstants.GERO_STAFF_SCHEDULE_PLAN_GET_SERVICE_FAILED, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, message);
}
}
@RequestMapping(method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Object putStaffSchedulePlans(
@PathVariable("gid") int geroId,
@RequestBody String inJson
) {
// 将参数转化成驼峰格式的 Map
List<Object> tempRquestList = ParamUtils.getListByJson(inJson, logger);
// 获取基础的 JSON
BasicReturnedJson basicReturnedJson = new BasicReturnedJson();
for (Object map : tempRquestList) {
Map<String, Object> tempRequestParamMap = (Map<String, Object>) map;
tempRequestParamMap.put("geroId", geroId);
Map<String, Object> requestParamMap = MapListUtils.convertMapToCamelStyle(tempRequestParamMap);
List<String> workDate;
List<String> noworkDate;
Integer staffId;
try {
workDate = (List<String>) requestParamMap.get("workDate");
noworkDate = (List<String>) requestParamMap.get("noworkDate");
staffId = (Integer) requestParamMap.get("staffId");
// 参数详细验证
// work_date, nowork_date 不能有交集
HashMap<String, Boolean> bin = new HashMap<String, Boolean>();
for (String date : workDate) {
if (!ParamValidator.isDate(date))
throw new Exception();
bin.put(date.trim(), true);
}
for (String date : noworkDate) {
if (!ParamValidator.isDate(date))
throw new Exception();
if (bin.get(date.trim()) != null)
throw new Exception();
}
} catch(Exception e) {
String otherMessage = "[work_date=" + requestParamMap.get("workDate") + "]" +
"[nowork_date=" + requestParamMap.get("noworkDate") + "]" +
"[staff_id=" + requestParamMap.get("staffId") + "]";
String message = ErrorConstants.format(ErrorConstants.GERO_STAFF_SCHEDULE_PLAN_PUT_PARAM_INVALID, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.BAD_REQUEST, message);
}
// 插入数据
try {
StaffSchedulePlanEntity postEntity = new StaffSchedulePlanEntity();
BeanUtils.populate(postEntity, requestParamMap);
postEntity.setGeroId(geroId);
if (!workDate.isEmpty())
staffDataService.insertStaffSchedulePlans(postEntity, workDate);
if (!noworkDate.isEmpty())
staffDataService.deleteStaffSchedulePlans(postEntity, noworkDate);
} catch(Exception e) {
String otherMessage = "[" + e.getMessage() + "]";
String message = ErrorConstants.format(ErrorConstants.GERO_STAFF_SCHEDULE_PLAN_PUT_SERVICE_FAILED, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, message);
}
}
return basicReturnedJson.getMap();
}
}
<file_sep>/src/main/java/com/sjtu/icare/modules/op/persistence/AreaworkDAO.java
package com.sjtu.icare.modules.op.persistence;
import java.util.List;
import java.util.Map;
import com.sjtu.icare.common.persistence.annotation.MyBatisDao;
import com.sjtu.icare.modules.op.entity.AreaworkEntity;
/**
* @Description 房间护工工作职责的 Mapper
* @author lzl
* @date 2015-03-13
*/
@MyBatisDao
public interface AreaworkDAO {
/**
* @Title getAreaworkEntities
* @Description TODO
* @param @param areaworkEntity
* @param @return
* @return List<AreaworkEntity>
* @throws
*/
List<AreaworkEntity> getAreaworkEntities(AreaworkEntity areaworkEntity);
/**
* @Title insertAreawork
* @Description TODO
* @param @param areaworkEntity
* @return void
* @throws
*/
void insertAreawork(AreaworkEntity areaworkEntity);
/**
* @Title updateAreawork
* @Description TODO
* @param @param areaworkEntity
* @return void
* @throws
*/
void updateAreawork(AreaworkEntity areaworkEntity);
/**
* @Title deleteAreawork
* @Description TODO
* @param @param areaworkEntity
* @return void
* @throws
*/
void deleteAreawork(AreaworkEntity areaworkEntity);
}<file_sep>/src/main/webapp/static/js/staff.js
var staff={
method:'',
sid:'',
drawStaffList:function(){
$("#staff-dialog-form").dialog("close");
$(".inf").addClass('hide');
$("#staffshow").removeClass('hide');
$('#staffpage').datagrid({
title:'员工信息列表',
iconCls:'icon-edit',//图标
fit:true,
nowrap: false,
loadMsg:"正在加载,请稍等...",
striped: true,
border: true,
collapsible:false,//是否可折叠的
url:'/gero/1/staff',
method:'get',
remoteSort:false,
singleSelect:true,//是否单选
pagination:true,//分页控件
rownumbers:true,//行号
pageNumber:1,
pagePosition:'bottom',
pageSize: 10,//每页显示的记录条数,默认为20
pageList: [10,20,30],//可以设置每页记录条数的列表
loadFilter:function(data){
var result={"total":0,"rows":0};
result.total=data.total;
result.rows=data.entities[0];
for (var i in result.rows) result.rows[i].gender=sex[result.rows[i].gender];
return result;
},
toolbar: [{
text: '添加',
iconCls: 'icon-add',
handler: function() {
staff.addStaffInfo();
}
}, '-',{
text: '删除',
iconCls: 'icon-remove',
handler: function(){
staff.delStaffInfo();
}
}]
});
var pager = $('#staffpage').datagrid('getPager'); // get the pager of datagrid
pager.pagination({
displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录',
/*onBeforeRefresh:function(){
$(this).pagination('loading');
alert('before refresh');
$(this).pagination('loaded');
}*/
});
},
drawStaffInfo: function(data){
staff.sid="/"+data.id;
$("#staff-dialog-form").dialog("open");
$("#staff-dialog-form").dialog("center");
$('#staff-Info-card-a input').attr('disabled','disabled');
$('#sname').attr('value',data.name);
$('#semail').attr('value',data.email);
$('#srole_list').attr('value',data.role_list);
$('#sbirthday').attr('value',data.birthday);
$('#sgender').attr('value',sex[data.gender]);
$('#shousehold_address').attr('value',data.household_address);
$('#snssf_id').attr('value',data.nssf_id);
$('#sarchive_id').attr('value',data.archive_id);
$('#sresidence_address').attr('value',data.residence_address);
$('#sidentity_no').attr('value',data.identity_no);
$('#sphone').attr('value',data.phone);
if(data.photo_url!==undefined) $('#staff-Info-card-b img').attr("src",data.photo_url).attr("width","178px").attr("height","220px");
else $('#staff-Info-card-b img').attr("src","/images/p_2.jpg").attr("width","178px").attr("height","220px");
},
addStaffInfo: function(){
staff.sid="";
staff.method='post';
$("#staff-dialog-form").dialog("open");
$("#staff-dialog-form").dialog("center");
$('#staff-Info-card-a input').attr('value'," ").removeAttr('disabled','');
$('#staff-Info-card-b img').attr("src","/images/p_2.jpg").attr("width","178px").attr("height","220px");
},
editStaffInfo: function(){
staff.method='put';
$("#staff-dialog-form").dialog("open");
$("#staff-dialog-form").dialog("center");
$('#staff-Info-card-a input').removeAttr('disabled','');
},
delStaffInfo: function(){
var stafft = $('#staffpage').datagrid('getSelected');
var infoUrl="gero/1/staff/" + stafft.id;
$.ajax({
url: infoUrl,
type: 'DELETE',
success:function(){
staff.drawstaffList();
}
})
},
onStaffDblClickRow:function(index){
var stafft = $('#staffpage').datagrid('getSelected');
infoUrl="gero/1/staff/" + stafft.id;
$.ajax({
type: "get",
dataType: "json",
contentType: "application/json;charset=utf-8",
url: infoUrl,
success: function (msg) {
var data=leftTop.dealdata(msg);
staff.drawStaffInfo(data);
},
error: function(e) {
alert(e);
}
});
},
buttonclk:function(){
var obj={
name:document.getElementById("sname").value,
gender:sexc[document.getElementById("sgender").value],
household_address:document.getElementById("shousehold_address").value,
identity_no:document.getElementById("sidentity_no").value,
nssf_id:document.getElementById("snssf_id").value,
archive_id:document.getElementById("sarchive_id").value,
email:document.getElementById("semail").value,
phone:document.getElementById("sphone").value,
role_list:document.getElementById("srole_list").value,
birthday:document.getElementById("sbirthday").value,
residence_address:document.getElementById("sresidence_address").value,
}
var infoUrl='/gero/1/staff'+staff.sid;
$.ajax({
url: infoUrl,
type: staff.method,
data:obj,
dataType: 'json',
timeout: 1000,
error: function(){alert('Error');},
success: function(result){staff.drawStaffList();}
});
}
}<file_sep>/src/main/java/com/sjtu/icare/modules/gero/webservice/GeroAreaItemRestController.java
/**
* @Package com.sjtu.icare.modules.gero.webservice
* @Description TODO
* @date Mar 18, 2015 11:15:53 AM
* @author <NAME>
* @version TODO
*/
package com.sjtu.icare.modules.gero.webservice;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.sjtu.icare.common.config.ErrorConstants;
import com.sjtu.icare.common.utils.BasicReturnedJson;
import com.sjtu.icare.common.utils.MapListUtils;
import com.sjtu.icare.common.utils.ParamUtils;
import com.sjtu.icare.common.web.rest.MediaTypes;
import com.sjtu.icare.common.web.rest.RestException;
import com.sjtu.icare.modules.op.entity.AreaItemEntity;
import com.sjtu.icare.modules.op.service.IItemService;
@RestController
@RequestMapping({"${api.web}/gero/{gid}/area_item", "${api.service}/gero/{gid}/area_item"})
public class GeroAreaItemRestController {
private static Logger logger = Logger.getLogger(GeroCareItemRestController.class);
@Autowired IItemService itemService;
@RequestMapping(method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Object getGeroAreaItems(
@PathVariable("gid") int geroId
) {
// 获取基础的 JSON返回
BasicReturnedJson basicReturnedJson = new BasicReturnedJson();
// 参数检查
// 参数预处理
try {
AreaItemEntity queryAreaItemEntity = new AreaItemEntity();
queryAreaItemEntity.setGeroId(geroId);
List<AreaItemEntity> areaItemEntities = itemService.getAreaItems(queryAreaItemEntity);
if (areaItemEntities != null) {
// 构造返回的 JSON
for (AreaItemEntity areaItemEntity : areaItemEntities) {
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("id", areaItemEntity.getId());
resultMap.put("gero_id", areaItemEntity.getGeroId());
resultMap.put("name", areaItemEntity.getName());
resultMap.put("icon", areaItemEntity.getIcon());
resultMap.put("period", areaItemEntity.getPeriod());
resultMap.put("frequency", areaItemEntity.getFrequency());
resultMap.put("notes", areaItemEntity.getNotes());
basicReturnedJson.addEntity(resultMap);
}
}
return basicReturnedJson.getMap();
} catch (Exception e) {
String otherMessage = "[" + e.getMessage() + "]";
String message = ErrorConstants.format(ErrorConstants.GERO_AREA_ITEMS_GET_SERVICE_FAILED, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, message);
}
}
@Transactional
@RequestMapping(method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Object postGeroAreaItem(
@PathVariable("gid") int geroId,
@RequestBody String inJson
) {
// 将参数转化成驼峰格式的 Map
Map<String, Object> tempRquestParamMap = ParamUtils.getMapByJson(inJson, logger);
tempRquestParamMap.put("geroId", geroId);
Map<String, Object> requestParamMap = MapListUtils.convertMapToCamelStyle(tempRquestParamMap);
String name;
String icon;
Integer period;
Integer frequency;
String notes;
try {
name = (String) requestParamMap.get("name");
icon = (String) requestParamMap.get("icon");
period = (Integer) requestParamMap.get("period");
frequency = (Integer) requestParamMap.get("frequency");
notes = (String) requestParamMap.get("notes");
if (name == null || icon == null || period == null || frequency == null || notes == null)
throw new Exception();
// 参数详细验证
// TODO
} catch(Exception e) {
String otherMessage = "[name=" + requestParamMap.get("name") + "]" +
"[icon=" + requestParamMap.get("icon") + "]" +
"[period=" + requestParamMap.get("period") + "]" +
"[frequency=" + requestParamMap.get("frequency") + "]" +
"[notes=" + requestParamMap.get("notes") + "]";
String message = ErrorConstants.format(ErrorConstants.GERO_AREA_ITEM_POST_PARAM_INVALID, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.BAD_REQUEST, message);
}
// 获取基础的 JSON
BasicReturnedJson basicReturnedJson = new BasicReturnedJson();
// 插入数据
try {
AreaItemEntity postEntity = new AreaItemEntity();
BeanUtils.populate(postEntity, requestParamMap);
itemService.insertAreaItem(postEntity);
} catch(Exception e) {
String otherMessage = "[" + e.getMessage() + "]";
String message = ErrorConstants.format(ErrorConstants.GERO_AREA_ITEM_POST_SERVICE_FAILED, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, message);
}
return basicReturnedJson.getMap();
}
@RequestMapping(value="/{aid}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Object getGeroAreaItem(
@PathVariable("gid") int geroId,
@PathVariable("aid") int itemId
) {
// 获取基础的 JSON返回
BasicReturnedJson basicReturnedJson = new BasicReturnedJson();
// 参数检查
// 参数预处理
try {
AreaItemEntity queryAreaItemEntity = new AreaItemEntity();
queryAreaItemEntity.setGeroId(geroId);
queryAreaItemEntity.setId(itemId);
AreaItemEntity areaItemEntity = itemService.getAreaItem(queryAreaItemEntity);
if (areaItemEntity != null) {
// 构造返回的 JSON
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("id", areaItemEntity.getId());
resultMap.put("gero_id", areaItemEntity.getGeroId());
resultMap.put("name", areaItemEntity.getName());
resultMap.put("icon", areaItemEntity.getIcon());
resultMap.put("period", areaItemEntity.getPeriod());
resultMap.put("frequency", areaItemEntity.getFrequency());
resultMap.put("notes", areaItemEntity.getNotes());
basicReturnedJson.addEntity(resultMap);
}
return basicReturnedJson.getMap();
} catch (Exception e) {
String otherMessage = "[" + e.getMessage() + "]";
String message = ErrorConstants.format(ErrorConstants.GERO_AREA_ITEM_GET_SERVICE_FAILED, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, message);
}
}
@Transactional
@RequestMapping(value="/{aid}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Object putGeroCareItem(
@PathVariable("gid") int geroId,
@PathVariable("aid") int itemId,
@RequestBody String inJson
) {
// 将参数转化成驼峰格式的 Map
Map<String, Object> tempRquestParamMap = ParamUtils.getMapByJson(inJson, logger);
tempRquestParamMap.put("geroId", geroId);
tempRquestParamMap.put("id", itemId);
Map<String, Object> requestParamMap = MapListUtils.convertMapToCamelStyle(tempRquestParamMap);
String name;
String icon;
Integer period;
Integer frequency;
String notes;
try {
name = (String) requestParamMap.get("name");
icon = (String) requestParamMap.get("icon");
period = (Integer) requestParamMap.get("period");
frequency = (Integer) requestParamMap.get("frequency");
notes = (String) requestParamMap.get("notes");
if (name == null || icon == null || period == null || frequency == null || notes == null)
throw new Exception();
// 参数详细验证
// TODO
} catch(Exception e) {
String otherMessage = "[name=" + requestParamMap.get("name") + "]" +
"[icon=" + requestParamMap.get("icon") + "]" +
"[period=" + requestParamMap.get("period") + "]" +
"[frequency=" + requestParamMap.get("frequency") + "]" +
"[notes=" + requestParamMap.get("notes") + "]";
String message = ErrorConstants.format(ErrorConstants.GERO_AREA_ITEM_PUT_PARAM_INVALID, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.BAD_REQUEST, message);
}
// 获取基础的 JSON
BasicReturnedJson basicReturnedJson = new BasicReturnedJson();
// 插入数据
try {
AreaItemEntity putEntity = new AreaItemEntity();
BeanUtils.populate(putEntity, requestParamMap);
itemService.updateAreaItem(putEntity);
} catch(Exception e) {
String otherMessage = "[" + e.getMessage() + "]";
String message = ErrorConstants.format(ErrorConstants.GERO_AREA_ITEM_PUT_SERVICE_FAILED, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, message);
}
return basicReturnedJson.getMap();
}
@Transactional
@RequestMapping(value = "/{aid}", method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
public Object deleteGeroAreaItem(
@PathVariable("gid") int geroId,
@PathVariable("aid") int itemId
) {
// 将参数转化成驼峰格式的 Map
Map<String, Object> tempRquestParamMap = new HashMap<String, Object>();
tempRquestParamMap.put("geroId", geroId);
tempRquestParamMap.put("id", itemId);
Map<String, Object> requestParamMap = MapListUtils.convertMapToCamelStyle(tempRquestParamMap);
// 获取基础的 JSON
BasicReturnedJson basicReturnedJson = new BasicReturnedJson();
// 删除数据
try {
AreaItemEntity inputEntity = new AreaItemEntity();
BeanUtils.populate(inputEntity, requestParamMap);
itemService.deleteAreaItem(inputEntity);
} catch(Exception e) {
String otherMessage = "[" + e.getMessage() + "]";
String message = ErrorConstants.format(ErrorConstants.GERO_AREA_ITEM_DELETE_SERVICE_FAILED, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, message);
}
return basicReturnedJson.getMap();
}
}
<file_sep>/src/main/java/com/sjtu/icare/modules/gero/entity/GeroElderExchangeEntity.java
/**
* @Package com.sjtu.icare.modules.gero.entity
* @Description TODO
* @date Mar 22, 2015 6:04:41 PM
* @author <NAME>
* @version TODO
*/
package com.sjtu.icare.modules.gero.entity;
import java.io.Serializable;
import com.sjtu.icare.common.persistence.DataEntity;
public class GeroElderExchangeEntity extends DataEntity<GeroElderExchangeEntity> implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String participants;
private String mediators;
private String description;
private String result;
private Integer recorder;
private String time;
private Integer geroId;
/**
* @return the id
*/
public int getId() {
return super.getId();
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the participants
*/
public String getParticipants() {
return participants;
}
/**
* @param participants the participants to set
*/
public void setParticipants(String participants) {
this.participants = participants;
}
/**
* @return the mediators
*/
public String getMediators() {
return mediators;
}
/**
* @param mediators the mediators to set
*/
public void setMediators(String mediators) {
this.mediators = mediators;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the result
*/
public String getResult() {
return result;
}
/**
* @param result the result to set
*/
public void setResult(String result) {
this.result = result;
}
/**
* @return the recorder
*/
public Integer getRecorder() {
return recorder;
}
/**
* @param recorder the recorder to set
*/
public void setRecorder(Integer recorder) {
this.recorder = recorder;
}
/**
* @return the time
*/
public String getTime() {
return time;
}
/**
* @param time the time to set
*/
public void setTime(String time) {
this.time = time;
}
/**
* @return the geroId
*/
public Integer getGeroId() {
return geroId;
}
/**
* @param geroId the geroId to set
*/
public void setGeroId(Integer geroId) {
this.geroId = geroId;
}
/**
* @return the serialversionuid
*/
public static long getSerialversionuid() {
return serialVersionUID;
}
/* (non-Javadoc)
* @see com.sjtu.icare.common.persistence.BaseEntity#preDelete()
*/
@Override
public void preDelete() {
// TODO Auto-generated method stub
}
}
<file_sep>/src/main/webapp/static/js/elder.js
var elder={
method:'',
eid:'',
drawElderList:function(){
$("#elder-dialog-form").dialog("close");
$(".inf").addClass('hide');
$("#eldershow").removeClass('hide');
$('#elderpage').datagrid({
title:'老人信息列表',
iconCls:'icon-edit',//图标
height:700,
nowrap: true,
loadMsg:"正在加载,请稍等...",
striped: true,
border: true,
collapsible:false,//是否可折叠的
fit: true,//自动大小
pageNumber:1,
url:'/gero/1/elder',
method:'get',
remoteSort:false,
singleSelect:true,//是否单选
pagination:true,//分页控件
rownumbers:true,//行号
pagePosition:'bottom',
pageSize: 10,//每页显示的记录条数,默认为20
pageList: [10,20,30],//可以设置每页记录条数的列表
loadFilter:function(data){
var result={"total":0,"rows":0};
result.total=data.total;
result.rows=data.entities[0];
for (var i in result.rows) result.rows[i].gender=sex[result.rows[i].gender];
return result;
},
toolbar: [{ text: '添加', iconCls: 'icon-add',
handler: function() {
elder.addElderInfo();
}
}, '-',{ text: '删除', iconCls: 'icon-remove',
handler: function(){
elder.delElderInfo();
}
}]
});
var pager = $('#elderpage').datagrid('getPager'); // get the pager of datagrid
pager.pagination({
displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录',
});
},
drawElderInfo: function(data){
elder.eid="/"+data.id;
$("#elder-dialog-form").dialog("open");
$("#elder-dialog-form").dialog("center");
$('#elder-Info-card-a input').attr('disabled','disabled');
$('#ename').attr('value',data.name);
$('#ebirthday').attr('value',data.birthday);
$('#egender').attr('value',sex[data.gender]);
$('#eaddress').attr('value',data.address);
$('#enative_place').attr('value',data.native_place);
$('#earea_id').attr('value',data.area_id);
$('#ecare_level').attr('value',data.care_level);
$('#enssf_id').attr('value',data.nssf_id);
$('#earchive_id').attr('value',data.archive_id);
$('#enationality').attr('value',data.nationality);
$('#eeducation').attr('value',data.education);
$('#eresidence').attr('value',data.residence);
$('#epolitical_status').attr('value',data.political_status);
$('#eidentity_no').attr('value',data.identity_no);
$('#ephone').attr('value',data.phone);
if(data.photo_url!==undefined) $('#elder-Info-card-b img').attr("src",data.photo_url).attr("width","178px").attr("height","220px");
else $('#elder-Info-card-b img').attr("src","/images/p_2.jpg").attr("width","178px").attr("height","220px");
},
addElderInfo: function(){
elder.eid="";
elder.method='post';
$("#elder-dialog-form").dialog("open");
$("#elder-dialog-form").dialog("center");
$('#elder-Info-card-a input').attr('value'," ").removeAttr('disabled','');
$('#elder-Info-card-b img').attr("src","/images/p_2.jpg").attr("width","178px").attr("height","220px");
},
editElderInfo: function(){
elder.method='put';
$("#elder-dialog-form").dialog("open");
$("#elder-dialog-form").dialog("center");
$('#elder-Info-card-a input').removeAttr('disabled','');
},
delElderInfo: function(){
var eldert = $('#elderpage').datagrid('getSelected');
infoUrl="gero/1/elder/" + eldert.id;
$.ajax({
url: infoUrl,
type: 'DELETE',
success:function(){
elder.drawElderList();
}
})
},
onElderDblClickRow:function(index){
var eldert = $('#elderpage').datagrid('getSelected');
infoUrl="gero/1/elder/" + eldert.id;
$.ajax({
type: "get",
dataType: "json",
contentType: "application/json;charset=utf-8",
url: infoUrl,
success: function (msg) {
var data=leftTop.dealdata(msg);
elder.drawElderInfo(data);
},
error: function(e) {
alert(e);
}
});
},
buttonclk:function(){
var obj={
name:document.getElementById("ename").value,
gender:sexc[document.getElementById("egender").value],
address:document.getElementById("eaddress").value,
identity_no:document.getElementById("eidentity_no").value,
nssf_id:document.getElementById("enssf_id").value,
archive_id:document.getElementById("earchive_id").value,
area_id:document.getElementById("earea_id").value,
care_level:document.getElementById("ecare_level").value,
nationality:document.getElementById("enationality").value,
native_place:document.getElementById("enative_place").value,
birthday:document.getElementById("ebirthday").value,
political_status:document.getElementById("epolitical_status").value,
education:document.getElementById("eeducation").value,
residence:document.getElementById("eresidence").value,
}
var infoUrl='/gero/1/elder'+elder.eid;
$.ajax({
url: infoUrl,
type: elder.method,
data:obj,
dataType: 'json',
timeout: 1000,
error: function(){alert('Error');},
success: function(result){elder.drawElderList();}
});
}
}
/*
function doSearch(){
$('#elderpage').datagrid('load',{
name: $('#elder_name').val(),
bed_id: $('#elder_bedid').val(),
care_level: $('#elder_care_level').val(),
});
}
function onthClick(e,field){
$('#elderpage').datagrid({
sortName:field,
sortOrder:"asc"
});
}*/<file_sep>/src/main/java/com/sjtu/icare/modules/op/persistence/ElderAudioRecordDAO.java
package com.sjtu.icare.modules.op.persistence;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.sjtu.icare.common.persistence.annotation.MyBatisDao;
import com.sjtu.icare.modules.op.entity.ElderAudioRecordEntity;
/**
* @Description 老人状况录音记录的 Mapper
* @author lzl
* @date 2015-03-13
*/
@MyBatisDao
public interface ElderAudioRecordDAO {
ElderAudioRecordEntity getElderAudioRecordEntityById(Map<String, Object> ElderAudioRecordEntity);
List<ElderAudioRecordEntity> getElderAudioRecordEntitiesByRecorderidentityRecorderid(@Param("recorderIdentity") int recorderIdentity, @Param("recorderId") int recorderId);
List<ElderAudioRecordEntity> getElderAudioRecordEntitiesByElderid(Map<String, Object> ElderAudioRecordEntity);
}<file_sep>/src/main/java/com/sjtu/icare/modules/staff/webservice/DutyCarerRestContorller.java
/**
* @Package com.sjtu.icare.modules.staff.webservice
* @Description TODO
* @date Mar 15, 2015 4:06:42 PM
* @author <NAME>
* @version TODO
*/
package com.sjtu.icare.modules.staff.webservice;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.sjtu.icare.common.config.ErrorConstants;
import com.sjtu.icare.common.utils.BasicReturnedJson;
import com.sjtu.icare.common.utils.DateUtils;
import com.sjtu.icare.common.utils.ParamUtils;
import com.sjtu.icare.common.utils.ParamValidator;
import com.sjtu.icare.common.web.rest.MediaTypes;
import com.sjtu.icare.common.web.rest.RestException;
import com.sjtu.icare.modules.elder.entity.ElderEntity;
import com.sjtu.icare.modules.gero.entity.GeroAreaEntity;
import com.sjtu.icare.modules.staff.entity.StaffEntity;
import com.sjtu.icare.modules.staff.service.IDutyCarerService;
import com.sjtu.icare.modules.staff.service.IStaffDataService;
import com.sjtu.icare.modules.sys.entity.User;
@RestController
@RequestMapping({"${api.web}", "${api.service}"})
public class DutyCarerRestContorller {
private static Logger logger = Logger.getLogger(DutyCarerRestContorller.class);
@Autowired
IDutyCarerService dutyCarerService;
@Autowired
IStaffDataService staffDataService;
@RequestMapping(value="/elder/{eid}/duty_carer", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Object getElderDutyCarer(
@PathVariable("eid") int elderId,
@RequestParam(value="date", required=false) String date
) {
// 参数检查
if (date != null && !ParamValidator.isDate(date)) {
String otherMessage = "date 不符合日期格式:" +
"[date=" + date + "]";
String message = ErrorConstants.format(ErrorConstants.DUTY_CARER_ELDER_GET_PARAM_INVALID, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.BAD_REQUEST, message);
}
try {
// 参数预处理
if (date == null) {
Date today = new Date();
date = DateUtils.formatDate(DateUtils.getDateStart(today));
}
if (date == null) {
Date thatDay = ParamUtils.convertStringToDate(date);
date = DateUtils.formatDate(DateUtils.getDateEnd(thatDay));
}
// 获取基础的 JSON返回
BasicReturnedJson basicReturnedJson = new BasicReturnedJson();
ElderEntity queryElderEntity = new ElderEntity();
queryElderEntity.setId(elderId);
List<StaffEntity> dutyCarers = dutyCarerService.getDutyCarerByElderIdAndDate(queryElderEntity, date);
// 构造返回的 JSON
for (StaffEntity staffEntity : dutyCarers) {
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("id", staffEntity.getId());
User user = staffDataService.getUserEntityOfStaff(staffEntity);
resultMap.put("gero_id", user.getGeroId());
resultMap.put("name", user.getName());
resultMap.put("phone", user.getPhoneNo());
resultMap.put("gender", user.getGender());
resultMap.put("photo_url", user.getPhotoUrl());
resultMap.put("work_date", date);
basicReturnedJson.addEntity(resultMap);
}
return basicReturnedJson.getMap();
} catch(Exception e) {
e.printStackTrace();
String otherMessage = "[" + e.getMessage() + "]";
String message = ErrorConstants.format(ErrorConstants.DUTY_CARER_ELDER_GET_SERVICE_FAILED, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, message);
}
}
@RequestMapping(value="/area/{aid}/duty_carer", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Object getAreaDutyCarer(
@PathVariable("aid") int areaId,
@RequestParam(value="date", required=false) String date
) {
// 参数检查
if (date != null && !ParamValidator.isDate(date)) {
String otherMessage = "date 不符合日期格式:" +
"[date=" + date + "]";
String message = ErrorConstants.format(ErrorConstants.DUTY_CARER_AREA_GET_PARAM_INVALID, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.BAD_REQUEST, message);
}
try {
// 参数预处理
if (date == null) {
Date today = new Date();
date = DateUtils.formatDate(DateUtils.getDateStart(today));
}
if (date == null) {
Date thatDay = ParamUtils.convertStringToDate(date);
date = DateUtils.formatDate(DateUtils.getDateEnd(thatDay));
}
// 获取基础的 JSON返回
BasicReturnedJson basicReturnedJson = new BasicReturnedJson();
GeroAreaEntity queryGeroAreaEntity = new GeroAreaEntity();
queryGeroAreaEntity.setId(areaId);
List<StaffEntity> dutyCarers = dutyCarerService.getDutyCarerByAreaIdAndDate(queryGeroAreaEntity, date);
// 构造返回的 JSON
for (StaffEntity staffEntity : dutyCarers) {
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("id", staffEntity.getId());
User user = staffDataService.getUserEntityOfStaff(staffEntity);
resultMap.put("gero_id", user.getGeroId());
resultMap.put("name", user.getName());
resultMap.put("phone", user.getPhoneNo());
resultMap.put("gender", user.getGender());
resultMap.put("photo_url", user.getPhotoUrl());
resultMap.put("work_date", date);
basicReturnedJson.addEntity(resultMap);
}
return basicReturnedJson.getMap();
} catch(Exception e) {
e.printStackTrace();
String otherMessage = "[" + e.getMessage() + "]";
String message = ErrorConstants.format(ErrorConstants.DUTY_CARER_ELDER_GET_SERVICE_FAILED, otherMessage);
logger.error(message);
throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, message);
}
}
}
<file_sep>/src/main/java/com/sjtu/icare/modules/op/persistence/AreaworkRecordDAO.java
package com.sjtu.icare.modules.op.persistence;
import java.util.List;
import java.util.Map;
import com.sjtu.icare.common.persistence.annotation.MyBatisDao;
import com.sjtu.icare.modules.op.entity.AreaworkRecordEntity;;
/**
* @Description 区域护理项目记录的 Mapper
* @author lzl
* @date 2015-03-12
*/
@MyBatisDao
public interface AreaworkRecordDAO {
/**
* @Title getAreaworkRecords
* @Description TODO
* @param @param paramMap
* @param @return
* @return List<AreaworkRecordEntity>
* @throws
*/
List<AreaworkRecordEntity> getAreaworkRecords(Map<String, Object> paramMap);
/**
* @Title insertAreaworkRecords
* @Description TODO
* @param @param paramList
* @return void
* @throws
*/
void insertAreaworkRecords(List<Map<String, Object>> paramList);
}<file_sep>/src/main/java/com/sjtu/icare/modules/elder/entity/ElderItemEntity.java
/**
* @Package com.sjtu.icare.modules.elder.entity
* @Description TODO
* @date Mar 20, 2015 3:43:19 PM
* @author <NAME>
* @version TODO
*/
package com.sjtu.icare.modules.elder.entity;
import java.io.Serializable;
import com.sjtu.icare.common.persistence.DataEntity;
import com.sjtu.icare.modules.sys.entity.User;
public class ElderItemEntity extends DataEntity<ElderItemEntity> implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id;
private Integer elderId;
private Integer careItemId;
private String careItemName;
private String icon;
private Integer level; //护理等级
private Integer period; //周期(几天为一轮)
private String startTime; //周期(几天为一轮)
private String endTime; //周期(几天为一轮)
private String delFlag; //默认为0,删除为1
/**
* @return the id
*/
public int getId() {
return super.getId();
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the elderId
*/
public Integer getElderId() {
return elderId;
}
/**
* @param elderId the elderId to set
*/
public void setElderId(Integer elderId) {
this.elderId = elderId;
}
/**
* @return the careItemId
*/
public Integer getCareItemId() {
return careItemId;
}
/**
* @param careItemId the careItemId to set
*/
public void setCareItemId(Integer careItemId) {
this.careItemId = careItemId;
}
/**
* @return the careItemName
*/
public String getCareItemName() {
return careItemName;
}
/**
* @param careItemName the careItemName to set
*/
public void setCareItemName(String careItemName) {
this.careItemName = careItemName;
}
/**
* @return the icon
*/
public String getIcon() {
return icon;
}
/**
* @param icon the icon to set
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
* @return the level
*/
public Integer getLevel() {
return level;
}
/**
* @param level the level to set
*/
public void setLevel(Integer level) {
this.level = level;
}
/**
* @return the period
*/
public Integer getPeriod() {
return period;
}
/**
* @param period the period to set
*/
public void setPeriod(Integer period) {
this.period = period;
}
/**
* @return the startTime
*/
public String getStartTime() {
return startTime;
}
/**
* @param startTime the startTime to set
*/
public void setStartTime(String startTime) {
this.startTime = startTime;
}
/**
* @return the endTime
*/
public String getEndTime() {
return endTime;
}
/**
* @param endTime the endTime to set
*/
public void setEndTime(String endTime) {
this.endTime = endTime;
}
/**
* @return the delFlag
*/
public String getDelFlag() {
return delFlag;
}
/**
* @param delFlag the delFlag to set
*/
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
/**
* @return the serialversionuid
*/
public static long getSerialversionuid() {
return serialVersionUID;
}
/* (non-Javadoc)
* @see com.sjtu.icare.common.persistence.BaseEntity#preDelete()
*/
@Override
public void preDelete() {
// TODO Auto-generated method stub
}
}
<file_sep>/src/main/java/com/sjtu/icare/modules/staff/persistence/StaffSchedulePlanDAO.java
/**
* @Package com.sjtu.icare.modules.staff.persistence
* @Description TODO
* @date Mar 13, 2015 10:44:35 AM
* @author <NAME>
* @version TODO
*/
package com.sjtu.icare.modules.staff.persistence;
import java.util.List;
import java.util.Map;
import com.sjtu.icare.common.persistence.annotation.MyBatisDao;
import com.sjtu.icare.modules.staff.entity.StaffSchedulePlanEntity;
@MyBatisDao
public interface StaffSchedulePlanDAO {
List<StaffSchedulePlanEntity> getStaffSchedulePlans(
Map<String, Object> paramMap);
void insertStaffSchedulePlans(Map<String, Object> paramMap);
void deleteStaffSchedulePlans(Map<String, Object> paramMap);
List<StaffSchedulePlanEntity> getAllStaffSchedulePlansByGeroId(
Map<String, Object> paramMap);
List<StaffSchedulePlanEntity> getAllStaffSchedulePlansByGeroIdAndRole(
Map<String, Object> paramMap);
}
<file_sep>/src/main/java/com/sjtu/icare/modules/staff/service/impl/DutyCarerService.java
/**
* @Package com.sjtu.icare.modules.staff.service.impl
* @Description TODO
* @date Mar 15, 2015 6:12:20 PM
* @author <NAME>
* @version TODO
*/
package com.sjtu.icare.modules.staff.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sjtu.icare.common.utils.MapListUtils;
import com.sjtu.icare.modules.elder.entity.ElderEntity;
import com.sjtu.icare.modules.gero.entity.GeroAreaEntity;
import com.sjtu.icare.modules.op.persistence.CareworkDAO;
import com.sjtu.icare.modules.staff.entity.StaffEntity;
import com.sjtu.icare.modules.staff.service.IDutyCarerService;
@Service
public class DutyCarerService implements IDutyCarerService {
@Autowired
CareworkDAO careworkDao;
/* (non-Javadoc)
* @see com.sjtu.icare.modules.staff.service.IDutyCarerService#getDutyCarerByElderIdAndDate(com.sjtu.icare.modules.elder.entity.ElderEntity, java.lang.String)
*/
@Override
public List<StaffEntity> getDutyCarerByElderIdAndDate(
ElderEntity elderEntity, String date) {
Map<String, Object> paramMap = MapListUtils.beanToMap(elderEntity);
paramMap.put("date", date);
return careworkDao.getStaffEntitiesByElderId(paramMap);
}
/* (non-Javadoc)
* @see com.sjtu.icare.modules.staff.service.IDutyCarerService#getDutyCarerByAreaIdAndDate(com.sjtu.icare.modules.gero.entity.GeroAreaEntity, java.lang.String)
*/
@Override
public List<StaffEntity> getDutyCarerByAreaIdAndDate(
GeroAreaEntity geroAreaEntity, String date) {
Map<String, Object> paramMap = MapListUtils.beanToMap(geroAreaEntity);
paramMap.put("date", date);
return careworkDao.getStaffEntitiesByAreaId(paramMap);
}
}
<file_sep>/src/main/java/com/sjtu/icare/modules/op/entity/CareworkRecordEntity.java
package com.sjtu.icare.modules.op.entity;
import java.io.Serializable;
public class CareworkRecordEntity implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private Integer carerId; //护工ID
private Integer elderId; //老人ID
private Integer elderItemId; //老人护理项目ID
private String itemName; //项目名
private String finishTime; //完成时间
private String elderName; //完成时间
private String carerName; //完成时间
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the carerId
*/
public Integer getCarerId() {
return carerId;
}
/**
* @param carerId the carerId to set
*/
public void setCarerId(Integer carerId) {
this.carerId = carerId;
}
/**
* @return the elderId
*/
public Integer getElderId() {
return elderId;
}
/**
* @param elderId the elderId to set
*/
public void setElderId(Integer elderId) {
this.elderId = elderId;
}
/**
* @return the elderItemId
*/
public Integer getElderItemId() {
return elderItemId;
}
/**
* @param elderItemId the elderItemId to set
*/
public void setElderItemId(Integer elderItemId) {
this.elderItemId = elderItemId;
}
/**
* @return the itemName
*/
public String getItemName() {
return itemName;
}
/**
* @param itemName the itemName to set
*/
public void setItemName(String itemName) {
this.itemName = itemName;
}
/**
* @return the finishTime
*/
public String getFinishTime() {
return finishTime;
}
/**
* @param finishTime the finishTime to set
*/
public void setFinishTime(String finishTime) {
this.finishTime = finishTime;
}
/**
* @return the serialversionuid
*/
public static long getSerialversionuid() {
return serialVersionUID;
}
/**
* @return the elderName
*/
public String getElderName() {
return elderName;
}
/**
* @param elderName the elderName to set
*/
public void setElderName(String elderName) {
this.elderName = elderName;
}
/**
* @return the staffName
*/
public String getCarerName() {
return carerName;
}
/**
* @param staffName the staffName to set
*/
public void setCarerName(String carerName) {
this.carerName = carerName;
}
}
<file_sep>/src/main/java/com/sjtu/icare/modules/elder/TODO.TXT
!!!这个文件请在文件结构建立后删除
加入老人服务相关内容
目前有:
老人健康数据
老人服务记录
<file_sep>/src/main/java/com/sjtu/icare/modules/op/TODO.TXT
!!!这个文件请在文件结构建立后删除
OP=operation
业务逻辑相关
可以预见的这个文件夹内文件会比较多
应该在service文件夹内再做一次分层
目前有:
排班
项目 | 50fae8de82c5bef70e27e52787e31bea31366ed8 | [
"JavaScript",
"Java",
"Text",
"SQL"
] | 19 | Java | wwhui/icare | d86b84a987447dd2122e0a22bb674a67e7ebad9a | 88f7618014d7469ab137f173f61cd99771201232 |
refs/heads/master | <file_sep>package benjaminpeter.name;
import java.util.List;
import java.util.Iterator;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.Date;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.osaf.caldav4j.CalDAVCollection;
import org.osaf.caldav4j.CalDAVConstants;
import org.osaf.caldav4j.exceptions.CalDAV4JException;
import org.osaf.caldav4j.methods.CalDAV4JMethodFactory;
import org.osaf.caldav4j.methods.HttpClient;
import org.osaf.caldav4j.model.request.CalendarQuery;
import org.osaf.caldav4j.util.GenerateQuery;
import static org.junit.Assert.assertTrue;
@RunWith(JUnit4.class)
public class ListCalendarTest {
private double calcDuration(VEvent ve) {
return ( ve.getEndDate().getDate().getTime()
- ve.getStartDate().getDate().getTime())
/ (1000. * 60. * 60.);
}
@Test
public void testList() throws CalDAV4JException
{
HttpClient httpClient = new HttpClient();
// I tried it with zimbra - but I had no luck using google calendar
httpClient.getHostConfiguration().setHost("CALDAVHOST", 443, "https");
String username = "username";
UsernamePasswordCredentials httpCredentials = new UsernamePasswordCredentials(username, "secret");
httpClient.getState().setCredentials(AuthScope.ANY, httpCredentials);
httpClient.getParams().setAuthenticationPreemptive(true);
// Need a proxy?
//httpClient.getHostConfiguration().setProxy("phost", 8080);
CalDAVCollection collection = new CalDAVCollection(
"/dav/"+ username +"/Calendar",
(HostConfiguration) httpClient.getHostConfiguration().clone(),
new CalDAV4JMethodFactory(),
CalDAVConstants.PROC_ID_DEFAULT
);
GenerateQuery gq=new GenerateQuery();
// TODO you might want to adjust the date
gq.setFilter("VEVENT [20131001T000000Z;20131010T000000Z] : STATUS!=CANCELLED");
// Get the raw caldav query
// System.out.println("Query: "+ gq.prettyPrint());
CalendarQuery calendarQuery = gq.generate();
List<Calendar>calendars = collection.queryCalendars(httpClient, calendarQuery);
for (Calendar calendar : calendars) {
ComponentList componentList = calendar.getComponents().getComponents(Component.VEVENT);
Iterator<VEvent> eventIterator = componentList.iterator();
while (eventIterator.hasNext()) {
VEvent ve = eventIterator.next();
System.out.println("Event: "+ ve.toString());
System.out.println("Duration (h): "+ String.format("%.2f", calcDuration(ve)));
System.out.println("\n\n");
}
}
// Give us a good feeling
assertTrue(true);
}
}
<file_sep>
# list-events-caldav #
A small example on how to access a caldav calendar using caldav4j.
I created this since I couldn't find one and had to extract it from
the unit tests.
Configure ./src/test/java/benjaminpeter/name/ListCalendarTest.java
*Usage:* mvn test
[ListCalendarTest.java](https://github.com/dedeibel/list-events-caldav4j-example/blob/master/src/test/java/benjaminpeter/name/ListCalendarTest.java)
*yeah ... it's not actually a test*
## Dependencies: ##
*caldav4j 0.8-SNAPSHOT*, best is to install it on yourself
https://code.google.com/p/caldav4j/source/checkout
You can simply try:
$ svn checkout http://caldav4j.googlecode.com/svn/trunk
$ cd trunk
$ mvn -Dmaven.test.skip=true install
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>benjaminpeter.name</groupId>
<artifactId>list-events-java</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>list-events-java</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<!--
Pls download and mvn install it yourself
https://code.google.com/p/caldav4j/source/checkout
-->
<groupId>org.osaf</groupId>
<artifactId>caldav4j</artifactId>
<version>0.8-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
</dependencies>
</project>
| 699666a3755e7c7f94ea3f80c94c14c64775474f | [
"Markdown",
"Java",
"Maven POM"
] | 3 | Java | dedeibel/list-events-caldav4j-example | b1832a194c4be031c34472c86dec933160ce4a2d | 0beecb40e26b4625ea8f46f4d7bbaa83adf6ac38 |
refs/heads/master | <repo_name>ktvoort123/video-store-api<file_sep>/test/controllers/videos_controller_test.rb
require "test_helper"
describe VideosController do
it "responds with JSON and success" do
get videos_path
expect(response.header['Content-Type']).must_include 'json'
must_respond_with :ok
end
it "must get index" do
get videos_path
must_respond_with :success
end
it "responds with an array of video hashes" do
# Act
get videos_path
# Get the body of the response
body = JSON.parse(response.body)
# Assert
expect(body).must_be_instance_of Array
body.each do |video|
expect(video).must_be_instance_of Hash
required_video_attrs = ["available_inventory", "id", "release_date", "title"]
expect(video.keys.sort).must_equal required_video_attrs.sort
end
end
it "will respond with an empty array when there are no videos" do
# Arrange
Video.destroy_all
# Act
get videos_path
body = JSON.parse(response.body)
# Assert
expect(body).must_be_instance_of Array
expect(body).must_equal []
end
describe "show" do
it "must get show for valid ids" do
video = videos(:valid_video)
get video_path(video)
must_respond_with :success
body = JSON.parse(response.body)
expect(body).must_be_instance_of Hash
end
it "must respond with not found for invalid id" do
# Act
get video_path(-1)
body = JSON.parse(response.body)
# Assert
expect(body).must_be_instance_of Hash
must_respond_with :not_found
end
end
describe "create" do
before do
@video_hash = {
title: "The Actors Are Chipmunks",
overview: "A tale of anthropomorphization",
release_date: "5/17/20",
total_inventory: 5,
available_inventory: 5
}
end
it "can create a new video" do
expect {
post videos_path, params: @video_hash
}.must_differ "Video.count", 1
new_video = Video.find_by(title: @video_hash[:title])
expect(new_video.overview).must_equal @video_hash[:overview]
end
it "can will not create a new video if title isn't included" do
@video_hash[:title] = nil
expect {
post videos_path, params: @video_hash
}.wont_change "Video.count"
body = JSON.parse(response.body)
expect(body).must_be_instance_of Hash
end
it "can will not create a new video if available inventory isn't included" do
@video_hash[:available_inventory] = nil
expect {
post videos_path, params: @video_hash
}.wont_change "Video.count"
body = JSON.parse(response.body)
expect(body).must_be_instance_of Hash
end
end
end
<file_sep>/app/models/customer.rb
class Customer < ApplicationRecord
validates :name, presence: true
validates :videos_checked_out_count, presence: true
has_many :rentals, dependent: :destroy
has_many :videos, :through => :rentals
end
<file_sep>/test/models/rental_test.rb
require "test_helper"
describe Rental do
before do
@blathers = customers(:blathers)
@valid_video = videos(:valid_video)
@museumrental = rentals(:museumrental)
end
describe "validations" do
it "can be recalled/is valid" do
expect(@museumrental.valid?).must_equal true
end
it "can be created when video_id and customer_id are present" do
new_rental = Rental.new(
customer: @blathers,
video: @valid_video
)
expect(new_rental.valid?).must_equal true
end
it "cannot create a new rental when video_id is not present" do
new_rental = Rental.new(customer: @blathers)
expect(new_rental.valid?).must_equal false
end
it "cannot create a new rental when customer_id is not present" do
new_rental = Rental.new(video: @valid_video)
expect(new_rental.valid?).must_equal false
end
end
describe "relationships" do
before do
@valid_video = videos(:valid_video)
@customer = customers(:blathers)
rentals(:museumrental)
end
it "can establish many to many relationship between videos and customers" do
expect(@customer.rentals.length).must_equal 1
expect(@customer.videos.length).must_equal 1
expect(@customer.videos[0].id).must_equal @valid_video.id
end
end
end
<file_sep>/app/models/video.rb
class Video < ApplicationRecord
validates :title, presence: true
validates :available_inventory, presence: true
validates :total_inventory, presence: true
validates :overview, presence: true
validates :release_date, presence: true
has_many :rentals, dependent: :destroy
has_many :customers, :through => :rentals
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::API
# def show
# render json: { testing: "it works" }, status: :ok
# end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
# get 'videos/#index'
# get 'videos/#show'
# get 'videos/#create'
# get 'customers/#index'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :customers, only: [:index]
resources :videos, only: [:index, :show, :create]
post '/rentals/check-out', to: 'rentals#check_out', as: 'check-out'
post '/rentals/check-in', to: 'rentals#check_in', as: 'check-in'
# get '/zomg', to: 'application#show'
end
<file_sep>/test/models/customer_test.rb
require "test_helper"
require "test_helper"
describe Customer do
before do
@customer = customers(:blathers)
end
describe "validations" do
it "can be recalled/is valid" do
expect(@customer.valid?).must_equal true
end
it "will not save if the name is nil" do
# Arrange
@customer.name = nil
# Assert
expect(@customer.valid?).must_equal false
expect(@customer.errors.messages).must_include :name
expect(@customer.errors.messages[:name]).must_equal ["can't be blank"]
end
it "will not save if the videos_checked_out_count is nil" do
# Arrange
@customer.videos_checked_out_count = nil
# Assert
expect(@customer.valid?).must_equal false
expect(@customer.errors.messages).must_include :videos_checked_out_count
expect(@customer.errors.messages[:videos_checked_out_count]).must_equal ["can't be blank"]
end
end
describe "relationships" do
before do
@valid_video = videos(:valid_video)
@customer = customers(:blathers)
rentals(:museumrental)
end
it "can establish many to many relationship between videos and customers" do
expect(@customer.rentals.length).must_equal 1
expect(@customer.videos.length).must_equal 1
expect(@customer.videos[0].id).must_equal @valid_video.id
end
end
end
<file_sep>/test/models/video_test.rb
require "test_helper"
describe Video do
before do
@valid_video = videos(:valid_video)
end
describe "validations" do
it "can be recalled/is valid" do
expect(@valid_video.valid?).must_equal true
end
it "will not save if the title is nil" do
# Arrange
@valid_video.title = nil
# Assert
expect(@valid_video.valid?).must_equal false
expect(@valid_video.errors.messages).must_include :title
expect(@valid_video.errors.messages[:title]).must_equal ["can't be blank"]
end
it "will not save if the available_inventory is nil" do
# Arrange
@valid_video.available_inventory = nil
# Assert
expect(@valid_video.valid?).must_equal false
expect(@valid_video.errors.messages).must_include :available_inventory
expect(@valid_video.errors.messages[:available_inventory]).must_equal ["can't be blank"]
end
describe "relationships" do
before do
@valid_video = videos(:valid_video)
@customer = customers(:blathers)
rentals(:museumrental)
end
it "can establish many to many relationship between videos and customers" do
expect(@customer.rentals.length).must_equal 1
expect(@customer.videos.length).must_equal 1
expect(@customer.videos[0].id).must_equal @valid_video.id
end
end
end
end
<file_sep>/app/controllers/rentals_controller.rb
class RentalsController < ApplicationController
def check_out
video = Video.find_by(id: params[:video_id])
customer = Customer.find_by(id: params[:customer_id])
rental = Rental.new(customer: customer, video: video, due_date: (Date.today + 7))
if !video.nil? && video.available_inventory <= 0
render json: {
errors: ['Not Found']
}, status: :not_found
return
elsif rental.save
video.available_inventory -= 1
video.save
customer.videos_checked_out_count += 1
customer.save
render json: { customer_id: rental.customer_id,
video_id: rental.video_id,
due_date: rental.due_date,
videos_checked_out_count: customer.videos_checked_out_count,
available_inventory: video.available_inventory }
else
render json: {
errors: ['Not Found']
}, status: :not_found
return
end
end
def check_in
rental = Rental.find_by(customer_id: params[:customer_id], video_id: params[:video_id])
if rental.nil?
render json: {
errors: ["Not Found"],
},status: :not_found
elsif rental
rental.customer.videos_checked_out_count -= 1
rental.customer.save
rental.video.available_inventory += 1
rental.video.save
rental.returned = true
rental.save
render json: { customer_id: rental.customer_id,
video_id: rental.video_id,
videos_checked_out_count: rental.customer.videos_checked_out_count,
available_inventory: rental.video.available_inventory }, status: :ok
end
end
end | cc7f2e2ef64ce1961e16a4d33ee8e37d605ce0f6 | [
"Ruby"
] | 9 | Ruby | ktvoort123/video-store-api | 3dfa714a7a5c2790b7fb7cbb7f7c82bd392663b4 | 0180f80c1b5a30abcf5bf40a591ae22a13ea1f63 |
refs/heads/master | <repo_name>Thomasubert/projetperso<file_sep>/src/Controller/HomeController.php
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class HomeController extends AbstractController{
public function home() : Response{
return $this->render('home.html.twig');
}
/**
* @Route("/", name="accueil")
*/
public function accueil() : Response{
return $this->render('accueil.html.twig');
}
public function profil() : Response{
return $this->render('profil.html.twig');
}
/**
* @Route("/apropos", name="apropos")
*/
public function apropos() : Response{
return $this->render('apropos.html.twig');
}
public function __construct(){
$this->created_at = new \DateTime();
}
} | 5649e4e5b34cd5dfdf16cc75a04d54112dd3516b | [
"PHP"
] | 1 | PHP | Thomasubert/projetperso | 4db91633f49dbc186fcf8bc1dc407c164cf8b3b4 | 4ba7f774204b76e93fe999ca23b06cae558c2c9f |
refs/heads/master | <repo_name>SterlingAr/PasswordApp<file_sep>/PasswordBucket/src/com/passwordbucket/view/EntryListController.java
package com.passwordbucket.view;
import java.util.List;
import com.passwordbucket.MainApp;
import com.passwordbucket.model.domain.Entry;
import com.passwordbucket.model.domain.EntryList;
import com.passwordbucket.model.services.EntryListService;
import com.passwordbucket.model.services.EntryService;
import com.passwordbucket.model.services.impl.EntryListServiceImpl;
import com.passwordbucket.model.services.impl.EntryServiceImpl;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
public class EntryListController {
private EntryService entryService = new EntryServiceImpl();
private EntryListService entryListService = new EntryListServiceImpl();
private ObservableList<Entry> entryList;
/** List columns */
@FXML
private TableView<EntryList> entryListTable;
@FXML
private TableColumn<EntryList, String> listTitleColumn;
/** Entry columns */
@FXML
private TableView<Entry> entryTable;
@FXML
private TableColumn<Entry, String> siteColumn;
@FXML
private TableColumn<Entry, String> userColumn;
@FXML
private TableColumn<Entry, String> passwordColumn;
// Reference to the main application
private MainApp mainApp;
/** The constructor is called before the initialize method */
public EntryListController() {
}
/**
* Initializes the controller class. This method is automatically called
* after the fxml file has been loaded
*/
@FXML
private void initialize() {
// Initialize the list table with its only column
listTitleColumn.setCellValueFactory(cellData -> cellData.getValue().titleProperty());
// listen for selection changes
entryListTable.getSelectionModel().selectedItemProperty();
entryTable.getSelectionModel().selectedItemProperty();
}
/** Is called by the main application to give a reference back to itself */
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
// add observable list data to the table
entryListTable.setItems(mainApp.getListData());
}
/** Called when the user clicks on the delete button */
@FXML
private void handleDeleteList() {
int selectedIndex = entryListTable.getSelectionModel().getSelectedIndex();
entryListService.deleteList(entryListTable.getItems().get(selectedIndex));
entryListTable.getItems().remove(selectedIndex);
}
@FXML
private void handleClickOnList() {
int selectedIndex = entryListTable.getSelectionModel().getSelectedIndex();
EntryList el = entryListTable.getItems().get(selectedIndex);
List<Entry> listOfEntries = entryService.getAllEntries(el);
this.entryTable.setItems(FXCollections.observableArrayList(listOfEntries));
siteColumn.setCellValueFactory(cellData -> cellData.getValue().siteProperty());
userColumn.setCellValueFactory(cellData -> cellData.getValue().userProperty());
passwordColumn.setCellValueFactory(cellData -> cellData.getValue().passwordProperty());
System.out.println("funca?");
}
@FXML
private void handleDeleteEntry() {
int selectedIndexEntry = entryTable.getSelectionModel().getSelectedIndex();
Entry e = entryTable.getItems().get(selectedIndexEntry);
entryService.deleteEntry(e);
entryTable.getItems().remove(selectedIndexEntry);
}
}
<file_sep>/TEsts/src/ch/makery/adress/view/RootLayoutController.java
package ch.makery.adress.view;
public class RootLayoutController {
}
<file_sep>/bbdd_entry.sql
CREATE DATABASE PasswordBucket;
USE PasswordBucket;
CREATE TABLE list (
id_list INT UNSIGNED NOT NULL,
title VARCHAR(50),
PRIMARY KEY(id_list)
);
CREATE TABLE entry (
id_entry INT UNSIGNED NOT NULL,
site VARCHAR(150),
password VARCHAR(100),
id_list INT UNSIGNED NOT NULL,
FOREIGN KEY (id_list) REFERENCES list (id_list),
PRIMARY KEY (id_entry)
);<file_sep>/App_Contrasenha/src/services/EntryListService.java
package services;
import java.util.List;
import domain.EntryList;
import domain.repository.ListRepository;
import domain.repository.impl.ListsInMemory;
public interface EntryListService {
void newEmptyList(EntryList el);
EntryList getListByName(String name);
EntryList loadSelectedList(EntryList e);
void deleteList(EntryList el);
void deleteMultipleLists(List<EntryList> lel);
}
<file_sep>/Tables.sql
CREATE TABLE `Lista` (
`id_Lista` INT NOT NULL,
`title` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id_Lista`))
ENGINE = InnoDB;
CREATE TABLE `Entry` (
`id_entry` INT NOT NULL,
`site` VARCHAR(100) NOT NULL,
`user` VARCHAR(30) NOT NULL,
`password` VARCHAR(45) NULL,
`id_lista` INT NULL,
PRIMARY KEY (`id_entry`),
INDEX `Fk_lista_idx` (`id_lista` ASC),
CONSTRAINT `Fk_lista`
FOREIGN KEY (`id_lista`)
REFERENCES `Lista` (`id_Lista`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
| fa0172c6b166f65cde173164a3e2e9a126da71c9 | [
"Java",
"SQL"
] | 5 | Java | SterlingAr/PasswordApp | 11df53d0a91b226846e8e062abecd7b217348452 | afec290b040c9f1aa49b2f9ce065ffd365a49e05 |
refs/heads/master | <repo_name>jffarias/algoritmos_python<file_sep>/cuadrado.py
def cuad1(num):
print num*num
def cuad2():
n = input("Ingrese un número: ")
cuad1(n)
<file_sep>/buscarEnArchivo1.py
#https://es.stackoverflow.com/questions/38288/duda-con-raw-input
#http://pharalax.com/blog/python-buscador-de-palabras-en-un-archivo/
print("*** buscador de palabras dentro de un archivo ***")
print("*************************************************")
print ("")
palabra = input("palabra a buscar ?? ")
archivo = input("Archivo donde Buscar >> ")
repetidas = 0
f = open(archivo)
lines = f.readlines()
for line in lines:
palabras = line.split(' ')
for p in palabras:
if p==palabra:
repetidas = repetidas+1
print("la palabra \"{0}\" se repite {1} veces en el Archivo {2}".format(palabra,repetidas,archivo))
<file_sep>/leerarchivo1.py
#https://www.youtube.com/watch?v=Z__uTkV4888
#https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
import time
def leerArch():
# Abre archivo en modo lectura
archivo = open('datos1.txt','r')
# Lee todas la líneas y asigna a lista
lista = archivo.readlines()
# Inicializa un contador
numlin = 0
# Recorre todas los elementos de la lista
for linea in lista:
# incrementa en 1 el contador
numlin += 1
# muestra contador y elemento (línea)
if(numlin <= 5):
print(numlin, linea)
archivo.close() # cierra archivo
while(True):
time.sleep(5)
print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')
leerArch()
| b6aa5e763bbf98db2538dd5c4301b19c843fdbb7 | [
"Python"
] | 3 | Python | jffarias/algoritmos_python | 0e8d753c2e5c9c6ec592e30fe5423be67b60dd3a | 261dddc0c73aac4cc3fd0b29abf106846a9c06b7 |
refs/heads/master | <repo_name>Andrzej-Marek/Netguru<file_sep>/start.js
const app = require("./app.js");
const db_connect = require("./actions/db_connect");
// const mongoose = require("mongoose");
db_connect();
// const tryToConnectDB = () => {
// mongoose
// .connect("mongodb://mongo:27017/netguru_test_app", {
// // useUnifiedTopology: true,
// useNewUrlParser: true
// })
// .then(() => console.log("MongoDB Connected"))
// .catch(err => {
// console.log("ERROR", err);
// setTimeout(() => tryToConnectDB(), 2000);
// });
// };
// tryToConnectDB();
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
<file_sep>/tests/movie.test.js
const MovieModel = require("../models/MovieModel");
const dbHandler = require("./db-handler");
const app = require("../app");
const supertest = require("supertest");
const testMovie = require("./filesForTests/movieTestObject");
const request = supertest(app);
beforeAll(async () => await dbHandler.connect());
afterEach(async () => await dbHandler.clearDatabase());
afterAll(async () => await dbHandler.closeDatabase());
describe("Testing endpoint", () => {
it("Get list of all movies in DB", async done => {
const responce = await request.get("/movies");
expect(responce.body).toMatchObject({ msg: "No records in DB" });
const newMovie = new MovieModel(testMovie);
const savedMovie = await newMovie.save();
expect(savedMovie).toBeTruthy();
expect(responce.body.title).toBe(savedMovie.title);
expect(responce.body.year).toBe(savedMovie.year);
done();
});
it("Find a movie in sevice", async done => {
const responce = await request.post("/movies").send({ title: "Monopoly" });
expect(responce.status).toBe(200);
expect(responce.body).toBeTruthy();
expect(responce.body).toHaveProperty("Title");
done();
});
it("Not provide a parametr ( error )", async done => {
const responce = await request.post("/movies");
expect(responce.status).toBe(400);
expect(responce.body.status).toBe("error");
expect(responce.body).toHaveProperty("status");
expect(responce.body).toHaveProperty("statusCode");
expect(responce.body).toHaveProperty("message");
done();
});
it("Not provide a parametr ( error )", async done => {
const responce = await request.post("/movies");
expect(responce.status).toBe(400);
expect(responce.body.status).toBe("error");
expect(responce.body).toHaveProperty("status");
expect(responce.body).toHaveProperty("statusCode");
expect(responce.body).toHaveProperty("message");
done();
});
});
describe("Testing datebase in /movies route", () => {
it("Create a new movie and save it to datebase", async () => {
const newMovie = new MovieModel(testMovie);
const savedMovie = await newMovie.save();
expect(savedMovie).toBeTruthy();
expect(savedMovie._id).toBeDefined();
expect(savedMovie.Title).toBe(testMovie.Title);
});
});
<file_sep>/routes/routes.js
const app = (module.exports = require("express")());
app.use("/movies", require("./movieApi"));
app.use("/comments", require("./commentApi"));
app.all("/*", (req, res) => {
res.status(404).json({ msg: "Not found endpoint" });
});
<file_sep>/actions/db_connect.js
const mongoose = require("mongoose");
const { DB_USER, DB_PASSWORD, DB_NAME } = require("../config/config.json");
module.exports = () => {
mongoose
.connect(
`mongodb://${process.env.DB_USER || DB_USER}:${process.env.DB_PASSWORD ||
DB_PASSWORD}@<EMAIL>:15131/${process.env.DB_NAME || DB_NAME}`,
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
.then(() => console.log("Datebase connected"))
.catch(err => console.log("ERROR", err));
};
<file_sep>/tests/comments.test.js
const mongoose = require("mongoose");
const CommentModel = require("../models/CommentModel");
const dbHandler = require("./db-handler");
const app = require("../app");
const supertest = require("supertest");
const request = supertest(app);
const comment = { comment: "Testing comment" };
beforeAll(async () => await dbHandler.connect());
afterEach(async () => await dbHandler.clearDatabase());
afterAll(async () => await dbHandler.closeDatabase());
describe("Comments End-points", () => {
it("Gets the test endpoint", async done => {
const response = await request
.get("/comments")
.expect("Content-Type", /json/);
expect(response.status).toBe(200);
done();
});
it("If Datebase is empty, get message about it", async done => {
const response = await request
.get("/comments")
.expect("Content-Type", /json/);
expect(response.status).toBe(200);
expect(response.body).toHaveProperty("msg");
done();
});
it("Add new comment to Datebae", async done => {
const response = await request
.post("/comments")
.send({
comment: "Test comment"
})
.expect("Content-Type", /json/);
expect(response.status).toBe(200);
expect(response.body).toHaveProperty("comment");
done();
});
it("Trow a error when no comment is provide", async done => {
const response = await request
.post("/comments")
.expect("Content-Type", /json/);
expect(response.status).toBe(400);
expect(response.body.status).toBe("error");
done();
});
});
describe("Testing datebase in /comments route", () => {
it("Create a new comment and save it to datebase", async () => {
const newComment = new CommentModel(comment);
const savedComment = await newComment.save();
expect(savedComment).toBeTruthy();
expect(savedComment._id).toBeDefined();
expect(savedComment.comment).toBe(comment.comment);
});
it("Create a new comment without comment ( error )", async () => {
const newCommentWithoutCommentField = new CommentModel();
let err;
try {
const savedCommentWithoutCommentField = await newCommentWithoutCommentField.save();
error = savedCommentWithoutCommentField;
} catch (error) {
err = error;
}
expect(err).toBeInstanceOf(mongoose.Error.ValidationError);
});
});
<file_sep>/routes/commentApi.js
const express = require("express");
const CommentModal = require("../models/CommentModel");
const router = express.Router();
const { ErrorHandler } = require("../helpers/error");
router.post("/", async (req, res, next) => {
const { comment } = req.body;
try {
if (!comment || comment.length < 4) {
throw new ErrorHandler(
400,
"You have to write a comment and it can't be short that 4 characters"
);
}
const newComment = new CommentModal({
comment
});
await newComment.save();
res.status(200).json(newComment);
} catch (error) {
next(error);
}
});
router.get("/", async (req, res, next) => {
try {
const allCommnetsInDB = await CommentModal.find({});
if (allCommnetsInDB.length === 0) {
return res.status(200).json({ msg: "No comments in DB" });
}
res.json(allCommnetsInDB);
} catch (error) {
next(error);
}
});
module.exports = router;
<file_sep>/routes/movieApi.js
const express = require("express");
const axios = require("axios");
const { API_KEY } = require("../config/config.json");
const { ErrorHandler } = require("../helpers/error");
const MovieModel = require("../models/MovieModel");
const router = express.Router();
//ROUTE: */movie
//DESC: movie api
router.post("/", async (req, res, next) => {
const { title, year, id } = req.body;
try {
if (!title && !year && !id) {
throw new ErrorHandler(400, "You have to post title or year or move id");
}
const { data } = await axios.get(
`http://www.omdbapi.com/?${id && `i=${id}`}&${title &&
`t=${title}`}&${year && `y=${year}`}&plot=full&apikey=${API_KEY}`
);
if (data.Response === "False") {
throw new ErrorHandler(404, "No movies finded");
}
const movieInDB = await MovieModel.find({
$or: [{ Title: data.Title }, { _id: id }]
});
if (movieInDB.length > 0) {
return res.status(200).send(movieInDB);
}
const newMovie = new MovieModel({ ...data });
await newMovie.save();
res.json(newMovie);
} catch (error) {
next(error);
}
});
router.get("/", async (req, res, next) => {
try {
const allMoviesInDB = await MovieModel.find({});
if (allMoviesInDB.length === 0) {
return res.status(200).json({ msg: "No records in DB" });
}
res.json(allMoviesInDB);
} catch (error) {
next(error);
}
});
module.exports = router;
<file_sep>/README.md
<NAME> task
<h2> How to run this application? </h2>
<ul>
<li>
Pull all this repo. ( master branch include all keys and config folder )
</li>
<li>
cd into folder with this files
</li>
<li>
Install all dependencis by type a commend npm i or npm install
</li>
<li>
In termina run npm start or npm run dev
</li>
</ul>
| 55a572abcfa5c15bc64840f485320f46633def4d | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | Andrzej-Marek/Netguru | b64d94c5a46128b3e1fe3e393d73729a0788fcdd | 4c2d1b6c24fa0778274b7e1d32ea0a2eb7f53385 |
refs/heads/master | <repo_name>RobertoFlores/RevolverETL<file_sep>/DataModel/Entities/Enum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataModel.Entities
{
public enum DatabaseDriver
{
MySQL = 1,
SQLServer,
SQLite,
Oracle
}
public enum FileType
{
CSV =1,
Excel,
XML
}
public enum RemoteConnection
{
FTP = 1,
RestFull,
SOA,
OData,
WCF
}
}
<file_sep>/README.md
# RevolverETL
Tiny ETL System
Extract, Transform & Load
Main Goals
* Extract information from MySQL, SQL Server, SQLite DBMS, CSV file, Excel File, XML File, Web Service, FTP.
* Transform easily the information extracted.
* Load the information to MySQL, SQL Server, SQLite DBMS
+ Features
- MultiThread, no blocking approach
- NetMQ based PipeLine System
- Nlog based logger
- Quartz Based Scheduler
- Windows Service Daemon
- UI to set up the Runner
<file_sep>/DataModel/Entities/FileSource.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataModel.Interfaces;
namespace DataModel.Entities
{
[Serializable()]
public class FileSource
{
public FileSource(string path, FileType ftype)
{
PathFile = path;
FileType = ftype;
}
private string _Name { get; set; }
public string Name
{
get { return this._Name; }
set { this._Name = value; }
}
public string PathFile { get; set; }
public FileType FileType { get; set; }
public void Enable()
{
//TBA
}
public void Disable()
{
//TBA
}
}
}
<file_sep>/DataModel/Entities/RemoteServer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataModel.Interfaces;
namespace DataModel.Entities
{
[Serializable()]
public class RemoteServer
{
public RemoteServer(string raddress, string user, string password, RemoteConnection dbconn)
{
RemoteAdress = raddress;
User = user;
Password = <PASSWORD>;
RemoteConnection = dbconn;
}
private string _Name { get; set; }
public string Name
{
get { return this._Name; }
set { this._Name = value; }
}
public string RemoteAdress { get; set; }
public string User { get; set; }
public string Password { get; set; }
public RemoteConnection RemoteConnection { get; set; }
public void Enable()
{
//TBA
}
public void Disable()
{
//TBA
}
}
}
<file_sep>/ETLUnitTest/MetaDataReader/MetaDataReaderTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NMG.Core;
using NMG.Core.Domain;
using NMG.Core.Reader;
namespace ETLUnitTest.MetaDataReader
{
[TestClass]
public class MetaDataReaderTest
{
[TestMethod]
public void GetTables()
{
IMetadataReader metadataReader;
Connection currentconnection = new Connection();
currentconnection.Id = new Guid();
currentconnection.ConnectionString = @"Data Source=localhost;Initial Catalog=eOS;User Id=sa;Password=<PASSWORD>;";
currentconnection.Type = ServerType.SqlServer;
metadataReader = MetadataFactory.GetReader(currentconnection.Type, currentconnection.ConnectionString);
var owners = metadataReader.GetOwners();
//var owner = owners.Contains("db_owner");
var tables = metadataReader.GetTables(owners[2]);
var tableuser = metadataReader.GetTableDetails(tables[1], owners[2]);
Assert.AreEqual(13, 13);
}
}
}
<file_sep>/DataModel/Entities/MysqlDataReader.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Data;
using DataModel.Interfaces;
using DataModel.Utils;
using NLog;
namespace DataModel.Entities
{
[Serializable()]
public class MysqlDataReader : IDataBaseReader
{
public MysqlDataReader(string raddress, string dbport, string dbname, string dbuser, string dbpassword)
{
RemoteAdress = raddress;
DataBasePort = dbport;
DataBaseName = dbname;
User = dbuser;
Password = <PASSWORD>;
DatabaseDriver = DatabaseDriver.MySQL;
}
public MysqlDataReader(string connectionstring)
{
connectionStr = connectionstring;
DatabaseDriver = DatabaseDriver.MySQL;
}
public MysqlDataReader()
{
//TBA
DatabaseDriver = DatabaseDriver.MySQL;
}
private string connectionStr = "";
private string _Name { get; set; }
public string Name
{
get { return this._Name; }
set { this._Name = value; }
}
private Logger logger = LogManager.GetCurrentClassLogger();
public string RemoteAdress { get; set; }
public string DataBasePort { get; set; }
public string DataBaseName { get; set; }
public string User { get; set; }
public string Password { get; set; }
public DatabaseDriver DatabaseDriver { get; set; }
public void Enable()
{
//TBA
}
public void Disable()
{
//TBA
}
public void SetConnection(string connectionstring)
{
this.connectionStr = connectionstring;
}
public int GetCount(string table, string dbname)
{
var conn = new MySqlConnection(connectionStr);
conn.Open();
int count = 0;
string stringcount = "";
try
{
using (conn)
{
var tableCommand = conn.CreateCommand();
tableCommand.CommandText = string.Format("select count(*) from {0}", table);
var sqlDataReader = tableCommand.ExecuteReader(CommandBehavior.CloseConnection);
while (sqlDataReader.Read())
{
stringcount = sqlDataReader.GetString(0);
}
}
}
finally
{
conn.Close();
}
bool resultParsing = int.TryParse(stringcount, out count);
if (resultParsing)
{
return count;
}
else
{
return 0;
}
}
public DataTable GetAllFromTable(string table, string dbname)
{
DataTable result = new DataTable();
var conn = new MySqlConnection(connectionStr);
conn.Open();
try
{
using (conn)
{
var tableCommand = conn.CreateCommand();
tableCommand.CommandText = String.Format("select * from {0}", table);
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = tableCommand;
da.Fill(result);
}
}
catch(Exception ex)
{
logger.Error("Error in GetAllFromTable", ex.Message);
}
finally
{
conn.Close();
}
if (result.Rows.Count > 0)
{
return result;
}
else
{
return new DataTable();
}
}
public DataTable GetSelectedColsFromTable(string table, string dbname, List<string> columns)
{
DataTable result = new DataTable();
var conn = new MySqlConnection(connectionStr);
conn.Open();
try
{
using (conn)
{
var tableCommand = conn.CreateCommand();
tableCommand.CommandText = CreateSqlCommand(table, columns);
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = tableCommand;
da.Fill(result);
}
}
catch (Exception ex)
{
logger.Error("Error in GetAllFromTable", ex.Message);
}
finally
{
conn.Close();
}
if (result.Rows.Count > 0)
{
return result;
}
else
{
return new DataTable();
}
}
private string CreateSqlCommand(string table, List<string> columns)
{
string result = "";
if(columns.Count > 0)
{
string fields = " ";
var lastitem = columns.Last();
foreach(string col in columns)
{
if(col == lastitem)
{
fields = fields + col;
}
else
{
fields = fields + col + ", ";
}
}
return string.Format("select {0} from {1}",fields, table);
}
else
{
return result;
}
}
public void CreateConnectionStr(string raddress, string dbport, string dbname, string dbuser, string dbpassword)
{
connectionStr = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};", raddress, dbport, dbname, dbuser, dbpassword);
}
public DataTable GetTables(string dbname)
{
DataTable result = new DataTable();
var conn = new MySqlConnection(connectionStr);
conn.Open();
int count = 0;
string stringcount = "";
try
{
using (conn)
{
var tableCommand = conn.CreateCommand();
tableCommand.CommandText = String.Format("select table_name from information_schema.tables where table_type like 'BASE TABLE' and TABLE_SCHEMA = '{0}'", dbname);
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = tableCommand;
da.Fill(result);
}
}
catch (Exception ex)
{
logger.Error("Error in GetTables", ex.Message);
}
finally
{
conn.Close();
}
bool resultParsing = int.TryParse(stringcount, out count);
if (result.Rows.Count > 0)
{
return result;
}
else
{
return new DataTable();
}
}
public DataColumnCollection GetTableDetails(string table, string dbname)
{
//select * from usuario LIMIT 1
DataTable result = new DataTable();
var conn = new MySqlConnection(connectionStr);
conn.Open();
try
{
using (conn)
{
var tableCommand = conn.CreateCommand();
tableCommand.CommandText = String.Format("select * from {0} limit 1", table);
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = tableCommand;
da.Fill(result);
}
}
catch (Exception ex)
{
logger.Error("Error in GetTableDetails", ex.Message);
}
finally
{
conn.Close();
}
return result.Columns;
}
}
}
<file_sep>/ETLUnitTest/DataModel/DbConnectTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DataModel.Entities;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Linq;
using System.Linq;
using System.Collections.Generic;
namespace ETLUnitTest.DataModel
{
[TestClass]
public class DbConnectUnitTest
{
#region MysqlReader
[TestMethod]
public void MysqlGetTablesTest()
{
const string connectionString = "Server=localhost;Database=adrepdbhuella;Uid=admin;Pwd=<PASSWORD>";
var database = new MysqlDataReader(connectionString);
database.Name = "MySQL Test";
var tables = database.GetTables("adrepdbhuella");
Assert.AreEqual(98, tables.Rows.Count);
}
[TestMethod]
public void MysqlTableGetCountTest()
{
const string connectionString = "Server=localhost;Database=adrepdbhuella;Uid=admin;Pwd=<PASSWORD>";
var database = new MysqlDataReader(connectionString);
database.Name = "MySQL Test";
var tables = database.GetTables("adrepdbhuella");
var tablecount = database.GetCount("asistencia", "adrepdbhuella");
Assert.AreEqual(293, tablecount);
}
[TestMethod]
public void GetAllFromTableTest()
{
const string connectionString = "Server=localhost;Database=adrepdbhuella;Uid=admin;Pwd=<PASSWORD>";
var reader = new MysqlDataReader();
reader.SetConnection(connectionString);
reader.Name = "MySQL Test";
var tables = reader.GetTables("adrepdbhuella");
var tableRows = reader.GetAllFromTable("asistencia", "adrepdbhuella").Rows;
Assert.AreEqual(293, tableRows.Count);
}
[TestMethod]
public void GetSelectedColsFromTable()
{
const string connectionString = "Server=localhost;Database=adrepdbhuella;Uid=admin;Pwd=<PASSWORD>";
var reader = new MysqlDataReader();
reader.SetConnection(connectionString);
reader.Name = "MySQL Test";
var tables = reader.GetTables("adrepdbhuella");
List<string> columns = new List<string>();
columns.Add("idpersona"); //nombre, apaterno, amaterno
columns.Add("nombre");
columns.Add("apaterno");
columns.Add("amaterno");
var tableRows = reader.GetSelectedColsFromTable("persona", "adrepdbhuella", columns).Rows;
Assert.AreEqual(104, tableRows.Count);
}
[TestMethod]
public void GetTableDetailsTest()
{
const string connectionString = "Server=localhost;Database=adrepdbhuella;Uid=admin;Pwd=<PASSWORD>";
var reader = new MysqlDataReader();
reader.SetConnection(connectionString);
reader.Name = "MySQL Test";
var tables = reader.GetTables("adrepdbhuella");
//var tableusuario = tables.FirstOrDefault(x => x.Name == "usuario");
var tableDetails = reader.GetTableDetails("persona", "adrepdbhuella");
//var tableRows = reader.GetAllFromTable("turno", "devbostons").Rows;
Assert.AreEqual(10, tableDetails.Count);
}
#endregion
#region SQL Server DataReader
#endregion
}
}
<file_sep>/NMG.Core/Domain/Connection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NMG.Core.Domain
{
public class Connection
{
public Guid Id { get; set; }
public string ConnectionString { get; set; }
public string Name { get; set; }
public ServerType Type { get; set; }
}
}
<file_sep>/DataModel/Utils/Filer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using NLog;
namespace DataModel.Utils
{
class Filer
{
Logger logger = LogManager.GetCurrentClassLogger();
public String filesName;
public String filesExt;
public byte codingKey = 127;
public Filer(String filesName, String filesExt)
{
this.filesName = filesName;
this.filesExt = filesExt;
}
public Filer(String filesName, String filesExt, byte codingKey)
{
this.filesName = filesName;
this.filesExt = filesExt;
this.codingKey = codingKey;
}
//calculate directory based on the current date
protected String calcCompleteDir(String globalDir)
{
//get date, and parse it to obtain the directories tree
DateTime dateNow = DateTime.Today;
String month = Convert.ToString(dateNow.Month);
if (month.Length < 2)
{
month = "0" + month;
}
String year = Convert.ToString(dateNow.Year);
String dir = globalDir + "\\" + year + "\\" + month;
return dir;
}
//calculate file name based current day
protected String calcDayFileName()
{
DateTime dateNow = DateTime.Today;
String day = Convert.ToString(dateNow.Day);
if (day.Length < 2)
{
day = "0" + day;
}
return filesName + day + filesExt;
}
//creates directory if not exist
protected bool checkDirExists(String dir)
{
if (!Directory.Exists(dir))
{
//directory inexistent, create
Directory.CreateDirectory(dir);
//inexistent
return false;
}
//allready exists
return true;
}
public bool appendToCurrentFile(String line, String globalDir)
{
try
{
//calculate directory
String completeDir = calcCompleteDir(globalDir);
//create directory if it doesn't exist
checkDirExists(completeDir);
//add the file name
String path = completeDir + "\\" + calcDayFileName();
//save line to the correspondent file
File.AppendAllText(path, line + "\n");
}
catch //pokemon exception handling
{
return false;
}
return true;
}
protected bool appendObjectToFile(Object obj, String path)
{
try
{
//open file for writing
Stream fstream = File.Open(path, FileMode.Append);
//serialize object
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fstream, obj);//here we serialize and write to file
fstream.Close();
}
catch
{
return false;
}
return true;
}
public bool appendToCurrentFile(Object obj, String globalDir)
{
try
{
//calculate directory
String completeDir = calcCompleteDir(globalDir);
//create directory if it doesn't exist
checkDirExists(completeDir);
//add the file name
String path = completeDir + calcDayFileName();
//save object to the correspondent file
appendObjectToFile(obj, path);
}
catch //pokemon exception handling
{
return false;
}
return true;
}
//Encodes/Decodes a byte stream with XOR function with a given key
private byte[] encodeXOR(Stream stream, byte key)
{
//from the begining
stream.Position = 0;
byte[] bytes = new byte[stream.Length];
//put the stream content into the bytes array
stream.Read(bytes, 0, bytes.Length);
//modify (encode) the bytes
for (int i = 0; i < bytes.Length; i++)
{
//XOR every byte
bytes[i] = (byte)(bytes[i] ^ key);
}
return bytes;
}
public bool saveToFile(Object obj, string dir)
{
//create directory if it doesn't exist
checkDirExists(dir);
string path = dir + "\\" + filesName + "." + filesExt;
if (saveObjectToFile(obj, path))
{
return true;
}
else
{
return false;
}
}
private bool saveObjectToFile(Object obj, string path)
{
//open file for writing
Stream fstream = File.Open(path, FileMode.Create);
try
{
Stream serialObj = new MemoryStream();
//serialize object
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(serialObj, obj);
//encode object with XOR function
byte[] bytes = encodeXOR(serialObj, codingKey);
//copy encoded serialized object to file
fstream.Write(bytes, 0, bytes.Length);
}
catch (Exception ex)
{
//Logger.output("#####ERROR:" + ex.Message);
logger.Error("#####ERROR Saving object: {0}", ex.Message);
return false;
}
finally
{
fstream.Close();
}
return true;
}
public ObjClass readClassObjectFromFile<ObjClass>(string path)
{
//verificar si existe archivo
if (!File.Exists(path))
{
//Logger.output("No existe el archivo: " + path);
logger.Error("#####ERROR File dosn't exist: {0}", path);
return default(ObjClass);
}
ObjClass obj;
//open file for reading
Stream fstream = File.OpenRead(path);
try
{
//decode stream with XOR function
byte[] bytes = encodeXOR(fstream, codingKey);
//get the bytes into a stream
Stream decoded = new MemoryStream();
decoded.Write(bytes, 0, bytes.Length);
//deserialize object
decoded.Position = 0;//from the begining
BinaryFormatter formatter = new BinaryFormatter();
obj = (ObjClass)formatter.Deserialize(decoded);
}
catch (Exception ex)
{
//Logger.output("#####ERROR:" + ex.Message);
logger.Error("#####ERROR Reading File: {0}", ex.Message);
return default(ObjClass);
}
finally
{
fstream.Close();
}
return obj;
}
public Object readObjectFromFile(string path)
{
//verificar si existe archivo
if (!File.Exists(path))
{
//Logger.output("No existe el archivo: " + path);
logger.Error("#####ERROR File Dosn't exist: {0}", path);
return null;
}
Object obj;
//open file for reading
Stream fstream = File.OpenRead(path);
try
{
//decode stream with XOR function
byte[] bytes = encodeXOR(fstream, codingKey);
//get the bytes into a stream
Stream decoded = new MemoryStream();
decoded.Write(bytes, 0, bytes.Length);
//deserialize object
decoded.Position = 0;//from the begining
BinaryFormatter formatter = new BinaryFormatter();
obj = (Object)formatter.Deserialize(decoded);
}
catch (Exception ex)
{
//Logger.output("#####ERROR:" + ex.Message);
logger.Error("#####ERROR Decoding File: {0}", ex.Message);
return null;
}
finally
{
fstream.Close();
}
return obj;
}
}
}
<file_sep>/ETL.Console.Revolver/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NMG.Core;
using NMG.Core.Domain;
using NMG.Core.Reader;
namespace ETL.Console.Revolver
{
class Program
{
static void Main(string[] args)
{
IMetadataReader metadataReader;
Connection currentconnection = new Connection();
currentconnection.Id = new Guid();
currentconnection.ConnectionString = @"Data Source=localhost;Initial Catalog=eOS;User Id=sa;Password=<PASSWORD>;";
currentconnection.Type = ServerType.SqlServer;
metadataReader = MetadataFactory.GetReader(currentconnection.Type, currentconnection.ConnectionString);
var owners = metadataReader.GetOwners();
var tables = metadataReader.GetTables(owners[2]);
var tableuser = metadataReader.GetTableDetails(tables[1], owners[2]);
foreach(var col in tableuser)
{
System.Console.WriteLine("Col Name: {0}",col.Name);
//Console.
}
System.Console.ReadKey();
}
}
}
<file_sep>/ETL.Core.Revolver/Core/Enum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ETL.Core.Revolver.Core
{
//public enum ServerType
//{
// Oracle,
// SqlServer,
// PostgreSQL,
// MySQL,
// SQLite,
// Sybase,
// Ingres,
// CUBRID
//}
}
<file_sep>/DataModel/Interfaces/IDataBaseReaderFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataModel.Entities;
namespace DataModel.Interfaces
{
interface IDataBaseReaderFactory
{
IDataBaseReader CreateDataBaseReader(DatabaseDriver DatabaseDriver);
}
}
<file_sep>/DataModel/Entities/DataBaseReaderFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataModel.Interfaces;
namespace DataModel.Entities
{
public class DataBaseReaderFactory : IDataBaseReaderFactory
{
public IDataBaseReader CreateDataBaseReader(DatabaseDriver DatabaseDriver)
{
switch (DatabaseDriver)
{
case DatabaseDriver.MySQL:
return new MysqlDataReader();
//case DatabaseDriver.SQLServer:
// return new SQLServerDataReader();
//case DatabaseDriver.SQLite:
// return new SQLiteDataReader();
default:
return new MysqlDataReader();
}
}
}
}
| 7389916eff6401fcdb51dc00868f5ec63f378434 | [
"Markdown",
"C#"
] | 13 | C# | RobertoFlores/RevolverETL | 947aec3f4899d9e68bbb974cea5228032c56cceb | aef7cb0d7a66c175f245a63fcf85b964602eb70b |
refs/heads/master | <repo_name>hildjj/itunes2html<file_sep>/fix
#!/usr/bin/env node
const plist = require('plist');
const pug = require('pug');
const fs = require('fs');
const path = require('path');
const util = require('util');
const PUG = path.join(__dirname, 'fix.pug');
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
const files = process.argv.splice(2);
Promise.all(files.map(async (file) => {
const xml = await readFile(file, 'utf-8');
const js = plist.parse(xml);
const html = pug.renderFile(PUG, {
pretty: true,
tracks: Object.values(js.Tracks)
});
const out = path.join(path.dirname(file), path.basename(file, path.extname(file)) + ".html");
await writeFile(out, html)
console.log(`${file} -> ${out}`);
}))
.then(
() => console.log('done'),
(er) => console.error('ERROR:', er))
<file_sep>/README.md
Translate an iTunes XML export file to HTML.
Install:
npm install -g itunes2html
Run:
itunes2html Library.xml
[Example output](https://hildjj.github.io/itunes2html/example/Library.html) | 1e103f34ab8993d191768d1dd0c3d3ee2a2c5dab | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | hildjj/itunes2html | 468794d2c461fa08d16c51bb36873ae9877bb728 | 3f61b6d14d56a90290a9dd134c06c470ec4fac94 |
refs/heads/master | <file_sep>using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
namespace pswdgen
{
class Program
{
static string RandomString(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+{},./<>?{}:~`";
StringBuilder res = new StringBuilder();
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] uintBuffer = new byte[sizeof(uint)];
while (length-- > 0)
{
rng.GetBytes(uintBuffer);
uint num = BitConverter.ToUInt32(uintBuffer, 0);
res.Append(valid[(int)(num % (uint)valid.Length)]);
}
}
return res.ToString();
}
// <Sarang.Baheti> 06-Mar-2018
// https://stackoverflow.com/a/43078669/916549
const int STD_OUTPUT_HANDLE = -11;
const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4;
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll")]
static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
[DllImport("kernel32.dll")]
static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
static void WriteWithUnderLine(string message, ConsoleColor color)
{
var handle = GetStdHandle(STD_OUTPUT_HANDLE);
uint mode;
GetConsoleMode(handle, out mode);
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(handle, mode);
const string UNDERLINE = "\x1B[4m";
const string RESET = "\x1B[0m";
var bkpColor = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.WriteLine(UNDERLINE + message + RESET);
Console.ForegroundColor = bkpColor;
}
static void Main(string[] args)
{
Console.WriteLine();
var currentForeGroundColor = Console.ForegroundColor;
try
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("A handy utility to generate random passwords");
Console.WriteLine("Copyright c <NAME> 2018");
Console.Write("source available at: ");
WriteWithUnderLine("https://www.github.com/sarangxyz/pswdgen", ConsoleColor.Green);
Console.WriteLine();
Console.WriteLine("usage: pswdgen <numchars>{opt} <numpswds>{opt}");
Console.WriteLine(" default will generate 5<numpswds> of 20<numchars> each");
Console.WriteLine();
int length = 20;
int numPasswords = 5;
if (args != null)
{
if (args.Length > 0)
length = Convert.ToInt32(args[0]);
if (args.Length > 1)
numPasswords = Convert.ToInt32(args[1]);
}
Console.WriteLine("------------------------Passwords------------------------\n");
Console.ForegroundColor = ConsoleColor.Yellow;
for (int idx = 0; idx < numPasswords; ++idx)
Console.WriteLine(RandomString(length));
}
finally
{
Console.ForegroundColor = currentForeGroundColor;
}
}
}
}
<file_sep>A handy utility to generate random passwords of varying length.
By default it will generate 5 passwords of 2o characters, but you can be configured to produce
longer or shorter passwords.

Eg: This will produce 10 passwords of 32 character length:
```
D:\blog> pswdgen.exe 32 10
A handy utility to generate random passwords
Copyright c <NAME> 2018
source available at: https://www.github.com/angeleno/pswdgen
usage: pswdgen <numchars>{opt} <numpswds>{opt}
default will generate 5<numpswds> of 20<numchars> each
------------------------Passwords------------------------
q0+aAZX_4s1#bbQ:MA?{ymfblwR+J?GU
&Y#E/W,N7?+{o}~C/^AmEp>Ft~tO1^tN
PVnRpiPXEb`!&)2EqSAHMQxHQVb<9b&Q
#Z{4PK(V9LG#ER:MA9ec~Rr73u!.+.RD
*StMPv+1DV!!o1+0P<TF3L)cK?`m2txc
2{o%1(~ngf?aZ/z0r{@ar/q0kS?I<&Q}
#g{8`?o$X{xZ*)}?@4RYcQ9BAsK6:FaZ
i^B>10}5Ho%!1:Wd7o8E6:xIz!#Xv8iO
yNh.%_s3sSc4qi`ksJ7AS4?j&Fq44^C6
cWQC:L}?T6w!}Xc+mUnfC%b@mz1ihav_
```
| c9c316100cadc59351c3c3db5501b0b819d739ad | [
"Markdown",
"C#"
] | 2 | C# | sarangxyz/pswdgen | 923db2a0e45818390d787a5fce73d8afb14b8305 | 55d4d05e64d26508329139c1fd7754e481d6e901 |
refs/heads/master | <repo_name>gioelevalori/ngbiblioteca<file_sep>/src/app/utenti/utenti-mod/utenti-mod.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UtentiModComponent } from './utenti-mod.component';
describe('UtentiModComponent', () => {
let component: UtentiModComponent;
let fixture: ComponentFixture<UtentiModComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ UtentiModComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(UtentiModComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/src/app/utenti/utenti.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UtentiModComponent } from './utenti-mod/utenti-mod.component';
import { UtentiListaComponent } from './utenti-lista/utenti-lista.component';
import { UtentiCreateComponent } from './utenti-create/utenti-create.component';
import { TableModule } from '@fundamental-ngx/core';
import { FormModule } from '@fundamental-ngx/core';
import { ButtonModule } from '@fundamental-ngx/core';
@NgModule({
declarations: [
UtentiModComponent,
UtentiListaComponent,
UtentiCreateComponent
],
imports: [
CommonModule,
TableModule,
FormModule,
ButtonModule
]
})
export class UtentiModule { }
<file_sep>/src/app/utenti/utenti-create/utenti-create.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-utenti-create',
templateUrl: './utenti-create.component.html',
styleUrls: ['./utenti-create.component.css']
})
export class UtentiCreateComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
<file_sep>/src/app/autori/autori-lista/autori-lista.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AutoriListaComponent } from './autori-lista.component';
describe('AutoriListaComponent', () => {
let component: AutoriListaComponent;
let fixture: ComponentFixture<AutoriListaComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ AutoriListaComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AutoriListaComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {UtentiListaComponent} from './utenti/utenti-lista/utenti-lista.component';
import {UtentiCreateComponent} from './utenti/utenti-create/utenti-create.component';
import {DataTableComponent} from './data-table/data-table.component';
const routes: Routes = [
{path: 'utenti', component: UtentiListaComponent},
{path: 'new-utenti', component: UtentiCreateComponent},
{path: 'table', component: DataTableComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/src/app/autori/autori-mod/autori-mod.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-autori-mod',
templateUrl: './autori-mod.component.html',
styleUrls: ['./autori-mod.component.css']
})
export class AutoriModComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
<file_sep>/src/app/autori/autori.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AutoriListaComponent } from './autori-lista/autori-lista.component';
import { AutoriCreateComponent } from './autori-create/autori-create.component';
import { AutoriModComponent } from './autori-mod/autori-mod.component';
@NgModule({
declarations: [
AutoriListaComponent,
AutoriCreateComponent,
AutoriModComponent
],
imports: [
CommonModule
]
})
export class AutoriModule { }
| 588b7fc1067a4374faf0559e4c054b81eac0e39f | [
"TypeScript"
] | 7 | TypeScript | gioelevalori/ngbiblioteca | 1d0863e73b180f6fb1782688776cc98f5f3dae3b | ef21bfc6a8746eecf277336a8b40a156169d981b |
refs/heads/master | <file_sep>module.exports = {
appId: 'wx3816e88e3c0c6c28',
appSecret: '<KEY>',
// host: 'https://www.sneptune.cn',
host: '172.16.58.3',
token: '<PASSWORD>'
};
// module.exports = {
// appId: 'wxcd0b833018b5cdc1',
// appSecret: '<KEY>',
// // host: 'https://www.sneptune.cn',
// host: '172.16.58.3',
// token: '<PASSWORD>'
// }
<file_sep># wx_authorize
wechat authorize
<file_sep>module.exports = {
apps : [{
name: 'wx_authorize',
script: 'bin/www',
// Options reference: https://pm2.io/doc/en/runtime/reference/ecosystem-file/
cwd: './',
watch: ['app/*', 'bin/*', 'config/*', 'app.js'],
watch_delay: 1000,
watch_options: {
followSymlinks: false,
usePolling: true
},
max_memory_restart: '1G',
env: {
NODE_ENV: 'development'
},
env_production: {
NODE_ENV: 'production'
}
}]
};
| 7b18a65ef21779f26d200536b4968358c177fe88 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | powercandy/wx_authorize | 32c71d9737a048ef8059ceb5cb256605547369ce | 8f9a3fe7ec3fb70f191225203731c42d84fd3802 |
refs/heads/master | <repo_name>nickKedro/eshop_project<file_sep>/js/script.js
$('.category').hover( function () {
setTimeout(function() {
$('.category > .subcategory').css({'display' : 'inline'});
}, 500);
},
function () {
var cursorPos = document.getElementsByClassName('category');
setTimeout(function() {
$('.category > .subcategory').css({'display' : 'none'});
}, 5000);
}
);
| 111e2f958a3bb847151f077e09c09a33280e0313 | [
"JavaScript"
] | 1 | JavaScript | nickKedro/eshop_project | 4b0673d2c043e38a8914e4af4a5d0395ca9bbc26 | 9eabc2e31d4c58300d27199db998ff47c6f3b987 |
refs/heads/master | <file_sep>sudo virsh net-start default
minikube delete
rm -rf ~/.minikube
minikube start --vm-driver kvm --memory 2000 --cpus 1 --disk-size 10g
helm install ./chart | 4bcd86d8873ae507a604c9088d7b4ef15c540c60 | [
"Shell"
] | 1 | Shell | efidel/kubernetes-ci-cd | b78753b389a2c0212687cee0b03896b423e5f4c6 | 0b8df809ebf87b59a93e061b1f0c8c01da8cbc42 |
refs/heads/master | <repo_name>rystills/N64-Rom-Disassembler<file_sep>/todo.py
'just pretend this string is not here'
''' ADDITIONS
A button for the jumps window which labels all jumps to a function using the function title comment.
A function optimiser which will condense a chosen function down to as little instructions as possible by removing
redundant code and modifying all code utilising redundant code.
A script for PJ64D to collect all callers to functions which this app has no jumps calculated for, then incorporate
collected data.
Some more documentation on each instruction, such as which parameter exactly is what.
(confusion with parameters of certain instructions such as MTC1 being back-to-front (compared to other instructions))
'''
''' CHANGES
Tweak jump mapping to be a little smarter. I aim to have it calculate target addresses for JR/JALR instructions if the
JR target is statically calculated.
Not sure if worth it/possible, due to "branch tables" and otherwise lack-thereof.
When cutting a section of code where branches target, modify the branches on paste so they still point to the same code.
Possibly could substitute with a hotkey such as Shift+Up/Down when selecting the branch target.
'''
''' BUGS
None I know of right now. I always fix bugs as soon as I encounter them and then commit the changes.
'''
''' MINOR KNOWN ISSUES
NOPs won't replace all blank lines straight away. However, the function which handles your changes will treat all
blank lines as NOP anyway.
Moving your mouse to the far-right of any text box and double-clicking that line will cause text on the following
line to become highlighted. This is a cause by something in the backend of TKinter, which I don't know how to change.
I have tried to fix this by simply moving the user's "selection start" and "selection end" cursors, but doing so
seems to corrupt the text boxes beyond repair so much that restarting the program is the only way to fix them.
Because of that, this has become part of the "too hard" pile.
Very rarely, "Calculate checksum when saving" will un-check itself. I really am stumped over what causes this.
For all I know, it's only happening to me during debugging. This is easy to notice when it has become un-checked,
as your rom will fail to boot if you have edited any part of the ROM between 0x1000 and 0xF5240.
Very rarely, something will cause any of the sub-windows such as comments navigator and script generation to not be
coloured properly when opening them, also throw a bunch of tkinter errors in the command prompt.
I have not been able to find the cause of this. It can be resolved by saving your work and restarting the program.
'''
| cc1ff9cf922ffa86b1f09b11ddd544dab1e35513 | [
"Python"
] | 1 | Python | rystills/N64-Rom-Disassembler | 3a1357f171efb0be3290ff5d3d7dd4642592833d | 23f79ec6fd274b41e5ed024f5d5796d06739346f |
refs/heads/master | <file_sep>//
// Generated By:JAX-WS RI IBM 2.1.1 in JDK 6 (JAXB RI IBM JAXB 2.1.3 in JDK 1.6)
//
package entitlement_v1.relationship.product.information.services.nm;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Subject complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Subject">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="SubjectNum" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="SubjNumSrcCde" type="{http://www.w3.org/2001/XMLSchema}short"/>
* <element name="SubjectTypeCde" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Subject", namespace = "http://nm.services.information.product.relationship.entitlement_v1", propOrder = {
"subjectNum",
"subjNumSrcCde",
"subjectTypeCde"
})
public class Subject {
@XmlElement(name = "SubjectNum", required = true)
protected String subjectNum;
@XmlElement(name = "SubjNumSrcCde")
protected short subjNumSrcCde;
@XmlElement(name = "SubjectTypeCde")
protected int subjectTypeCde;
/**
* Gets the value of the subjectNum property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSubjectNum() {
return subjectNum;
}
/**
* Sets the value of the subjectNum property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSubjectNum(String value) {
this.subjectNum = value;
}
/**
* Gets the value of the subjNumSrcCde property.
*
*/
public short getSubjNumSrcCde() {
return subjNumSrcCde;
}
/**
* Sets the value of the subjNumSrcCde property.
*
*/
public void setSubjNumSrcCde(short value) {
this.subjNumSrcCde = value;
}
/**
* Gets the value of the subjectTypeCde property.
*
*/
public int getSubjectTypeCde() {
return subjectTypeCde;
}
/**
* Sets the value of the subjectTypeCde property.
*
*/
public void setSubjectTypeCde(int value) {
this.subjectTypeCde = value;
}
}
<file_sep>package com.nm.edas.entitlementwebservice.dao;
import java.util.List;
import org.apache.log4j.Logger;
import com.nm.edas.entitlement.domain.EnterpriseEntitlementConstants;
import com.nm.edas.entitlement.domain.Entitlement;
import com.nm.edas.entitlement.domain.EntitlementRequest;
import com.nm.edas.entitlement.domain.Subject;
import com.nm.edas.entitlement.pab.EnterpriseEntitlementProcessAccess;
import com.nm.edas.entitlement.pab.EnterpriseEntitlementProcessAccessHome;
import com.nm.edas.entitlementwebservice.exception.EntitlementInputException;
import com.nm.edas.operatorlookup.domain.Operator;
public class EntitlementMasterDAOImpl implements EntitlementMasterDAO {
Logger logger = Logger.getLogger(EntitlementMasterDAOImpl.class);
public Entitlement getEntitlementData(String strMsgSenderApplId,
Operator operator,
String strFieldDataInd,
List<Subject> subjects) throws EntitlementInputException{
long start = System.currentTimeMillis();
Entitlement entitlement = null;
EnterpriseEntitlementProcessAccess entitlementPAB =
EnterpriseEntitlementProcessAccessHome.instance().getEnterpriseEntitlementProcessBean();
EntitlementRequest request = new EntitlementRequest();
request.setOperatorType(operator.getOperatorType());
request.setDistributorNums(operator.getDistributorNum());
request.setNoTerrNum(operator.getNoTerrNum());
request.setFieldDataInd(strFieldDataInd);
request.setMsgSenderApplId(strMsgSenderApplId);
request.setRuleSet(EnterpriseEntitlementConstants.SERVICING_READ_RULESET);
request.setSubjects(subjects);
entitlement = entitlementPAB.getEntitlementData(request);
for (Subject s : entitlement.getSubjects()){
if (s.getSubjectFoundInd().equals("N")){
//logger.debug(s.getSubjectNum() + " is not found");
StringBuffer errorStr = new StringBuffer();
errorStr.append("Invalid Input. Subject ");
errorStr.append(s.getSubjectNum() + "/" + s.getSubjectTypeCde() + "/" + s.getSubjNumSrcCde());
errorStr.append(" not found in Consolidated Client database.");
throw new EntitlementInputException(errorStr.toString());
}
}
logger.debug("getEntitlementData DAO method took " + (System.currentTimeMillis() - start) + "ms");
return entitlement;
}
}
<file_sep>entitlementws.initDelay=600000
entitlementws.pingInterval=900000
entitlementws.pingPCSubjectKey=99999999
entitlementws.log4jConfigRefreshMs=900000
entitlementws.log4jConfigFile=/nmlprod/edaserv/config/Entitlementws/log4j-prod.xml<file_sep>package com.nm.edas.entitlementwebservice.dao;
import java.util.List;
import com.nm.edas.entitlement.domain.Subject;
public interface SubjectEntitlementDAO {
public List<Subject> getSubjectEntitlement(List<Subject> subjects);
}
<file_sep>package com.nm.edas.entitlementwebservice.exception;
public class EntitlementInputException extends Exception {
/**
*
*/
private static final long serialVersionUID = -4903755493427703683L;
public EntitlementInputException(String message) {
super(message);
}
public EntitlementInputException(String message, Throwable cause) {
super(message, cause);
}
public EntitlementInputException(Throwable cause) {
super(cause);
}
}
<file_sep>//
// Generated By:JAX-WS RI IBM 2.1.1 in JDK 6 (JAXB RI IBM JAXB 2.1.3 in JDK 1.6)
//
package entitlement_v1.relationship.product.information.services.nm;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
import com.nm.dataserv.help.IObjectFactory;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the entitlement_v1.relationship.product.information.services.nm package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory implements IObjectFactory {
private final static QName _EntitlementData_QNAME = new QName("http://nm.services.information.product.relationship.entitlement_v1", "EntitlementData");
private final static QName _EntitlementWSException_QNAME = new QName("http://nm.services.information.product.relationship.entitlement_v1", "EntitlementWSException");
private final static QName _GetEntitlementData_QNAME = new QName("http://nm.services.information.product.relationship.entitlement_v1", "GetEntitlementData");
private final static QName _RoleOperRoleTypeCde_QNAME = new QName("", "OperRoleTypeCde");
private final static QName _RoleOperRoleSeqNum_QNAME = new QName("", "OperRoleSeqNum");
private final static QName _DistributorRoleTypeCde_QNAME = new QName("", "RoleTypeCde");
private final static QName _DistributorRoleSeqNum_QNAME = new QName("", "RoleSeqNum");
private final static QName _DistributorDistributorNum_QNAME = new QName("", "DistributorNum");
private final static QName _EntitlementOverallEntitlementInd_QNAME = new QName("", "OverallEntitlementInd");
private final static QName _SubjectEntitlementNetworkDsbNum_QNAME = new QName("", "NetworkDsbNum");
private final static QName _SubjectEntitlementEntitlementInd_QNAME = new QName("", "EntitlementInd");
private final static QName _SubjectEntitlementNoTerrNum_QNAME = new QName("", "NoTerrNum");
private final static QName _SubjectEntitlementJointWorkInd_QNAME = new QName("", "JointWorkInd");
private final static QName _SubjectEntitlementNetworkClientInd_QNAME = new QName("", "NetworkClientInd");
private final static QName _SubjectEntitlementSubjectNum_QNAME = new QName("", "SubjectNum");
private final static QName _SubjectEntitlementSubjNumSrcCde_QNAME = new QName("", "SubjNumSrcCde");
private final static QName _SubjectEntitlementSubjectTypeCde_QNAME = new QName("", "SubjectTypeCde");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: entitlement_v1.relationship.product.information.services.nm
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Keys }
*
*/
public Keys createKeys() {
return new Keys();
}
/**
* Create an instance of {@link EntitlementWSFault }
*
*/
public EntitlementWSFault createEntitlementWSFault() {
return new EntitlementWSFault();
}
/**
* Create an instance of {@link MsgHeader }
*
*/
public MsgHeader createMsgHeader() {
return new MsgHeader();
}
/**
* Create an instance of {@link Distributor }
*
*/
public Distributor createDistributor() {
return new Distributor();
}
/**
* Create an instance of {@link Role }
*
*/
public Role createRole() {
return new Role();
}
/**
* Create an instance of {@link Entitlement }
*
*/
public Entitlement createEntitlement() {
return new Entitlement();
}
/**
* Create an instance of {@link EntitlementData }
*
*/
public EntitlementData createEntitlementData() {
return new EntitlementData();
}
/**
* Create an instance of {@link ReplyFields }
*
*/
public ReplyFields createReplyFields() {
return new ReplyFields();
}
/**
* Create an instance of {@link GetEntitlementData }
*
*/
public GetEntitlementData createGetEntitlementData() {
return new GetEntitlementData();
}
/**
* Create an instance of {@link SubjectEntitlement }
*
*/
public SubjectEntitlement createSubjectEntitlement() {
return new SubjectEntitlement();
}
/**
* Create an instance of {@link Subject }
*
*/
public Subject createSubject() {
return new Subject();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link EntitlementData }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://nm.services.information.product.relationship.entitlement_v1", name = "EntitlementData")
public JAXBElement<EntitlementData> createEntitlementData(EntitlementData value) {
return new JAXBElement<EntitlementData>(_EntitlementData_QNAME, EntitlementData.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link EntitlementWSFault }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://nm.services.information.product.relationship.entitlement_v1", name = "EntitlementWSException")
public JAXBElement<EntitlementWSFault> createEntitlementWSException(EntitlementWSFault value) {
return new JAXBElement<EntitlementWSFault>(_EntitlementWSException_QNAME, EntitlementWSFault.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetEntitlementData }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://nm.services.information.product.relationship.entitlement_v1", name = "GetEntitlementData")
public JAXBElement<GetEntitlementData> createGetEntitlementData(GetEntitlementData value) {
return new JAXBElement<GetEntitlementData>(_GetEntitlementData_QNAME, GetEntitlementData.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Short }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "OperRoleTypeCde", scope = Role.class)
public JAXBElement<Short> createRoleOperRoleTypeCde(Short value) {
return new JAXBElement<Short>(_RoleOperRoleTypeCde_QNAME, Short.class, Role.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Short }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "OperRoleSeqNum", scope = Role.class)
public JAXBElement<Short> createRoleOperRoleSeqNum(Short value) {
return new JAXBElement<Short>(_RoleOperRoleSeqNum_QNAME, Short.class, Role.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Short }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "RoleTypeCde", scope = Distributor.class)
public JAXBElement<Short> createDistributorRoleTypeCde(Short value) {
return new JAXBElement<Short>(_DistributorRoleTypeCde_QNAME, Short.class, Distributor.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Short }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "RoleSeqNum", scope = Distributor.class)
public JAXBElement<Short> createDistributorRoleSeqNum(Short value) {
return new JAXBElement<Short>(_DistributorRoleSeqNum_QNAME, Short.class, Distributor.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "DistributorNum", scope = Distributor.class)
public JAXBElement<String> createDistributorDistributorNum(String value) {
return new JAXBElement<String>(_DistributorDistributorNum_QNAME, String.class, Distributor.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "OverallEntitlementInd", scope = Entitlement.class)
public JAXBElement<String> createEntitlementOverallEntitlementInd(String value) {
return new JAXBElement<String>(_EntitlementOverallEntitlementInd_QNAME, String.class, Entitlement.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "NetworkDsbNum", scope = SubjectEntitlement.class)
public JAXBElement<String> createSubjectEntitlementNetworkDsbNum(String value) {
return new JAXBElement<String>(_SubjectEntitlementNetworkDsbNum_QNAME, String.class, SubjectEntitlement.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "EntitlementInd", scope = SubjectEntitlement.class)
public JAXBElement<String> createSubjectEntitlementEntitlementInd(String value) {
return new JAXBElement<String>(_SubjectEntitlementEntitlementInd_QNAME, String.class, SubjectEntitlement.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "NoTerrNum", scope = SubjectEntitlement.class)
public JAXBElement<String> createSubjectEntitlementNoTerrNum(String value) {
return new JAXBElement<String>(_SubjectEntitlementNoTerrNum_QNAME, String.class, SubjectEntitlement.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "JointWorkInd", scope = SubjectEntitlement.class)
public JAXBElement<String> createSubjectEntitlementJointWorkInd(String value) {
return new JAXBElement<String>(_SubjectEntitlementJointWorkInd_QNAME, String.class, SubjectEntitlement.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "NetworkClientInd", scope = SubjectEntitlement.class)
public JAXBElement<String> createSubjectEntitlementNetworkClientInd(String value) {
return new JAXBElement<String>(_SubjectEntitlementNetworkClientInd_QNAME, String.class, SubjectEntitlement.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "SubjectNum", scope = SubjectEntitlement.class)
public JAXBElement<String> createSubjectEntitlementSubjectNum(String value) {
return new JAXBElement<String>(_SubjectEntitlementSubjectNum_QNAME, String.class, SubjectEntitlement.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Short }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "SubjNumSrcCde", scope = SubjectEntitlement.class)
public JAXBElement<Short> createSubjectEntitlementSubjNumSrcCde(Short value) {
return new JAXBElement<Short>(_SubjectEntitlementSubjNumSrcCde_QNAME, Short.class, SubjectEntitlement.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Integer }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "SubjectTypeCde", scope = SubjectEntitlement.class)
public JAXBElement<Integer> createSubjectEntitlementSubjectTypeCde(Integer value) {
return new JAXBElement<Integer>(_SubjectEntitlementSubjectTypeCde_QNAME, Integer.class, SubjectEntitlement.class, value);
}
}
<file_sep>package com.nm.edas.entitlementwebservice.pab;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.nm.dataserv.help.NameValuePair;
import com.nm.dataserv.mapper.DataMapper;
import com.nm.dataserv.pab.DataServiceProcessAccess;
import com.nm.dataserv.pab.DataServiceProcessAccessHome;
import com.nm.edas.entitlement.domain.Subject;
import com.nm.edas.entitlementwebservice.common.EntitlementServiceConstants;
import com.nm.edas.entitlementwebservice.common.EntitlementUtil;
import com.nm.edas.entitlementwebservice.exception.EntitlementInputException;
import com.nm.edas.entitlementwebservice.exception.EntitlementServiceException;
import com.nm.edas.exception.ExceptionUtils;
import com.nm.edas.operatorlookup.domain.Operator;
import com.nm.edas.operatorlookup.pab.OperatorLookupProcessAccess;
import com.nm.edas.operatorlookup.pab.OperatorLookupProcessAccessHome;
import entitlement_v1.relationship.product.information.services.nm.Entitlement;
import entitlement_v1.relationship.product.information.services.nm.MsgHeader;
import entitlement_v1.relationship.product.information.services.nm.ObjectFactory;
import entitlement_v1.relationship.product.information.services.nm.ReplyFields;
public class EntitlementProcessAccessBean implements EntitlementProcessAccess {
private final static EntitlementProcessAccess instance =
new EntitlementProcessAccessBean();
private static Logger logger = Logger.getLogger(EntitlementProcessAccessBean.class);
private static ObjectFactory factory = new ObjectFactory();
private static OperatorLookupProcessAccess operatorLookupPAB;
private static DataServiceProcessAccess dataServicePAB;
private EntitlementProcessAccessBean() {
operatorLookupPAB =
OperatorLookupProcessAccessHome.instance().getOperatorLookupProcessBean();
dataServicePAB =
DataServiceProcessAccessHome.instance().getDataServiceProcessAccessBean();
/*DOMConfigurator.configureAndWatch(
EntitlementServiceConstants.LOG4J_CONFIG_FILE,
EntitlementServiceConstants.LOG4J_CONFIG_REFRESH_INTERVAL_MS);*/
}
public static EntitlementProcessAccess instance() {
return instance;
}
public Entitlement getEntitlementData(MsgHeader msgHeader, List<Subject> subjects, ReplyFields replyFields)
throws EntitlementInputException, EntitlementServiceException {
List<NameValuePair> entitlementReply = null;
Entitlement entitlementResponse = new Entitlement();
long start = 0;
try{
//call the operator lookup to fetch the operator details
Operator operator =
operatorLookupPAB.getOperatorData(msgHeader.getMsgClientOperId());
//Get the list of fields required in entitlement reply
start = System.currentTimeMillis();
List<NameValuePair> requiredFieldsList = DataMapper.unmarshall(replyFields.getEntitlement());
logger.info("Requested Fields " + requiredFieldsList);
logger.debug("Unmarshalling request took " + (System.currentTimeMillis() - start) + "ms");
if (requiredFieldsList.size() == 0){
String errorMsg = "Invalid input. ReplyFields list is empty.";
throw new EntitlementInputException(errorMsg);
}
//Determine if any field data is requested for the subjects
String strFieldDataInd = EntitlementUtil.getFieldDataInd(requiredFieldsList);
logger.debug("FieldDataInd " + strFieldDataInd);
//Prepare for the DAO call
com.nm.edas.entitlement.domain.Entitlement entitlementSkeleton =
new com.nm.edas.entitlement.domain.Entitlement();
Map<String, Object> keyMap = new HashMap<String, Object>();
keyMap.put("Subjects", subjects);
keyMap.put("Operator", operator);
keyMap.put("MsgSenderApplId", msgHeader.getMsgSenderApplId());
keyMap.put("FieldDataInd", strFieldDataInd);
com.nm.edas.entitlement.domain.Entitlement entitlement =
(com.nm.edas.entitlement.domain.Entitlement)dataServicePAB.callDAOMethod(
EntitlementServiceConstants.ENTITLEMENT_REPY_BASE_LEVEL,
keyMap,
entitlementSkeleton);
entitlementReply = dataServicePAB.retrieveData(requiredFieldsList,
keyMap,
entitlement,
System.currentTimeMillis() + EntitlementServiceConstants.TIME_TO_RUN);
//Marshall the reply
start = System.currentTimeMillis();
DataMapper.marshall(entitlementResponse, entitlementReply, factory);
logger.debug("Marshalling reply took " + (System.currentTimeMillis() - start) + "ms");
}catch(InvocationTargetException e){
Throwable t = ExceptionUtils.getRootCause(e);
if (t instanceof EntitlementInputException){
logger.debug("Subject not found exception from entitlementMasterDAO");
throw new EntitlementInputException(t);
}else{
throw new EntitlementServiceException(t);
}
}
return entitlementResponse;
}
}
<file_sep>package entitlement_v1.relationship.product.information.services.nm;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.nm.edas.entitlementwebservice.common.EntitlementServiceConstants;
import com.nm.edas.entitlementwebservice.common.EntitlementUtil;
import com.nm.edas.entitlementwebservice.exception.EntitlementInputException;
import com.nm.edas.entitlementwebservice.exception.EntitlementServiceException;
import com.nm.edas.entitlementwebservice.exception.ExceptionHelper;
import com.nm.edas.entitlementwebservice.pab.EntitlementProcessAccess;
import com.nm.edas.entitlementwebservice.pab.EntitlementProcessAccessHome;
import com.nm.edas.log4j.EDMTimeLogData;
import com.nm.edas.thread.ParentThreadContext;
@javax.jws.HandlerChain(file="../../../../../../handlers.xml")
@javax.jws.WebService (endpointInterface="entitlement_v1.relationship.product.information.services.nm.GetEntitlementDataInterface", targetNamespace="http://nm.services.information.product.relationship.entitlement_v1", serviceName="GetEntitlementData_v1", portName="GetEntitlementDataServicePort")
public class GetEntitlementDataServicePortBindingImpl{
private static Logger logger = Logger.getLogger(GetEntitlementDataServicePortBindingImpl.class);
private static Logger timeLogger = Logger.getLogger("TimingsLogger");
private static EntitlementProcessAccess entitlementPAB =
EntitlementProcessAccessHome.instance().getEntitlementProcessAccessBean();
public Entitlement getEntitlementData(MsgHeader msgHeader, Keys keys, ReplyFields replyFields) throws EntitlementWSException {
logger.info("Recieved GetEntitlementData request");
Integer keyCnt = 0;
StringBuffer subjKey = new StringBuffer();
Entitlement entitlement = null;
EDMTimeLogData timeLogData = new EDMTimeLogData();
String strMsgSenderApplId = null;
String strMsgClientOperId = null;
try{
if (msgHeader == null){
String errorMsg = "Invalid input parameter. MsgHeader is not passed in request.";
throw new EntitlementInputException(errorMsg);
}else if (keys == null){
String errorMsg = "Invalid input parameter. Keys is not passed in request.";
throw new EntitlementInputException(errorMsg);
}else if (replyFields == null || replyFields.getEntitlement() == null){
String errorMsg = "Invalid input parameter. ReplyFields list is not passed in request.";
throw new EntitlementInputException(errorMsg);
}
strMsgSenderApplId = msgHeader.getMsgSenderApplId();
strMsgClientOperId = msgHeader.getMsgClientOperId();
if (EntitlementUtil.isEmpty(strMsgSenderApplId)){
String errorMsg = "Invalid input parameter. MsgSenderApplId is not passed in the request.";
throw new EntitlementInputException(errorMsg);
}else if(EntitlementUtil.isEmpty(strMsgClientOperId)){
String errorMsg = "Invalid input parameter. MsgClientOperId is not passed in the request.";
throw new EntitlementInputException(errorMsg);
}
//Read the input keys
List<Subject> subjectKeys = keys.getSubject();
keyCnt = subjectKeys.size();
if (keyCnt == 0){
String errorMsg = "Invalid input parameter. No subjects passed in the request.";
throw new EntitlementInputException(errorMsg);
}
List<com.nm.edas.entitlement.domain.Subject> subjects =
new ArrayList<com.nm.edas.entitlement.domain.Subject>();
for (Subject s: subjectKeys){
if (EntitlementUtil.isEmpty(s.getSubjectNum())){
String errorMsg = "Invalid input parameter. Subject with blank SubjectNum.";
throw new EntitlementInputException(errorMsg);
}else if (Integer.valueOf(s.getSubjectTypeCde()) == null){
String errorMsg = "Invalid input parameter. Subject with blank or invalid SubjectTypeCde.";
throw new EntitlementInputException(errorMsg);
}else if (Integer.valueOf(s.getSubjNumSrcCde()) == null){
String errorMsg = "Invalid input parameter. Subject with blank or invalid SubjNumSrcCde.";
throw new EntitlementInputException(errorMsg);
}
com.nm.edas.entitlement.domain.Subject subject =
new com.nm.edas.entitlement.domain.Subject();
subject.setSubjectNum(s.getSubjectNum());
subject.setSubjectTypeCde(s.getSubjectTypeCde());
subject.setSubjNumSrcCde(s.getSubjNumSrcCde());
subjects.add(subject);
if (subjKey.length() == 0){
subjKey.append(s.getSubjectNum() + "/" + s.getSubjectTypeCde() + "/" + s.getSubjNumSrcCde());
}else{
subjKey.append(",");
subjKey.append(s.getSubjectNum() + "/" + s.getSubjectTypeCde() + "/" + s.getSubjNumSrcCde());
}
}
entitlement = entitlementPAB.getEntitlementData(msgHeader, subjects, replyFields);
} catch (EntitlementInputException e){
logger.error(e.getStackTrace());
throw ExceptionHelper.createEntitlementWSException(e, "INVALID INPUT", "ENTWS001");
} catch (EntitlementServiceException e) {
logger.error(e.getStackTrace());
throw ExceptionHelper.createEntitlementWSException(e, "SERVICE INTERNAL EXCEPTION", "ENTWS002");
} catch (Throwable t) {
logger.error(t.getStackTrace());
throw ExceptionHelper.createEntitlementWSException(t, "UNHANDLED EXCEPTION", "ENTWS003");
}finally{
timeLogData.addRequiredFields(strMsgSenderApplId,
strMsgClientOperId,
EntitlementServiceConstants.GETENTITLEMENTDATA_REQUEST_NAME,
EntitlementServiceConstants.VERSION_V1,
EntitlementServiceConstants.SERVICE_NAME,
keyCnt.toString(),
subjKey.toString(),
ParentThreadContext.getMessageId());
timeLogger.info(timeLogData);
}
logger.info("Sending the EntitlementData response");
return entitlement;
}
}<file_sep>package com.nm.edas.entitlementwebservice.dao;
import java.util.List;
import com.nm.edas.entitlement.domain.Distributor;
public class SubjectDistributorDAOImpl implements SubjectDistributorDAO {
public List<Distributor> getSubjectDistributor(List<Distributor> distributors){
return distributors;
}
}
<file_sep>package com.nm.edas.entitlementwebservice.dao;
import java.util.List;
import com.nm.edas.entitlement.domain.Distributor;
public interface SubjectDistributorDAO {
public List<Distributor> getSubjectDistributor(List<Distributor> distributors);
}
<file_sep>entitlementws.initDelay=600000
entitlementws.pingInterval=900000
entitlementws.pingPCSubjectKey=99999999
entitlementws.log4jConfigRefreshMs=900000
entitlementws.log4jConfigFile=/nmltest/edaserv/config/Entitlementws/log4j-test.xml<file_sep>//
// Generated By:JAX-WS RI IBM 2.1.1 in JDK 6 (JAXB RI IBM JAXB 2.1.3 in JDK 1.6)
//
package entitlement_v1.relationship.product.information.services.nm;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
@WebService(name = "GetEntitlementDataInterface", targetNamespace = "http://nm.services.information.product.relationship.entitlement_v1")
@XmlSeeAlso({
ObjectFactory.class
})
public interface GetEntitlementDataInterface {
/**
*
* @param replyFields
* @param keys
* @param msgHeader
* @return
* returns entitlement_v1.relationship.product.information.services.nm.Entitlement
* @throws EntitlementWSException
*/
@WebMethod(operationName = "GetEntitlementData")
@WebResult(name = "Entitlement", targetNamespace = "")
@RequestWrapper(localName = "GetEntitlementData", targetNamespace = "http://nm.services.information.product.relationship.entitlement_v1", className = "entitlement_v1.relationship.product.information.services.nm.GetEntitlementData")
@ResponseWrapper(localName = "EntitlementData", targetNamespace = "http://nm.services.information.product.relationship.entitlement_v1", className = "entitlement_v1.relationship.product.information.services.nm.EntitlementData")
public Entitlement getEntitlementData(
@WebParam(name = "MsgHeader", targetNamespace = "")
MsgHeader msgHeader,
@WebParam(name = "Keys", targetNamespace = "")
Keys keys,
@WebParam(name = "ReplyFields", targetNamespace = "")
ReplyFields replyFields)
throws EntitlementWSException
;
}
<file_sep>entitlementws.initDelay=600000
entitlementws.pingInterval=900000
entitlementws.pingPCSubjectKey=99999999
entitlementws.log4jConfigRefreshMs=900000
entitlementws.log4jConfigFile=C:/edas/edaserv/EntitlementWebService/config/log4j.xml<file_sep>package com.nm.edas.entitlementwebservice.common;
import java.util.List;
import java.util.ArrayList;
import com.nm.dataserv.help.NameValuePair;
import entitlement_v1.relationship.product.information.services.nm.Entitlement;
import entitlement_v1.relationship.product.information.services.nm.ReplyFields;
import entitlement_v1.relationship.product.information.services.nm.ObjectFactory;
import entitlement_v1.relationship.product.information.services.nm.SubjectEntitlement;
public class EntitlementUtil {
private static ReplyFields replyFields = null;
@SuppressWarnings("unchecked")
public static String getFieldDataInd(List<NameValuePair> reqFieldsList){
String fieldDataInd = "N";
for (NameValuePair entField : reqFieldsList){
if (entField.getKey().toString().equals("SubjectEntitlement")){
List<NameValuePair> subjFields = (List<NameValuePair>) entField.getValue();
for (NameValuePair subjField : subjFields){
if (subjField.getKey().toString().equals("Role") ||
subjField.getKey().toString().equals("NoTerrNum") ||
subjField.getKey().toString().equals("Distributor")){
fieldDataInd = "Y";
break;
}
}
break;
}
}
return fieldDataInd;
}
public static boolean isSubjectTypeCdeValid(int iSubjectTypeCde){
boolean valid = true;
if (Integer.valueOf(iSubjectTypeCde) == null){
valid = false;
}
if (iSubjectTypeCde != 2 && iSubjectTypeCde != 3 && iSubjectTypeCde != 4 &&
iSubjectTypeCde != 5 && iSubjectTypeCde != 6 && iSubjectTypeCde != 26)
valid = false;
return valid;
}
public static boolean isSubjNumSrcCdeValid(short iSubjNumSrcCde){
boolean valid = true;
if (Integer.valueOf(iSubjNumSrcCde) == null){
valid = false;
}
if (iSubjNumSrcCde != 3 && iSubjNumSrcCde != 4 &&
iSubjNumSrcCde != 5 && iSubjNumSrcCde != 6 && iSubjNumSrcCde != 20)
valid = false;
return valid;
}
public static boolean isEmpty(String str){
boolean empty = false;
if (str == null || str.equals(""))
empty = true;
return empty;
}
public static ReplyFields getReplyFields(){
if (replyFields == null){
ObjectFactory factory = new ObjectFactory();
SubjectEntitlement subjEnt = factory.createSubjectEntitlement();
subjEnt.setSubjectNum(factory.createSubjectEntitlementSubjectNum(null));
subjEnt.getSubjectNum().setNil(true);
subjEnt.setSubjectTypeCde(factory.createSubjectEntitlementSubjectTypeCde(null));
subjEnt.getSubjectTypeCde().setNil(true);
subjEnt.setSubjNumSrcCde(factory.createSubjectEntitlementSubjNumSrcCde(null));
subjEnt.getSubjNumSrcCde().setNil(true);
subjEnt.setEntitlementInd(factory.createSubjectEntitlementEntitlementInd(null));
subjEnt.getEntitlementInd().setNil(true);
Entitlement entitlement = factory.createEntitlement();
entitlement.getSubjectEntitlement().add(subjEnt);
replyFields = factory.createReplyFields();
replyFields.setEntitlement(entitlement);
}
return replyFields;
}
}
<file_sep>entitlementws.initDelay=600000
entitlementws.pingInterval=900000
entitlementws.pingPCSubjectKey=99999999
entitlementws.log4jConfigRefreshMs=900000
entitlementws.log4jConfigFile=/nmlstage/edaserv/config/Entitlementws/log4j-stage.xml<file_sep>package com.nm.edas.entitlementwebservice.exception;
import com.nm.edas.exception.ExceptionUtils;
import entitlement_v1.relationship.product.information.services.nm.EntitlementWSException;
import entitlement_v1.relationship.product.information.services.nm.EntitlementWSFault;
public class ExceptionHelper {
public static EntitlementWSException createEntitlementWSException(Throwable cause, String message, String faultId) {
EntitlementWSFault fault = new EntitlementWSFault();
Throwable rootcause = ExceptionUtils.getRootCause(cause);
fault.setID(faultId);
fault.setMessage(cause.getMessage());
fault.setCauseMessage(rootcause.getMessage());
fault.setCauseException(rootcause.getClass().getName());
EntitlementWSException exception = new EntitlementWSException(message, fault);
return exception;
}
}
<file_sep><?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE project [
<!ENTITY standard SYSTEM "W:/appls/ANT/TFS/ECC_BUILD_V2.3.TFS.xml">
]>
<project name="AutoBuild" default="test" basedir=".">
<!-- include the standard ECC_BUILD.xml assembly logic -->
<property file="build.properties"/>
&standard;
<typedef resource="com/teamprise/ant/antlib.xml" classpath=" W:/appls/ANT/TFS/teamprise-ant-1.2.jar" />
<path id="application">
<fileset dir="${entitlementear.project.workspace.directory}">
<include name="*.jar"/>
</fileset>
<fileset dir="${lib.plugins}">
<include name="**/*.jar"/>
</fileset>
<fileset dir="${lib.runtimes}">
<include name="**/*.jar"/>
</fileset>
</path>
<tstamp>
<format property="tstamped-file-name" pattern="yyyyMMdd hh:mm aa" locale="en,UK"/>
</tstamp>
<target name="verifyLabelExists">
<condition property="label.present">
<and>
<equals arg1="${label}" arg2=""/>
</and>
</condition>
<fail if="label.present">
A label must be provided via the command line -Dlabel=<tfs label> parameter.
</fail>
</target>
<target name="makeDeployDir">
<mkdir dir="${project.destination.directory}"/>
</target>
<target name="getConfigDir">
<tfsget localpath="${entitlementconfig.project.workspace.directory}" version="L${label}" force="true" />
</target>
<target name="buildall">
<antcall target="makeDeployDir"/>
<antcall target="test"/>
<antcall target="stage"/>
<antcall target="production"/>
<antcall target="int"/>
<antcall target="test1"/>
</target>
<target name="testConfig" description="Build TEST Config">
<copy file="${project.build.directory}/${java.dest.directory}/log4j.xml"
toFile="${project.destination.directory}/log4j-test.xml"
overWrite="true"/>
<copy file="${entitlementconfig.project.workspace.directory}/entitlementws.properties"
toFile="${project.destination.directory}/entitlementws-test.properties"
overWrite="true"/>
<replace file="${project.destination.directory}/entitlementws-test.properties">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/config/log4j.xml]]></replacetoken>
<replacevalue><![CDATA[/nmltest/edaserv/config/Entitlementws/log4j-test.xml]]></replacevalue>
</replace>
</target>
<target name="stageConfig" description="Build STAGE Config">
<copy file="${project.build.directory}/${java.dest.directory}/log4j.xml"
toFile="${project.destination.directory}/log4j-stage.xml"
overWrite="true"/>
<copy file="${entitlementconfig.project.workspace.directory}/entitlementws.properties"
toFile="${project.destination.directory}/entitlementws-stage.properties"
overWrite="true"/>
<replace file="${project.destination.directory}/entitlementws-stage.properties">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/config/log4j.xml]]></replacetoken>
<replacevalue><![CDATA[/nmlstage/edaserv/config/Entitlementws/log4j-stage.xml]]></replacevalue>
</replace>
</target>
<target name="productionConfig" description="Build PRODUCTION Config">
<copy file="${project.build.directory}/${java.dest.directory}/log4j.xml"
toFile="${project.destination.directory}/log4j-prod.xml"
overWrite="true"/>
<copy file="${entitlementconfig.project.workspace.directory}/entitlementws.properties"
toFile="${project.destination.directory}/entitlementws-prod.properties"
overWrite="true"/>
<replace file="${project.destination.directory}/entitlementws-prod.properties">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/config/log4j.xml]]></replacetoken>
<replacevalue><![CDATA[/nmlprod/edaserv/config/Entitlementws/log4j-prod.xml]]></replacevalue>
</replace>
</target>
<target name="intConfig" description="Build INT Config">
<copy file="${project.build.directory}/${java.dest.directory}/log4j.xml"
toFile="${project.destination.directory}/log4j-int.xml"
overWrite="true"/>
<copy file="${entitlementconfig.project.workspace.directory}/entitlementws.properties"
toFile="${project.destination.directory}/entitlementws-int.properties"
overWrite="true"/>
<replace file="${project.destination.directory}/entitlementws-int.properties">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/config/log4j.xml]]></replacetoken>
<replacevalue><![CDATA[/nmltest/edaserv/int/config/Entitlementws/log4j-int.xml]]></replacevalue>
</replace>
</target>
<target name="test1Config" description="Build TEST1 Config">
<copy file="${project.build.directory}/${java.dest.directory}/log4j.xml"
toFile="${project.destination.directory}/log4j-test1.xml"
overWrite="true"/>
<copy file="${entitlementconfig.project.workspace.directory}/entitlementws.properties"
toFile="${project.destination.directory}/entitlementws-test1.properties"
overWrite="true"/>
<replace file="${project.destination.directory}/entitlementws-test1.properties">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/config/log4j.xml]]></replacetoken>
<replacevalue><![CDATA[/nmltest/edaserv/test1/config/Entitlementws/log4j-test1.xml]]></replacevalue>
</replace>
</target>
<target name="test" description="Build TEST Entitlement Web Service EAR">
<record name="${project.destination.directory}/${buildlog.test.name}" action="start" append="no"/>
<echo message="Build started on: ${tstamped-file-name}"/>
<echo message="Built by : ${user.name}"/>
<echo message="Java version : ${java.version}"/>
<echo message="Project label : ${label}"/>
<echo message="Java source : ${java.source}"/>
<echo message="Java target : ${java.target}"/>
<buildear prefix="entitlementear"
outputName="${enterprise.archive.unixid}-${enterprise.archive.applicationid}-Test.ear"
environment="Test"
compileDebug="true"
includeSource="true">
<postpvcs>
<delete file="${entitlementear.project.workspace.directory}/.project"/>
<delete file="${entitlementear.project.workspace.directory}/.compatibility"/>
</postpvcs>
<buildwar prefix="entitlement"
outputName="${entitlement.war.name}"
environment="Test"
compileDebug="true"
includeSource="true">
<postpvcs>
<mkdir dir="${entitlement.project.workspace.directory}/${project.web.directory}/${java.dest.directory}"/>
<mkdir dir="${entitlement.project.workspace.directory}/${project.lib.directory}"/>
<delete file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/lib/jconn3.jar"/>
</postpvcs>
<postcompile>
<replace file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/ibm-web-bnd.xml">
<replacetoken><![CDATA[default_host]]></replacetoken>
<replacevalue><![CDATA[field_host]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/log4j.xml">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/logs]]></replacetoken>
<replacevalue><![CDATA[/nmlwaslocal/edaserv/logs/Entitlementws]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/Entitlement_Spring.xml">
<replacetoken><![CDATA[//hotest/dfs02t/nmltest]]></replacetoken>
<replacevalue><![CDATA[/nmlstage]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/Entitlement_Spring.xml">
<replacetoken><![CDATA[ENTWSRVT]]></replacetoken>
<replacevalue><![CDATA[ENTWSRVS]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/spring.xml">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/config/entitlementws.properties]]></replacetoken>
<replacevalue><![CDATA[/nmltest/edaserv/config/Entitlementws/entitlementws-test.properties]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[LDAP_DEV]]></replacetoken>
<replacevalue><![CDATA[LDAP_TEST]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[//hotest/dfs02t/nmltest]]></replacetoken>
<replacevalue><![CDATA[/nmltest]]></replacevalue>
</replace>
<copy file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_internal.wsdl"
toFile="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_TEST_EP_internal.wsdl"
overWrite="true"/>
<replace file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_TEST_EP_internal.wsdl">
<replacetoken><![CDATA[localhost:9081]]></replacetoken>
<replacevalue><![CDATA[ws41.nml.com]]></replacevalue>
</replace>
<delete file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_internal.wsdl"/>
<copy file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_exposed.wsdl"
toFile="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_TEST_EP_exposed.wsdl"
overWrite="true"/>
<replace file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_TEST_EP_exposed.wsdl">
<replacetoken><![CDATA[localhost:9081]]></replacetoken>
<replacevalue><![CDATA[ws41test.nml.com]]></replacevalue>
</replace>
<delete file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_exposed.wsdl"/>
</postcompile>
</buildwar>
</buildear>
<delete file="${project.destination.directory}/${entitlement.war.name}"/>
<exec executable="cmd" output="${project.destination.directory}/${buildlog.test.name}" append="true">
<!-- C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE must be on your system %PATH% -->
<arg value="/c"/>
<arg value="tf.exe"/>
<arg value="Labels"/>
<arg value="/collection:ntdbph4966m00\INFRA"/>
<arg value="${label}"/>
<arg value="/format:detailed"/>
<arg value="/owner:*"/>
</exec>
<zip destfile="${project.destination.directory}/${enterprise.archive.unixid}-${enterprise.archive.applicationid}-Test.ear"
basedir="${project.destination.directory}"
includes="${buildlog.test.name}"
update="true"/>
<antcall target="getConfigDir"/>
<antcall target="testConfig"/>
<record name="${project.destination.directory}/${buildlog.test.name}" action="stop"/>
<echo message="PLEASE REMEMBER TO UPDATE THE CONFIG DIRECTORY IF THERE WERE ANY CONFIG CHANGES"/>
</target>
<target name="stage" description="Build STAGE Entitlement Web Service EAR">
<record name="${project.destination.directory}/${buildlog.stage.name}" action="start" append="no"/>
<echo message="Build started on: ${tstamped-file-name}"/>
<echo message="Built by : ${user.name}"/>
<echo message="Java version : ${java.version}"/>
<echo message="Project label : ${label}"/>
<echo message="Java source : ${java.source}"/>
<echo message="Java target : ${java.target}"/>
<buildear prefix="entitlementear"
outputName="${enterprise.archive.unixid}-${enterprise.archive.applicationid}-Stage.ear"
environment="Stage"
compileDebug="false"
includeSource="false">
<postpvcs>
<delete file="${entitlementear.project.workspace.directory}/.project"/>
<delete file="${entitlementear.project.workspace.directory}/.compatibility"/>
</postpvcs>
<buildwar prefix="entitlement"
outputName="${entitlement.war.name}"
environment="Stage"
compileDebug="false"
includeSource="false">
<postpvcs>
<mkdir dir="${entitlement.project.workspace.directory}/${project.web.directory}/${java.dest.directory}"/>
<mkdir dir="${entitlement.project.workspace.directory}/${project.lib.directory}"/>
<delete file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/lib/jconn3.jar"/>
</postpvcs>
<postcompile>
<replace file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/ibm-web-bnd.xml">
<replacetoken><![CDATA[default_host]]></replacetoken>
<replacevalue><![CDATA[field_host]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/log4j.xml">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/logs]]></replacetoken>
<replacevalue><![CDATA[/nmlwaslocal/edaserv/logs/Entitlementws]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/log4j.xml">
<replacetoken><![CDATA[<root><level value="Debug"]]></replacetoken>
<replacevalue><![CDATA[<root><level value="Info"]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/Entitlement_Spring.xml">
<replacetoken><![CDATA[//hotest/dfs02t/nmltest]]></replacetoken>
<replacevalue><![CDATA[/nmlstage]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/Entitlement_Spring.xml">
<replacetoken><![CDATA[ENTWSRVT]]></replacetoken>
<replacevalue><![CDATA[ENTWSRVS]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/spring.xml">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/config/entitlementws.properties]]></replacetoken>
<replacevalue><![CDATA[/nmlstage/edaserv/config/Entitlementws/entitlementws-stage.properties]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[LDAP_DEV]]></replacetoken>
<replacevalue><![CDATA[LDAP_TEST]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[//hotest/dfs02t/nmltest]]></replacetoken>
<replacevalue><![CDATA[/nmlstage]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[ENTWSRVT]]></replacetoken>
<replacevalue><![CDATA[ENTWSRVS]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[DIV13]]></replacetoken>
<replacevalue><![CDATA[DIV11]]></replacevalue>
</replace>
<copy file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_internal.wsdl"
toFile="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_STAGE_EP_internal.wsdl"
overWrite="true"/>
<replace file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_STAGE_EP_internal.wsdl">
<replacetoken><![CDATA[localhost:9081]]></replacetoken>
<replacevalue><![CDATA[ws41stage.nml.com]]></replacevalue>
</replace>
<delete file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_internal.wsdl"/>
<copy file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_exposed.wsdl"
toFile="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_STAGE_EP_exposed.wsdl"
overWrite="true"/>
<replace file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_STAGE_EP_exposed.wsdl">
<replacetoken><![CDATA[localhost:9081]]></replacetoken>
<replacevalue><![CDATA[ws41.nml.com]]></replacevalue>
</replace>
<delete file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_exposed.wsdl"/>
</postcompile>
</buildwar>
</buildear>
<delete file="${project.destination.directory}/${entitlement.war.name}"/>
<exec executable="cmd" output="${project.destination.directory}/${buildlog.stage.name}" append="true">
<!-- C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE must be on your system %PATH% -->
<arg value="/c"/>
<arg value="tf.exe"/>
<arg value="Labels"/>
<arg value="/collection:ntdbph4966m00\INFRA"/>
<arg value="${label}"/>
<arg value="/format:detailed"/>
<arg value="/owner:*"/>
</exec>
<zip destfile="${project.destination.directory}/${enterprise.archive.unixid}-${enterprise.archive.applicationid}-Stage.ear"
basedir="${project.destination.directory}"
includes="${buildlog.stage.name}"
update="true"
/>
<antcall target="getConfigDir"/>
<antcall target="stageConfig"/>
<record name="${project.destination.directory}/${buildlog.stage.name}" action="stop"/>
<echo message="PLEASE REMEMBER TO UPDATE THE CONFIG DIRECTORY IF THERE WERE ANY CONFIG CHANGES"/>
</target>
<target name="production" description="Build PRODUCTION Entitlement Web Service EAR">
<record name="${project.destination.directory}/${buildlog.prod.name}" action="start" append="no"/>
<echo message="Build started on: ${tstamped-file-name}"/>
<echo message="Built by : ${user.name}"/>
<echo message="Java version : ${java.version}"/>
<echo message="Project label : ${label}"/>
<echo message="Java source : ${java.source}"/>
<echo message="Java target : ${java.target}"/>
<buildear prefix="entitlementear"
outputName="${enterprise.archive.unixid}-${enterprise.archive.applicationid}-Prod.ear"
environment="Prod"
compileDebug="false"
includeSource="false">
<postpvcs>
<delete file="${entitlementear.project.workspace.directory}/.project"/>
<delete file="${entitlementear.project.workspace.directory}/.compatibility"/>
</postpvcs>
<buildwar prefix="entitlement"
outputName="${entitlement.war.name}"
environment="Prod"
compileDebug="false"
includeSource="false">
<postpvcs>
<mkdir dir="${entitlement.project.workspace.directory}/${project.web.directory}/${java.dest.directory}"/>
<mkdir dir="${entitlement.project.workspace.directory}/${project.lib.directory}"/>
<delete file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/lib/jconn3.jar"/>
</postpvcs>
<postcompile>
<replace file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/ibm-web-bnd.xml">
<replacetoken><![CDATA[default_host]]></replacetoken>
<replacevalue><![CDATA[field_host]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/log4j.xml">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/logs]]></replacetoken>
<replacevalue><![CDATA[/nmlwaslocal/edaserv/logs/Entitlementws]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/log4j.xml">
<replacetoken><![CDATA[<root><level value="Debug"]]></replacetoken>
<replacevalue><![CDATA[<root><level value="Info"]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/Entitlement_Spring.xml">
<replacetoken><![CDATA[//hotest/dfs02t/nmltest]]></replacetoken>
<replacevalue><![CDATA[/nmlprod]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/Entitlement_Spring.xml">
<replacetoken><![CDATA[ENTWSRVT]]></replacetoken>
<replacevalue><![CDATA[ENTWSRVP]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/spring.xml">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/config/entitlementws.properties]]></replacetoken>
<replacevalue><![CDATA[/nmlprod/edaserv/config/Entitlementws/entitlementws-prod.properties]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[LDAP_TEST]]></replacetoken>
<replacevalue><![CDATA[LDAP_PROD]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[LDAP_DEV]]></replacetoken>
<replacevalue><![CDATA[LDAP_PROD]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[//hotest/dfs02t/nmltest]]></replacetoken>
<replacevalue><![CDATA[/nmlprod]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[ENTWSRVT]]></replacetoken>
<replacevalue><![CDATA[ENTWSRVP]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[DIV13]]></replacetoken>
<replacevalue><![CDATA[DIV12]]></replacevalue>
</replace>
<copy file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_internal.wsdl"
toFile="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_PROD_EP_internal.wsdl"
overWrite="true"/>
<replace file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_PROD_EP_internal.wsdl">
<replacetoken><![CDATA[localhost:9081]]></replacetoken>
<replacevalue><![CDATA[ws41.nml.com]]></replacevalue>
</replace>
<delete file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_internal.wsdl"/>
<copy file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_exposed.wsdl"
toFile="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_PROD_EP_exposed.wsdl"
overWrite="true"/>
<replace file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_PROD_EP_exposed.wsdl">
<replacetoken><![CDATA[localhost:9081]]></replacetoken>
<replacevalue><![CDATA[ws41.nml.com]]></replacevalue>
</replace>
<delete file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_exposed.wsdl"/>
</postcompile>
</buildwar>
</buildear>
<delete file="${project.destination.directory}/${entitlement.war.name}"/>
<exec executable="cmd" output="${project.destination.directory}/${buildlog.prod.name}" append="true">
<!-- C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE must be on your system %PATH% -->
<arg value="/c"/>
<arg value="tf.exe"/>
<arg value="Labels"/>
<arg value="/collection:ntdbph4966m00\INFRA"/>
<arg value="${label}"/>
<arg value="/format:detailed"/>
<arg value="/owner:*"/>
</exec>
<zip destfile="${project.destination.directory}/${enterprise.archive.unixid}-${enterprise.archive.applicationid}-Prod.ear"
basedir="${project.destination.directory}"
includes="${buildlog.prod.name}"
update="true"/>
<antcall target="getConfigDir"/>
<antcall target="productionConfig"/>
<record name="${project.destination.directory}/${buildlog.prod.name}" action="stop"/>
<echo message="PLEASE REMEMBER TO UPDATE THE CONFIG DIRECTORY IF THERE WERE ANY CONFIG CHANGES"/>
</target>
<target name="int" description="Build INT Entitlement Web Service EAR">
<record name="${project.destination.directory}/${buildlog.int.name}" action="start" append="no"/>
<echo message="Build started on: ${tstamped-file-name}"/>
<echo message="Built by : ${user.name}"/>
<echo message="Java version : ${java.version}"/>
<echo message="Project label : ${label}"/>
<echo message="Java source : ${java.source}"/>
<echo message="Java target : ${java.target}"/>
<buildear prefix="entitlementear"
outputName="${enterprise.archive.unixid}-${enterprise.archive.applicationid}Int-Stage.ear"
environment="Int"
compileDebug="true"
includeSource="true">
<postpvcs>
<delete file="${entitlementear.project.workspace.directory}/.project"/>
<delete file="${entitlementear.project.workspace.directory}/.compatibility"/>
</postpvcs>
<buildwar prefix="entitlement"
outputName="${entitlement.war.name}"
environment="Int"
compileDebug="true"
includeSource="true">
<postpvcs>
<mkdir dir="${entitlement.project.workspace.directory}/${project.web.directory}/${java.dest.directory}"/>
<mkdir dir="${entitlement.project.workspace.directory}/${project.lib.directory}"/>
<delete file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/lib/jconn3.jar"/>
</postpvcs>
<postcompile>
<replace file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/ibm-web-bnd.xml">
<replacetoken><![CDATA[default_host]]></replacetoken>
<replacevalue><![CDATA[field_host]]></replacevalue>
</replace>
<replace file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/ibm-web-bnd.xml">
<replacetoken><![CDATA[jdbc/enterpriseods]]></replacetoken>
<replacevalue><![CDATA[jdbc/enterpriseods-entitlementwsint]]></replacevalue>
</replace>
<replace file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/ibm-web-bnd.xml">
<replacetoken><![CDATA[tm/EntitlementWSDeepPingTimerManager]]></replacetoken>
<replacevalue><![CDATA[tm/EntitlementWSDeepPingTimerManagerInt]]></replacevalue>
</replace>
<replace file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/ibm-web-ext.xml">
<replacetoken><![CDATA[/Entitlement]]></replacetoken>
<replacevalue><![CDATA[/EntitlementInt]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/log4j.xml">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/logs/entitlementws]]></replacetoken>
<replacevalue><![CDATA[/nmlwaslocal/edaserv/logs/Entitlementws/entitlementwsInt]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/Entitlement_Spring.xml">
<replacetoken><![CDATA[//hotest/dfs02t/nmltest]]></replacetoken>
<replacevalue><![CDATA[/nmlstage]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/Entitlement_Spring.xml">
<replacetoken><![CDATA[ENTWSRVT]]></replacetoken>
<replacevalue><![CDATA[ENTWSRVS]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/spring.xml">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/config/entitlementws.properties]]></replacetoken>
<replacevalue><![CDATA[/nmlstage/edaserv/config/EntitlementwsInt/entitlementwsInt.properties]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[LDAP_DEV]]></replacetoken>
<replacevalue><![CDATA[LDAP_TEST]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[//hotest/dfs02t/nmltest]]></replacetoken>
<replacevalue><![CDATA[/nmltest]]></replacevalue>
</replace>
<copy file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_internal.wsdl"
toFile="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_INT_EP_internal.wsdl"
overWrite="true"/>
<replace file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_INT_EP_internal.wsdl">
<replacetoken><![CDATA[localhost:9081]]></replacetoken>
<replacevalue><![CDATA[ws41.nml.com]]></replacevalue>
</replace>
<delete file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_internal.wsdl"/>
<copy file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_exposed.wsdl"
toFile="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_INT_EP_exposed.wsdl"
overWrite="true"/>
<replace file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_INT_EP_exposed.wsdl">
<replacetoken><![CDATA[localhost:9081]]></replacetoken>
<replacevalue><![CDATA[ws41test.nml.com]]></replacevalue>
</replace>
<delete file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_exposed.wsdl"/>
</postcompile>
</buildwar>
</buildear>
<delete file="${project.destination.directory}/${entitlement.war.name}"/>
<exec executable="cmd" output="${project.destination.directory}/${buildlog.int.name}" append="true">
<!-- C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE must be on your system %PATH% -->
<arg value="/c"/>
<arg value="tf.exe"/>
<arg value="Labels"/>
<arg value="/collection:ntdbph4966m00\INFRA"/>
<arg value="${label}"/>
<arg value="/format:detailed"/>
<arg value="/owner:*"/>
</exec>
<zip destfile="${project.destination.directory}/${enterprise.archive.unixid}-${enterprise.archive.applicationid}Int-Stage.ear"
basedir="${project.destination.directory}"
includes="${buildlog.int.name}"
update="true"/>
<antcall target="getConfigDir"/>
<antcall target="intConfig"/>
<record name="${project.destination.directory}/${buildlog.int.name}" action="stop"/>
<echo message="PLEASE REMEMBER TO UPDATE THE CONFIG DIRECTORY IF THERE WERE ANY CONFIG CHANGES"/>
</target>
<target name="test1" description="Build TEST1 Entitlement Web Service EAR">
<record name="${project.destination.directory}/${buildlog.test1.name}" action="start" append="no"/>
<echo message="Build started on: ${tstamped-file-name}"/>
<echo message="Built by : ${user.name}"/>
<echo message="Java version : ${java.version}"/>
<echo message="Project label : ${label}"/>
<echo message="Java source : ${java.source}"/>
<echo message="Java target : ${java.target}"/>
<buildear prefix="entitlementear"
outputName="${enterprise.archive.unixid}-${enterprise.archive.applicationid}Test1-Stage.ear"
environment="Test1"
compileDebug="true"
includeSource="true">
<postpvcs>
<delete file="${entitlementear.project.workspace.directory}/.project"/>
<delete file="${entitlementear.project.workspace.directory}/.compatibility"/>
</postpvcs>
<buildwar prefix="entitlement"
outputName="${entitlement.war.name}"
environment="Test1"
compileDebug="true"
includeSource="true">
<postpvcs>
<mkdir dir="${entitlement.project.workspace.directory}/${project.web.directory}/${java.dest.directory}"/>
<mkdir dir="${entitlement.project.workspace.directory}/${project.lib.directory}"/>
<delete file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/lib/jconn3.jar"/>
</postpvcs>
<postcompile>
<replace file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/ibm-web-bnd.xml">
<replacetoken><![CDATA[default_host]]></replacetoken>
<replacevalue><![CDATA[field_host]]></replacevalue>
</replace>
<replace file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/ibm-web-bnd.xml">
<replacetoken><![CDATA[jdbc/enterpriseods]]></replacetoken>
<replacevalue><![CDATA[jdbc/enterpriseods-entitlementws1]]></replacevalue>
</replace>
<replace file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/ibm-web-bnd.xml">
<replacetoken><![CDATA[tm/EntitlementWSDeepPingTimerManager]]></replacetoken>
<replacevalue><![CDATA[tm/EntitlementWSDeepPingTimerManager1]]></replacevalue>
</replace>
<replace file="${entitlement.project.workspace.directory}/${project.web.directory}/WEB-INF/ibm-web-ext.xml">
<replacetoken><![CDATA[/Entitlement]]></replacetoken>
<replacevalue><![CDATA[/Entitlement1]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/log4j.xml">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/logs/entitlementws]]></replacetoken>
<replacevalue><![CDATA[/nmlwaslocal/edaserv/logs/Entitlementws/entitlementws1]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/Entitlement_Spring.xml">
<replacetoken><![CDATA[//hotest/dfs02t/nmltest]]></replacetoken>
<replacevalue><![CDATA[/nmltest]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/spring.xml">
<replacetoken><![CDATA[C:/edas/edaserv/EntitlementWebService/config/entitlementws.properties]]></replacetoken>
<replacevalue><![CDATA[/nmlstage/edaserv/config/Entitlementws1/entitlementws1.properties]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[LDAP_DEV]]></replacetoken>
<replacevalue><![CDATA[LDAP_TEST]]></replacevalue>
</replace>
<replace file="${project.build.directory}/${java.dest.directory}/DICE.properties">
<replacetoken><![CDATA[//hotest/dfs02t/nmltest]]></replacetoken>
<replacevalue><![CDATA[/nmltest]]></replacevalue>
</replace>
<copy file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_internal.wsdl"
toFile="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_TEST1_EP_internal.wsdl"
overWrite="true"/>
<replace file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_TEST1_EP_internal.wsdl">
<replacetoken><![CDATA[localhost:9081]]></replacetoken>
<replacevalue><![CDATA[ws41.nml.com]]></replacevalue>
</replace>
<delete file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_internal.wsdl"/>
<copy file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_exposed.wsdl"
toFile="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_TEST1_EP_exposed.wsdl"
overWrite="true"/>
<replace file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_TEST1_EP_exposed.wsdl">
<replacetoken><![CDATA[localhost:9081]]></replacetoken>
<replacevalue><![CDATA[ws41test.nml.com]]></replacevalue>
</replace>
<delete file="${entitlement.project.workspace.directory}/${project.wsdl.directory}/EntitlementService_v1_exposed.wsdl"/>
</postcompile>
</buildwar>
</buildear>
<delete file="${project.destination.directory}/${entitlement.war.name}"/>
<exec executable="cmd" output="${project.destination.directory}/${buildlog.test1.name}" append="true">
<!-- C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE must be on your system %PATH% -->
<arg value="/c"/>
<arg value="tf.exe"/>
<arg value="Labels"/>
<arg value="/collection:ntdbph4966m00\INFRA"/>
<arg value="${label}"/>
<arg value="/format:detailed"/>
<arg value="/owner:*"/>
</exec>
<zip destfile="${project.destination.directory}/${enterprise.archive.unixid}-${enterprise.archive.applicationid}Test1-Stage.ear"
basedir="${project.destination.directory}"
includes="${buildlog.test.name}"
update="true"/>
<antcall target="getConfigDir"/>
<antcall target="test1Config"/>
<record name="${project.destination.directory}/${buildlog.test1.name}" action="stop"/>
<echo message="PLEASE REMEMBER TO UPDATE THE CONFIG DIRECTORY IF THERE WERE ANY CONFIG CHANGES"/>
</target>
</project> | fc684860bc4ff1cb59eabfc2fbdc7b802599624d | [
"Java",
"Ant Build System",
"INI"
] | 17 | Java | asenguptagithublocalwi/edas-entitlement-migration | e8dbf7fce15a2ac3a224ebc64c385e0b089ef78a | 02d7f0853ab3d4404899af04d3b88e96d62b436e |
refs/heads/master | <file_sep><p align="center">
<img src="https://altyra.com/wp-content/uploads/2018/11/mysql-logo-png-transparent.png" width="200" />
</p>
<h1 align="center">
Mysql
</h1>
## Imagens do Projeto

## Como executar o Projeto
```bash
git clone https://github.com/GustavoNoronhaCursos/mysql
$ cd mysql
```
Bom aprendizado.<br/><file_sep>select * from 'requests';
select pedido from 'requests';<file_sep>INSERT INTO requests ( "nome", "pedido", "endereco", "valor", "data", "status" )
VALUES ("Gustavo", "<NAME>", "<NAME>", 130, 123, "Entregue");<file_sep>select * from 'requests' where id = 1;
select pedido from 'requests' where nome = "Gustavo";<file_sep>DELETE FROM requests WHERE id = 1;<file_sep>UPDATE requests
SET nome = "<NAME>", valor = 140,
WHERE id = 1 or nome = "Gustavo";<file_sep>CREATE TABLE requests (
id INT NOT NULL AUTO_INCREMENT,
nome VARCHAR(500),
pedido VARCHAR(500),
endereco VARCHAR(500),
valor FLOAT(5,2),
data DATE,
status VARCHAR(500)
);<file_sep>create database "requests" | 48d1c11a2fc4f96769d085b1dde5d4111423b9be | [
"Markdown",
"SQL"
] | 8 | Markdown | GustavoNoronhaCursos/mysql | fc551d5b29b10a9786c7cefb75960f26a3db1bb0 | 286d432d1238fa8d6de08cf68d2e43ffe3e752fc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.